Public: anyone can read this; the crew can change it.
Jay Moran's displays are reachable: the display and displays pages, the display builds route, and the arcade host they launch #9383
scout/forge:scout/9208-jay-moran-s-displays-are-reachable-the-d → main 8 commits fork
34 files
changed +2502
−26
docs/design/areas/displays.md added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | # Displays | |
| 2 | ||
| 3 | `/displays` lists the displays the viewer may read in a stock `table`; a row | |
| 4 | opens `/:owner/:name/display`. | |
| 5 | ||
| 6 | The display page is built from stock components only and works with scripts off: | |
| 7 | ||
| 8 | - The display's builds are a `listCard` of `row()`s; each row is a link | |
| 9 | (`?build=<key>`), so choosing a build is navigation. The chosen build's | |
| 10 | player and info panel (`it-*`, the Iterations panel) are drawn under the | |
| 11 | list on the server. | |
| 12 | - A writer's controls are `btn` buttons, each in its own post form: Up and | |
| 13 | Remove on a row, Add or Remove on each pinned build in the side card, and a | |
| 14 | Rename `disclosure` holding the title form. Each posts to | |
| 15 | `…/display/builds` or `…/display/title` and redirects back with a flash. | |
| 16 | - The side card lists the sources' builds as nested `row()`s under one row per | |
| 17 | repository ("N of M"), always open: nothing collapses by script. | |
| 18 | - Other displays are links in a `disclosure`. | |
| 19 | - One accent per page: the Rename form's Save is the only `primary` button. | |
| 20 | ||
| 21 | The one class the page owns is `.display-shots`, the screenshots gallery shown | |
| 22 | through a display (a plain column of pictures; no stock equivalent). No | |
| 23 | `dp-*` classes remain. A phone look is attached to the pull from its preview. |
docs/design/audit.md +2
| @@ -135,6 +135,8 @@ Machine routes are not pages and have no entry: `/audit.csv`, | ||
| 135 | 135 | - `/settings/crew` — `pages/crew.ts` · the named agents and what each may do · `/settings/model`, `/settings/telemetry` · none seen. |
| 136 | 136 | - `/settings/teams` — `pages/teams.ts` · the named crew teams, each with a charter, a dial and members · `/settings/crew` · none seen. |
| 137 | 137 | - `/settings/origins` — `pages/origins.ts` (1,497 lines) · other forges this one reads and mirrors from · `/migrate` · none seen. |
| 138 | - `/displays` — `pages/displays.ts` · the displays on this forge, each a shelf of a repository's builds · `/displays/new`, a display page · none seen. | |
| 139 | - `/displays/new` — `pages/displays.ts` · start a display from a repository · `/displays` · none seen. | |
| 138 | 140 | - `/settings/security` — `pages/security.ts` · the Shield and the evidence an admin needs to act with no AI · `/settings/traffic`, `/settings/backups` · none seen. |
| 139 | 141 | - `/settings/traffic` — `pages/traffic.ts` · who used the answering time in the last 15 minutes · `/settings/usage`, `/settings/telemetry` · none seen. |
| 140 | 142 |
docs/features/displays.md added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | # Displays | |
| 2 | ||
| 3 | A display is a repository with a `display.json` on its default branch: a title, | |
| 4 | a layout (`shelf`, `grid`, `graph`), the sources it reads builds from, and | |
| 5 | optionally `builds`, the chosen builds in order (`owner/name:label`). | |
| 6 | ||
| 7 | - `/displays` lists every display you may read; `/displays/new` makes one. | |
| 8 | - `/:owner/:name/display` is the display, server-rendered. A writer ticks builds | |
| 9 | on the page (`POST …/display/builds`) and edits its title. | |
| 10 | - `PUT /api/v1/repos/:owner/:name/display/builds` with `{"builds": [...]}` (or | |
| 11 | `null` to hold every showcased pin again): `rw` scope, a person who writes | |
| 12 | the repository, one commit on the default branch. A bad list is 422. | |
| 13 | - In the terminal, `Displays` in the palette lists them; enter opens one and, for a writer, space ticks or unticks a build (the same write as the page, live to web viewers); anyone else reads. | |
| 14 | - `…/display/snapshot.html` downloads the shelf as one offline file. | |
| 15 | - The Arcade host (`arcade/host.ts`) serves the site admin's display titled | |
| 16 | `arcade-builds` at its own host. | |
| 17 | ||
| 18 | Not done here: the `/arcade` door, a pin's `/cover` route and the showcase | |
| 19 | and demo editing forms (they need `actions/pin_demos.ts` verbs that are not on main). |
scripts/hollow-allow.ts +1 −12
| @@ -18,15 +18,4 @@ export type Allowed = { | ||
| 18 | 18 | issue: number; |
| 19 | 19 | }; |
| 20 | 20 | |
| 21 | export const ALLOWED: readonly Allowed[] = [ | |
| 22 | { | |
| 23 | orphan: "src/actions/pin_demos.ts#demoDefaults", | |
| 24 | reason: "read by src/display/items.ts, which no page serves until the display route lands", | |
| 25 | issue: 9208, | |
| 26 | }, | |
| 27 | { | |
| 28 | orphan: "src/actions/pin_demos.ts#demoFactsAt", | |
| 29 | reason: "read by src/display/items.ts, which no page serves until the display route lands", | |
| 30 | issue: 9208, | |
| 31 | }, | |
| 32 | ]; | |
| 21 | export const ALLOWED: readonly Allowed[] = []; |
scripts/unreached-allow.json −7
| @@ -1,15 +1,8 @@ | ||
| 1 | 1 | [ |
| 2 | "src/actions/pin_demos.ts", | |
| 3 | 2 | "src/apps/cloud.ts", |
| 4 | "src/arcade/cover.ts", | |
| 5 | "src/arcade/shelf.ts", | |
| 6 | 3 | "src/boards/machine.ts", |
| 7 | 4 | "src/crew/governor_log.ts", |
| 8 | 5 | "src/crew/tries.ts", |
| 9 | "src/display/config.ts", | |
| 10 | "src/display/items.ts", | |
| 11 | "src/display/known.ts", | |
| 12 | "src/display/selections.ts", | |
| 13 | 6 | "src/flow/alarm_drift.ts", |
| 14 | 7 | "src/flow/alarm_unproposed.ts", |
| 15 | 8 | "src/flow/approved_wait.ts", |
src/actions/displays.ts added +199
| @@ -0,0 +1,199 @@ | ||
| 1 | /** | |
| 2 | * A display's writes (`display/config.ts`): save `display.json` to the | |
| 3 | * display repository's default branch, as one commit by the person who | |
| 4 | * edited it, through the file edit every page uses (`contents.ts`), whole | |
| 5 | * or one key of it (its title, its builds); and | |
| 6 | * capture every showcased demo of the display that opens as a file and has | |
| 7 | * no capture yet (`arcade/carts.ts`). A person who writes the display | |
| 8 | * repository, never an agent. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { App } from "../app.ts"; | |
| 12 | import { captureState, startCapture, type CaptureOptions } from "../arcade/carts.ts"; | |
| 13 | import { canWrite, type Repo } from "../core/repos.ts"; | |
| 14 | import type { User } from "../core/users.ts"; | |
| 15 | import { readFileAt } from "../apps/checkout.ts"; | |
| 16 | import { checkDisplay, DISPLAY_FILE, parseBuilds, parseDisplay, readDisplay } from "../display/config.ts"; | |
| 17 | import { exactRefOid } from "../git/branches.ts"; | |
| 18 | import { repoDir } from "../git/repos.ts"; | |
| 19 | import { displayItems } from "../display/items.ts"; | |
| 20 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 21 | import { requireWriter, type AccessError } from "./access.ts"; | |
| 22 | import { editFiles } from "./contents.ts"; | |
| 23 | ||
| 24 | /** A person who writes the display repository. */ | |
| 25 | function displayWriter(app: App, actor: User | undefined, repo: Repo): Result<User, AccessError> { | |
| 26 | const writer = requireWriter(app, actor, repo); | |
| 27 | if (!writer.ok) return writer; | |
| 28 | return writer.value.kind === "agent" ? err("forbidden") : writer; | |
| 29 | } | |
| 30 | ||
| 31 | export type SaveDisplayError = | |
| 32 | | AccessError | |
| 33 | | { readonly kind: "invalid_display"; readonly message: string } | |
| 34 | | { readonly kind: "moved" } | |
| 35 | | { readonly kind: "protected_branch" } | |
| 36 | | { readonly kind: "commit_failed"; readonly message: string }; | |
| 37 | ||
| 38 | /** | |
| 39 | * Write `text` as `display.json` on the default branch, refused unless it | |
| 40 | * parses and the branch is still at `expectTip` (when one is given). | |
| 41 | */ | |
| 42 | export async function saveDisplay( | |
| 43 | app: App, | |
| 44 | actor: User | undefined, | |
| 45 | repo: Repo, | |
| 46 | text: string, | |
| 47 | expectTip: string | undefined, | |
| 48 | ): Promise<Result<{ readonly commit: string; readonly created: boolean }, SaveDisplayError>> { | |
| 49 | const writer = displayWriter(app, actor, repo); | |
| 50 | if (!writer.ok) return writer; | |
| 51 | const parsed = parseDisplay(text); | |
| 52 | if (!parsed.ok) return err({ kind: "invalid_display", message: parsed.error }); | |
| 53 | const created = (await readDisplay(app, repo)) === undefined; | |
| 54 | const edited = await editFiles(app, writer.value, repo, { | |
| 55 | branch: repo.defaultBranch, | |
| 56 | message: `${created ? "Create" : "Update"} ${DISPLAY_FILE}`, | |
| 57 | files: [{ path: DISPLAY_FILE, content: text }], | |
| 58 | ...(expectTip === undefined || expectTip === "" ? {} : { expectTip }), | |
| 59 | }); | |
| 60 | if (!edited.ok) { | |
| 61 | const e = edited.error; | |
| 62 | if (typeof e === "string") { | |
| 63 | if (e === "not_found" || e === "unauthorized" || e === "forbidden") return err(e); | |
| 64 | return err({ kind: "commit_failed", message: e }); | |
| 65 | } | |
| 66 | if (e.kind === "branch_moved") return err({ kind: "moved" }); | |
| 67 | if (e.kind === "protected_branch") return err({ kind: "protected_branch" }); | |
| 68 | return err({ kind: "commit_failed", message: e.kind }); | |
| 69 | } | |
| 70 | await checkDisplay(app, repo); | |
| 71 | return ok({ commit: edited.value.commit.commitOid, created }); | |
| 72 | } | |
| 73 | ||
| 74 | /** | |
| 75 | * Change one key of `display.json` on the default branch and save it as one | |
| 76 | * commit, leased on the tip it was read at; the rest of the file stays. | |
| 77 | */ | |
| 78 | async function rewriteDisplay( | |
| 79 | app: App, | |
| 80 | writer: User, | |
| 81 | repo: Repo, | |
| 82 | change: (raw: Record<string, unknown>) => void, | |
| 83 | ): Promise<Result<{ readonly commit: string }, SaveDisplayError | { readonly kind: "no_display" }>> { | |
| 84 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 85 | const tip = await exactRefOid(dir, `refs/heads/${repo.defaultBranch}`); | |
| 86 | const text = tip === undefined ? undefined : await readFileAt(dir, tip, DISPLAY_FILE); | |
| 87 | if (tip === undefined || text === undefined) return err({ kind: "no_display" }); | |
| 88 | const parsed = parseDisplay(text); | |
| 89 | if (!parsed.ok) return err({ kind: "invalid_display", message: parsed.error }); | |
| 90 | const raw = JSON.parse(text) as Record<string, unknown>; | |
| 91 | change(raw); | |
| 92 | const saved = await saveDisplay(app, writer, repo, `${JSON.stringify(raw, null, 2)}\n`, tip); | |
| 93 | return saved.ok ? ok({ commit: saved.value.commit }) : saved; | |
| 94 | } | |
| 95 | ||
| 96 | export type SetDisplayTitleError = SaveDisplayError | { readonly kind: "no_display" }; | |
| 97 | ||
| 98 | /** | |
| 99 | * Set the display's title: `title` in `display.json`, one commit through | |
| 100 | * `saveDisplay`; the rest of the file stays. The title `arcade-builds` on a | |
| 101 | * site admin's repository makes it the Arcade (`display/known.ts`), whose | |
| 102 | * pick the commit's push event reads again. | |
| 103 | */ | |
| 104 | export async function setDisplayTitle( | |
| 105 | app: App, | |
| 106 | actor: User | undefined, | |
| 107 | displayRepo: Repo, | |
| 108 | title: string, | |
| 109 | ): Promise<Result<{ readonly commit: string; readonly title: string }, SetDisplayTitleError>> { | |
| 110 | const writer = displayWriter(app, actor, displayRepo); | |
| 111 | if (!writer.ok) return writer; | |
| 112 | const saved = await rewriteDisplay(app, writer.value, displayRepo, (raw) => { | |
| 113 | raw.title = title; | |
| 114 | }); | |
| 115 | return saved.ok ? ok({ commit: saved.value.commit, title }) : saved; | |
| 116 | } | |
| 117 | ||
| 118 | export type SetDisplayBuildsError = | |
| 119 | | SaveDisplayError | |
| 120 | | { readonly kind: "no_display" } | |
| 121 | | { readonly kind: "invalid_builds"; readonly message: string }; | |
| 122 | ||
| 123 | /** | |
| 124 | * Set the display's chosen builds and their order: `builds` in | |
| 125 | * `display.json`, `owner/name:label` each, written as one commit through | |
| 126 | * `saveDisplay`; null removes the key, so the display holds every showcased | |
| 127 | * pin of its sources again. The rest of the file stays as it is. A build | |
| 128 | * need not be showcased: the display decides, and `display/items.ts` keeps | |
| 129 | * one that is not from anyone who cannot read its repository. | |
| 130 | */ | |
| 131 | export async function setDisplayBuilds( | |
| 132 | app: App, | |
| 133 | actor: User | undefined, | |
| 134 | displayRepo: Repo, | |
| 135 | builds: readonly string[] | null, | |
| 136 | ): Promise<Result<{ readonly commit: string; readonly builds: readonly string[] | null }, SetDisplayBuildsError>> { | |
| 137 | const writer = displayWriter(app, actor, displayRepo); | |
| 138 | if (!writer.ok) return writer; | |
| 139 | const checked = parseBuilds(builds ?? undefined); | |
| 140 | if (!checked.ok) return err({ kind: "invalid_builds", message: `${DISPLAY_FILE}: ${checked.error}` }); | |
| 141 | const saved = await rewriteDisplay(app, writer.value, displayRepo, (raw) => { | |
| 142 | if (checked.value === undefined) delete raw.builds; | |
| 143 | else raw.builds = checked.value; | |
| 144 | }); | |
| 145 | if (!saved.ok) return saved; | |
| 146 | app.bus.append({ | |
| 147 | kind: "display.builds", | |
| 148 | repoId: displayRepo.id, | |
| 149 | actorId: writer.value.id, | |
| 150 | payload: { commit: saved.value.commit, builds: checked.value ?? null }, | |
| 151 | }); | |
| 152 | return ok({ commit: saved.value.commit, builds: checked.value ?? null }); | |
| 153 | } | |
| 154 | ||
| 155 | export type CaptureDisplayError = AccessError | "no_display" | "invalid_display"; | |
| 156 | ||
| 157 | export interface CaptureDisplayDone { | |
| 158 | /** The demos whose capture started. */ | |
| 159 | readonly started: readonly string[]; | |
| 160 | /** File demos with no capture that the person may not capture: they do not write the source. */ | |
| 161 | readonly skipped: number; | |
| 162 | } | |
| 163 | ||
| 164 | /** | |
| 165 | * Start a capture for each showcased file demo of the display with none | |
| 166 | * kept and none running, as the person who asked; a demo whose repository | |
| 167 | * they do not write is skipped. | |
| 168 | */ | |
| 169 | export async function captureDisplay( | |
| 170 | app: App, | |
| 171 | actor: User | undefined, | |
| 172 | repo: Repo, | |
| 173 | options: CaptureOptions = {}, | |
| 174 | ): Promise<Result<CaptureDisplayDone, CaptureDisplayError>> { | |
| 175 | const writer = displayWriter(app, actor, repo); | |
| 176 | if (!writer.ok) return writer; | |
| 177 | const config = await readDisplay(app, repo); | |
| 178 | if (config === undefined) return err("no_display"); | |
| 179 | if (!config.ok) return err("invalid_display"); | |
| 180 | const started: string[] = []; | |
| 181 | let skipped = 0; | |
| 182 | for (const item of await displayItems(app, repo, config.value, writer.value)) { | |
| 183 | if (item.launch !== "file" || item.captured !== undefined) continue; | |
| 184 | if (captureState(app, item.repo, item.pin.oid, item.demo.page).state === "capturing") continue; | |
| 185 | if (!canWrite(app.db, item.repo, writer.value)) { | |
| 186 | skipped++; | |
| 187 | continue; | |
| 188 | } | |
| 189 | void startCapture(app, writer.value, item.repo, item.pin.oid, item.demo.page, options); | |
| 190 | started.push(item.key); | |
| 191 | } | |
| 192 | app.bus.append({ | |
| 193 | kind: "display.captured", | |
| 194 | repoId: repo.id, | |
| 195 | actorId: writer.value.id, | |
| 196 | payload: { started: started.length, skipped }, | |
| 197 | }); | |
| 198 | return ok({ started, skipped }); | |
| 199 | } |
src/arcade/arcade.html added +338
| @@ -0,0 +1,338 @@ | ||
| 1 | ||
| 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 | : #120a26; | |
| 11 | : #fff6e0; | |
| 12 | : #9a90c0; | |
| 13 | : #ffd200; | |
| 14 | : #ff4fa0; | |
| 15 | : #9bbc0f; | |
| 16 | : #08040f; | |
| 17 | : "Press Start 2P", ui-monospace, Menlo, monospace; | |
| 18 | } | |
| 19 | * { box-sizing: border-box; } | |
| 20 | html, body { margin: 0; min-height: 100%; color: var(); font: 11px/1.5 var(); 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(); font-size: 10px; color: var(); | |
| 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(); border: 5px solid var(); | |
| 41 | box-shadow: inset 6px 6px 0 var(), inset -6px -6px 0 var(), 8px 8px 0 var(); } | |
| 42 | .shell::before { content: ""; position: absolute; left: 50%; top: 4px; width: 46px; height: 5px; margin-left: -23px; background: var(); box-shadow: 0 0 0 2px var(); } | |
| 43 | .screw { position: absolute; bottom: 52px; width: 9px; height: 9px; border-radius: 50%; background: var(); box-shadow: 0 0 0 2px var(), inset -2px -2px 0 var(); } | |
| 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(); | |
| 46 | background: repeating-linear-gradient(0deg, var() 0 5px, var() 5px 7px, var() 7px 10px); } | |
| 47 | .sticker { position: relative; aspect-ratio: 1; background: #000; border: 5px solid #fff; box-shadow: 0 0 0 4px var(); 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(), -1px -1px 0 var(); background: linear-gradient(transparent, rgba(0,0,0,.75)); text-align: left; } | |
| 51 | .cart.loading { top: 230px; transform: translateZ(0) scale(.92) ; } | |
| 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(); | |
| 56 | box-shadow: inset 0 8px 0 #6a6488, inset 0 -10px 0 #1c1828, 10px 10px 0 var(); } | |
| 57 | .console .slot { position: absolute; left: 50%; top: -6px; width: 250px; height: 22px; margin-left: -125px; background: #05030a; border: 6px solid var(); 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(); } | |
| 61 | .led { width: 14px; height: 14px; border-radius: 50%; background: #5a1010; box-shadow: 0 0 0 3px var(); } | |
| 62 | .led.on { background: #ff3a3a; box-shadow: 0 0 0 3px var(), 0 0 14px #ff3a3a; } | |
| 63 | .led.go { background: #3aff6a; box-shadow: 0 0 0 3px var(), 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(); } | |
| 65 | .lcd { flex: 1; min-width: 220px; background: #9bbc0f; color: #0f380f; border: 5px solid var(); 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(); box-shadow: inset 3px 3px 0 #55507a, 4px 4px 0 var(); } | |
| 69 | .switch[aria-pressed="true"] { background: var(); color: var(); box-shadow: inset 3px 3px 0 #fff2a0, 2px 2px 0 var(); transform: translate(2px, 2px); } | |
| 70 | .big { cursor: pointer; padding: 14px 18px; font-size: 12px; border: 5px solid var(); 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(); } | |
| 72 | .eject { background: #c8c0e0; color: var(); box-shadow: inset 4px 4px 0 #fff, inset -4px -4px 0 #8a80a8, 5px 5px 0 var(); } | |
| 73 | .big:active { transform: translate(4px, 4px); box-shadow: none; } | |
| 74 | .switch:focus-visible, .big:focus-visible, .cart:focus-visible { outline: 4px solid var(); outline-offset: 4px; } | |
| 75 | footer { position: relative; text-align: center; color: var(); font-size: 9px; padding: 22px 16px 30px; } | |
| 76 | footer a { color: var(); text-decoration: none; margin-left: 14px; } | |
| 77 | footer a:hover, footer a:focus-visible { text-decoration: underline; } | |
| 78 | .empty { text-align: center; padding-top: 80px; } | |
| 79 | @media (max-width: 600px) { .stage { height: 290px; } .cart { width: 170px; margin-left: -85px; } .cart.loading { top: 200px; } } | |
| 80 | ||
| 81 | /* The player: the game fills the screen, with a way back. */ | |
| 82 | #player { position: fixed; inset: 0; background: #000; display: none; z-index: 10; } | |
| 83 | #player.on { display: block; } | |
| 84 | #player iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; } | |
| 85 | #back { position: absolute; top: 10px; left: 10px; z-index: 4; cursor: pointer; font-size: 10px; color: var(); | |
| 86 | background: #2c283c; border: 4px solid var(); box-shadow: 3px 3px 0 var(); padding: 6px 9px; opacity: .6; } | |
| 87 | #back:hover, #back:focus-visible { opacity: 1; } | |
| 88 | /* The jbox boot tag plays over the screen while a cartridge loads. */ | |
| 89 | #boot { position: absolute; inset: 0; display: none; place-items: center; background: #1b1b25; z-index: 1; transition: opacity .25s; } | |
| 90 | #boot.on { display: grid; } | |
| 91 | #boot.out { opacity: 0; } | |
| 92 | #boot canvas { display: block; image-rendering: pixelated; } | |
| 93 | /* Opened from a link, the cartridge waits for a press so its power-on chord can play. */ | |
| 94 | #power { position: absolute; inset: 0; display: none; place-items: center; z-index: 3; background: #1b1b25; color: var(); cursor: pointer; text-align: center; font-size: 11px; } | |
| 95 | #power.on { display: grid; } | |
| 96 | #power b { display: block; font-size: 32px; margin-bottom: 14px; } | |
| 97 | </style> | |
| 98 | </head> | |
| 99 | <body> | |
| 100 | <header id="topline">JBOX • BROWSER ARCADE</header> | |
| 101 | <main id="games"><p class="empty">LOADING…</p><noscript><p class="empty">THE ARCADE NEEDS JAVASCRIPT TO PLAY CARTRIDGES.</p></noscript></main> | |
| 102 | <footer>◀ ▶ CHOOSE · Z X BUILD · ENTER POWER<a id="export" href="snapshot.html" download>⤓ EXPORT SNAPSHOT</a></footer> | |
| 103 | ||
| 104 | <div id="player" aria-hidden="true"> | |
| 105 | <button id="back" type="button">◀ ARCADE</button> | |
| 106 | <div id="boot"><canvas id="tag"></canvas></div> | |
| 107 | <div id="power"><div><b>⏻</b>PRESS ANY KEY TO POWER ON</div></div> | |
| 108 | <iframe id="screen" title="Game" allow="autoplay *; fullscreen *; gamepad *"></iframe> | |
| 109 | </div> | |
| 110 | ||
| 111 | <script type="module"> | |
| 112 | import { jboxScale, playJboxSpin } from './boot/jbox-spin.js'; | |
| 113 | const shelfEl = document.getElementById('games'); | |
| 114 | const player = document.getElementById('player'); | |
| 115 | const screen = document.getElementById('screen'); | |
| 116 | const bootEl = document.getElementById('boot'); | |
| 117 | const tag = document.getElementById('tag'); | |
| 118 | const powerEl = document.getElementById('power'); | |
| 119 | /** Bytes as a short size: 38 KB, 1.2 MB. */ | |
| 120 | const size = (n) => (!n ? '' : n < 1e6 ? `${Math.round(n / 1024)} KB` : `${(n / 1048576).toFixed(1)} MB`); | |
| 121 | // A single-file bundle (a snapshot) carries the shelf, carts and covers inside the | |
| 122 | // page as window.__ARCADE__; the forge's own display page carries the shelf with | |
| 123 | // absolute addresses. Served as a folder, the arcade reads its files instead. | |
| 124 | const BUNDLE = window.__ARCADE__; | |
| 125 | const HOME = document.title; | |
| 126 | const urls = new Map(); | |
| 127 | /** Where a cart or label lives: its path, or a blob or data URL from the bundle. */ | |
| 128 | const url = (path) => { | |
| 129 | if (!BUNDLE || !path || /^(data:|https?:|\/)/.test(path)) return path; | |
| 130 | if (!urls.has(path)) { | |
| 131 | const label = BUNDLE.labels[path]; | |
| 132 | urls.set(path, label ?? URL.createObjectURL(new Blob([BUNDLE.carts[path] ?? ''], { type: 'text/html' }))); | |
| 133 | } | |
| 134 | return urls.get(path); | |
| 135 | }; | |
| 136 | if (BUNDLE?.snapshot) document.getElementById('topline').textContent = BUNDLE.snapshot; | |
| 137 | // A snapshot is the export: it has nothing further to export. | |
| 138 | if (BUNDLE?.exportHref) document.getElementById('export').href = BUNDLE.exportHref; | |
| 139 | else if (BUNDLE) document.getElementById('export').remove(); | |
| 140 | const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]); | |
| 141 | ||
| 142 | /** Cart plastic by game: body, highlight and shadow. Unknown games get grey. */ | |
| 143 | const PLASTIC = { | |
| 144 | 'krazy-karts': ['#e8322a', '#ff7a6a', '#8a1410'], | |
| 145 | 'nova-lantern': ['#5a3ab8', '#8a6ae8', '#2a1a68'], | |
| 146 | ballistics: ['#f0a020', '#ffd870', '#9a5a0a'], | |
| 147 | 'krazy-karts-fiesta': ['#ff7a1a', '#ffb060', '#a83e00'], | |
| 148 | 'krazy-karts-london': ['#4a6a8a', '#7a9aba', '#24384c'], | |
| 149 | 'krazy-karts-chicago': ['#2a8ad8', '#6ac0ff', '#124a7a'], | |
| 150 | 'nova-moves': ['#1f8a6a', '#4ac89a', '#0e4a38'], | |
| 151 | }; | |
| 152 | const plastic = (id) => PLASTIC[id] ?? ['#8a8a96', '#c0c0cc', '#4a4a56']; | |
| 153 | ||
| 154 | /** Wait for a key or click: browsers only play sound after one. */ | |
| 155 | function powerPress() { | |
| 156 | powerEl.classList.add('on'); | |
| 157 | return new Promise((done) => { | |
| 158 | const go = (e) => { | |
| 159 | e.preventDefault(); | |
| 160 | removeEventListener('keydown', go); | |
| 161 | powerEl.removeEventListener('pointerdown', go); | |
| 162 | powerEl.classList.remove('on'); | |
| 163 | done(); | |
| 164 | }; | |
| 165 | addEventListener('keydown', go); | |
| 166 | powerEl.addEventListener('pointerdown', go); | |
| 167 | }); | |
| 168 | } | |
| 169 | ||
| 170 | /** The jbox tag spins up while the cartridge loads behind it. `sound` needs a click. */ | |
| 171 | async function bootCartridge(sound) { | |
| 172 | bootEl.classList.remove('out'); | |
| 173 | bootEl.classList.add('on'); | |
| 174 | const s = jboxScale(innerWidth * 0.8, innerHeight * 0.8); | |
| 175 | tag.style.width = `${160 * s}px`; | |
| 176 | tag.style.height = `${144 * s}px`; | |
| 177 | await playJboxSpin(tag, { sound }); | |
| 178 | } | |
| 179 | ||
| 180 | let opener = null; | |
| 181 | async function play(game, build, push = true) { | |
| 182 | opener = document.activeElement instanceof HTMLElement ? document.activeElement : null; | |
| 183 | if (push) history.pushState({ game: game.id, build: build.id }, '', `#${game.id}/${build.id}`); | |
| 184 | player.classList.add('on'); | |
| 185 | player.setAttribute('aria-hidden', 'false'); | |
| 186 | document.getElementById('back').focus(); | |
| 187 | document.title = `${game.name} · ${build.name}`; | |
| 188 | const ready = new Promise((r) => (screen.onload = r)); | |
| 189 | // Replace, so the frame's own loads never land in the browser's history. | |
| 190 | screen.contentWindow.location.replace(BUNDLE ? url(build.file) : new URL(build.file, location.href).href); | |
| 191 | // A click on a cartridge already counts as the press. A link has to ask for one. | |
| 192 | if (!push) await powerPress(); | |
| 193 | await Promise.all([ready, bootCartridge(true)]); | |
| 194 | bootEl.classList.add('out'); | |
| 195 | screen.focus(); | |
| 196 | setTimeout(() => bootEl.classList.remove('on', 'out'), 260); | |
| 197 | } | |
| 198 | ||
| 199 | function stop() { | |
| 200 | player.classList.remove('on'); | |
| 201 | player.setAttribute('aria-hidden', 'true'); | |
| 202 | screen.contentWindow.location.replace('about:blank'); | |
| 203 | document.title = HOME; | |
| 204 | if (opener?.isConnected) opener.focus(); | |
| 205 | shelfEl.querySelector('.loading')?.classList.remove('loading'); | |
| 206 | shelfEl.querySelector('.led')?.classList.replace('go', 'on'); | |
| 207 | } | |
| 208 | ||
| 209 | document.getElementById('back').addEventListener('click', () => { | |
| 210 | history.pushState(null, '', location.pathname); | |
| 211 | stop(); | |
| 212 | }); | |
| 213 | ||
| 214 | const games = BUNDLE ? BUNDLE.games : await fetch('games.json').then((r) => r.json()).catch(() => []); | |
| 215 | // Builds stand in the display's order. | |
| 216 | // A build with no cover of its own gets the house cover, drawn from its page's picture. | |
| 217 | /*COVER_JS*/ | |
| 218 | if (games.some((g) => g.builds.some((b) => !b.label))) { | |
| 219 | await Promise.race([document.fonts?.load('700 44px Ubuntu'), new Promise((r) => setTimeout(r, 1500))]).catch(() => {}); | |
| 220 | const tpl = await loadImage(url('cover-template.png')); | |
| 221 | for (const g of games) for (const b of g.builds) { | |
| 222 | if (b.label) continue; | |
| 223 | const c = document.createElement('canvas'); | |
| 224 | drawCover(c, b.art ? await loadImage(url(b.art)) : null, tpl, g.name, b.name); | |
| 225 | b.label = c.toDataURL('image/png'); | |
| 226 | b.titled = true; | |
| 227 | } | |
| 228 | } | |
| 229 | let gi = 0; | |
| 230 | const bi = games.map(() => 0); | |
| 231 | const find = (gid, bid) => { | |
| 232 | const g = games.find((x) => x.id === gid); | |
| 233 | const b = g?.builds.find((x) => x.id === bid); | |
| 234 | return g && b ? [g, b] : null; | |
| 235 | }; | |
| 236 | ||
| 237 | // The carousel of carts is built once; `draw` turns it and refreshes the console. | |
| 238 | if (!games.length) shelfEl.innerHTML = '<p class="empty">THE SHELF IS EMPTY</p>'; | |
| 239 | else { | |
| 240 | shelfEl.innerHTML = ` | |
| 241 | <div class="stage">${games.map((g, i) => { | |
| 242 | const [body, hi, lo] = plastic(g.id); | |
| 243 | return `<button type="button" class="cart" data-i="${i}" style="--body:${body};--hi:${hi};--lo:${lo}" aria-label="${esc(g.name)}"> | |
| 244 | <div class="shell"><div class="sticker"><img alt=""><div class="logo">${esc(g.name).toUpperCase()}</div></div> | |
| 245 | <span class="screw l"></span><span class="screw r"></span><div class="grip"></div></div></button>`; | |
| 246 | }).join('')}</div> | |
| 247 | <section class="console" aria-label="Console"> | |
| 248 | <div class="slot"></div> | |
| 249 | <div class="row"><span class="led on"></span><span class="badge">JBOX</span><span class="grille"></span></div> | |
| 250 | <div class="row"><div class="lcd" id="lcd"></div><div class="switches" id="switches"></div></div> | |
| 251 | <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> | |
| 252 | </section>`; | |
| 253 | } | |
| 254 | ||
| 255 | function draw() { | |
| 256 | if (!games.length) return; | |
| 257 | const g = games[gi]; | |
| 258 | const b = g.builds[bi[gi]]; | |
| 259 | shelfEl.querySelectorAll('.cart').forEach((c, i) => { | |
| 260 | const d = i - gi; | |
| 261 | const x = games[i]; | |
| 262 | const xb = x.builds[bi[i]]; | |
| 263 | const img = c.querySelector('img'); | |
| 264 | if (xb.label && img.dataset.label !== xb.label) { | |
| 265 | img.dataset.label = xb.label; | |
| 266 | img.src = url(xb.label); | |
| 267 | } | |
| 268 | // Cover art carries its own title; a plain snapshot gets the game's name. | |
| 269 | c.querySelector('.logo').hidden = Boolean(xb.titled); | |
| 270 | // Far carts turn no more than 70°, so none shows its back. | |
| 271 | 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)`; | |
| 272 | c.style.filter = d ? 'brightness(.5)' : 'none'; | |
| 273 | c.style.zIndex = 10 - Math.abs(d); | |
| 274 | c.tabIndex = d ? -1 : 0; | |
| 275 | }); | |
| 276 | 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()}` : ''}`; | |
| 277 | 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(''); | |
| 278 | const save = document.getElementById('save'); | |
| 279 | // A page served elsewhere names where it downloads from. | |
| 280 | save.href = url(b.save ?? b.file); | |
| 281 | save.download = b.download ?? `${g.id}-${b.id}.html`; | |
| 282 | } | |
| 283 | ||
| 284 | /** Drop the front cart into the slot, light the LED, then boot it. */ | |
| 285 | function insert() { | |
| 286 | const g = games[gi]; | |
| 287 | shelfEl.querySelector(`.cart[data-i="${gi}"]`).classList.add('loading'); | |
| 288 | shelfEl.querySelector('.led').classList.replace('on', 'go'); | |
| 289 | setTimeout(() => play(g, g.builds[bi[gi]]), 380); | |
| 290 | } | |
| 291 | ||
| 292 | shelfEl.addEventListener('click', (e) => { | |
| 293 | const cart = e.target.closest('.cart'); | |
| 294 | const sw = e.target.closest('.switch'); | |
| 295 | if (cart) { | |
| 296 | const i = Number(cart.dataset.i); | |
| 297 | if (i === gi) insert(); | |
| 298 | else { gi = i; draw(); } | |
| 299 | } else if (sw) { | |
| 300 | bi[gi] = Number(sw.dataset.build); | |
| 301 | draw(); | |
| 302 | } else if (e.target.closest('#go')) insert(); | |
| 303 | }); | |
| 304 | ||
| 305 | // Pad controls: left and right turn the carousel, Z and X flip the build, Enter powers on. | |
| 306 | addEventListener('keydown', (e) => { | |
| 307 | if (player.classList.contains('on') || !games.length) return; | |
| 308 | if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') { | |
| 309 | e.preventDefault(); | |
| 310 | gi = Math.min(games.length - 1, Math.max(0, gi + (e.key === 'ArrowLeft' ? -1 : 1))); | |
| 311 | draw(); | |
| 312 | } else if (e.key === 'z' || e.key === 'x') { | |
| 313 | const n = games[gi].builds.length; | |
| 314 | bi[gi] = (bi[gi] + (e.key === 'x' ? 1 : n - 1)) % n; | |
| 315 | draw(); | |
| 316 | } else if (e.key === 'Enter' && !e.target.closest?.('a, .switch, #go, .cart')) { | |
| 317 | e.preventDefault(); | |
| 318 | insert(); | |
| 319 | } | |
| 320 | }); | |
| 321 | draw(); | |
| 322 | ||
| 323 | // Links like #krazy-karts/alpha-1025 open a cartridge directly. Back returns to the shelf. | |
| 324 | const route = () => { | |
| 325 | const [gid, bid] = location.hash.slice(1).split('/'); | |
| 326 | const hit = gid && find(gid, bid); | |
| 327 | if (hit) { | |
| 328 | gi = games.indexOf(hit[0]); | |
| 329 | bi[gi] = hit[0].builds.indexOf(hit[1]); | |
| 330 | draw(); | |
| 331 | play(...hit, false); | |
| 332 | } else stop(); | |
| 333 | }; | |
| 334 | addEventListener('popstate', route); | |
| 335 | route(); | |
| 336 | </script> | |
| 337 | </body> | |
| 338 | </html> |
src/arcade/host.ts added +272
| @@ -0,0 +1,272 @@ | ||
| 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 { securityFloor } from "../http/respond.ts"; | |
| 37 | import { pageFile, readArt, readCapture } from "./carts.ts"; | |
| 38 | import { COVER_JS } from "./cover.ts"; | |
| 39 | import { shelfOf, type Shelf } from "./shelf.ts"; | |
| 40 | import { snapshotFile } from "./snapshot.ts"; | |
| 41 | ||
| 42 | /** The app name the Arcade answers at. */ | |
| 43 | export const ARCADE_SLUG = "arcade"; | |
| 44 | ||
| 45 | /** Whether a request's `Host` is the Arcade's. */ | |
| 46 | export function isArcadeHost(host: string | null, domain: string): boolean { | |
| 47 | if (host === null) return false; | |
| 48 | const parsed = parseAppHost(host, domain); | |
| 49 | return parsed !== undefined && parsed.slug === ARCADE_SLUG && parsed.env === "production" && !parsed.nested; | |
| 50 | } | |
| 51 | ||
| 52 | /** Where the Arcade is reached, as the runtime addresses an app. */ | |
| 53 | export function arcadeUrl(runtime: AppsRuntime): string { | |
| 54 | const { scheme, publicPort, domain } = runtime.options; | |
| 55 | const port = | |
| 56 | publicPort === undefined || (scheme === "http" && publicPort === 80) || (scheme === "https" && publicPort === 443) | |
| 57 | ? "" | |
| 58 | : `:${publicPort}`; | |
| 59 | return `${scheme}://${ARCADE_SLUG}${appHostSuffix(domain)}${port}`; | |
| 60 | } | |
| 61 | ||
| 62 | /** Whether the forge has an Arcade: apps run and a site admin's display is titled `arcade-builds`. */ | |
| 63 | export function arcadeOn(app: App): boolean { | |
| 64 | return appsRuntime(app) !== undefined && arcadeRepoKnown(app) !== undefined; | |
| 65 | } | |
| 66 | ||
| 67 | /** The Arcade's address when the forge has one. */ | |
| 68 | export function arcadeHome(app: App): string | undefined { | |
| 69 | const runtime = appsRuntime(app); | |
| 70 | return runtime !== undefined && arcadeRepoKnown(app) !== undefined ? arcadeUrl(runtime) : undefined; | |
| 71 | } | |
| 72 | ||
| 73 | const file = (name: string): string => readFileSync(new URL(name, import.meta.url), "utf8"); | |
| 74 | let page: string | undefined; | |
| 75 | let boot: string | undefined; | |
| 76 | let template: Uint8Array | undefined; | |
| 77 | ||
| 78 | /** The Arcade's page, with the house cover drawing spliced in. */ | |
| 79 | export function arcadePage(): string { | |
| 80 | page ??= file("./arcade.html").replace("/*COVER_JS*/", () => COVER_JS); | |
| 81 | return page; | |
| 82 | } | |
| 83 | export const bootScript = (): string => (boot ??= file("./jbox-spin.js")); | |
| 84 | export const coverTemplateBytes = (): Uint8Array => | |
| 85 | (template ??= new Uint8Array(readFileSync(new URL("./cover-template.png", import.meta.url)))); | |
| 86 | ||
| 87 | const IMPORT_LINE = "import { jboxScale, playJboxSpin } from './boot/jbox-spin.js';"; | |
| 88 | const escapeText = (s: string): string => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]!); | |
| 89 | ||
| 90 | /** | |
| 91 | * The shelf page for a display: its title, its producer, and — for a page | |
| 92 | * that carries its shelf inside it — the data, with the boot tag inline. | |
| 93 | */ | |
| 94 | export function shelfPage(o: { title: string; producer: string | undefined; data?: unknown; tabTitle?: string; bar?: string; nonce?: string }): string { | |
| 95 | let out = arcadePage(); | |
| 96 | // The forge's own bar above the shelf (a writer's Edit display), outside the arcade's frame. | |
| 97 | if (o.bar !== undefined) out = out.replace('<body>\n <header id="topline">', () => `<body>\n ${o.bar}\n <header id="topline">`); | |
| 98 | const topline = o.producer === undefined ? o.title : `${o.producer} • ${o.title}`; | |
| 99 | out = out | |
| 100 | .replace("<title>Browser Arcade</title>", () => `<title>${escapeText(o.tabTitle ?? o.title)}</title>`) | |
| 101 | .replace('<header id="topline">JBOX • BROWSER ARCADE</header>', () => `<header id="topline">${escapeText(topline.toUpperCase())}</header>`) | |
| 102 | .replace('<button id="back" type="button">◀ ARCADE</button>', () => `<button id="back" type="button">◀ ${escapeText(o.title.toUpperCase())}</button>`); | |
| 103 | const tagged = (html: string): string => (o.nonce === undefined ? html : html.replace(/<script(?=[ >])/g, `<script nonce="${o.nonce}"`)); | |
| 104 | if (o.data === undefined) return tagged(out); | |
| 105 | if (!out.includes(IMPORT_LINE)) throw new Error("the Arcade page no longer imports the boot tag as expected"); | |
| 106 | // The boot tag goes inline, as plain script in the page's module. | |
| 107 | out = out.replace(IMPORT_LINE, () => bootScript().replace(/^export /gm, "")); | |
| 108 | // "<" escaped, so a cart's own </script> cannot end this script early. | |
| 109 | const data = JSON.stringify(o.data).replace(/</g, "\\u003c"); | |
| 110 | return tagged(out.replace('<script type="module">', () => `<script>window.__ARCADE__ = ${data};</script>\n <script type="module">`)); | |
| 111 | } | |
| 112 | ||
| 113 | /** The page's own policy: its inline module by nonce, no third party, carts in frames from itself. */ | |
| 114 | const pagePolicy = (nonce: string): string => | |
| 115 | `default-src 'self'; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'unsafe-inline'; ` + | |
| 116 | "font-src 'self'; img-src 'self' data: blob:; frame-src 'self' blob:; media-src 'self' blob: data:; " + | |
| 117 | "base-uri 'none'; form-action 'none'; frame-ancestors 'self'"; | |
| 118 | ||
| 119 | const nonceOf = (): string => Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64"); | |
| 120 | ||
| 121 | const answer = (body: string | Uint8Array, type: string, extra: Record<string, string> = {}): Response => | |
| 122 | new Response(body, { | |
| 123 | headers: { | |
| 124 | "content-type": type, | |
| 125 | "cache-control": "no-cache", | |
| 126 | "x-content-type-options": "nosniff", | |
| 127 | "referrer-policy": "no-referrer", | |
| 128 | ...extra, | |
| 129 | }, | |
| 130 | }); | |
| 131 | ||
| 132 | const missing = (): Response => | |
| 133 | new Response("not found", { | |
| 134 | status: 404, | |
| 135 | headers: { "content-type": "text/plain; charset=utf-8", "content-security-policy": "default-src 'none'", "x-content-type-options": "nosniff" }, | |
| 136 | }); | |
| 137 | ||
| 138 | export interface ArcadeDisplay { | |
| 139 | readonly repo: Repo; | |
| 140 | readonly config: Result<DisplayConfig, string>; | |
| 141 | } | |
| 142 | ||
| 143 | /** | |
| 144 | * The Arcade's display, read as a stranger reads it; undefined when there is | |
| 145 | * none to show. A site admin titling a display `arcade-builds` publishes it, | |
| 146 | * as Showcase publishes a demo: a private display repository is served all | |
| 147 | * the same, and its private sources stay unnamed. | |
| 148 | */ | |
| 149 | export async function arcadeDisplay(app: App): Promise<ArcadeDisplay | undefined> { | |
| 150 | const repo = await arcadeRepoOf(app); | |
| 151 | if (repo === undefined) return undefined; | |
| 152 | const config = await readDisplay(app, repo); | |
| 153 | return config === undefined ? undefined : { repo, config }; | |
| 154 | } | |
| 155 | ||
| 156 | /** | |
| 157 | * A captured page any display may play: the pin at `oid` in that | |
| 158 | * repository has its demo in the showcase and the page is captured, and | |
| 159 | * the repository is public or the request carries a grant for this page. | |
| 160 | */ | |
| 161 | async function servePlayable(app: App, path: string, grant: string | null): Promise<Response> { | |
| 162 | const m = /^carts\/([^/]+)\/([^/]+)\/([0-9a-f]{40,64})\/([A-Za-z0-9._-]+)\.html$/.exec(path); | |
| 163 | if (m === null) return missing(); | |
| 164 | const [, owner, name, oid, page] = m as unknown as [string, string, string, string, string]; | |
| 165 | const repo = getRepo(app.db, owner, name); | |
| 166 | if (repo === undefined || !ownerInStanding(app.db, repo)) return missing(); | |
| 167 | if (!canRead(app.db, repo, undefined) && (grant === null || !verifyCart(app.config.dataDir, path, grant))) return missing(); | |
| 168 | const pins = await listBuildPins(repoDir(app.reposRoot, repo.ownerName, repo.name)); | |
| 169 | const pin = pins.find((p) => p.oid === oid && p.demo?.showcase === true && pageFile(p.demo.page) === page); | |
| 170 | if (pin?.demo === undefined) return missing(); | |
| 171 | const html = readCapture(app.config.dataDir, repo, oid, pin.demo.page); | |
| 172 | return html === undefined ? missing() : answer(html, "text/html; charset=utf-8", { "content-security-policy": cartAncestors(app) }); | |
| 173 | } | |
| 174 | ||
| 175 | /** | |
| 176 | * A published demo, by the display that shows it and its id there: its | |
| 177 | * captured page, its cover or its page's picture. The display must be | |
| 178 | * public or the Arcade's named display, or the request carry a grant for | |
| 179 | * this path; the demo must be in the display's showcase now. | |
| 180 | */ | |
| 181 | async function serveShown(app: App, path: string, grant: string | null): Promise<Response> { | |
| 182 | const m = /^displays\/([^/]+)\/([^/]+)\/([A-Za-z0-9_-]{22})(\.html|\/cover\.png|\/art\.png)$/.exec(path); | |
| 183 | if (m === null) return missing(); | |
| 184 | const [, owner, name, id, kind] = m as unknown as [string, string, string, string, string]; | |
| 185 | const display = getRepo(app.db, owner, name); | |
| 186 | if (display === undefined || !ownerInStanding(app.db, display)) return missing(); | |
| 187 | const published = canRead(app.db, display, undefined) || (await arcadeRepoOf(app))?.id === display.id; | |
| 188 | if (!published && (grant === null || !verifyCart(app.config.dataDir, path, grant))) return missing(); | |
| 189 | const config = await readDisplay(app, display); | |
| 190 | if (config === undefined || !config.ok) return missing(); | |
| 191 | const item = await displayItem(app, display, config.value, id); | |
| 192 | if (item === undefined) return missing(); | |
| 193 | const { repo, pin, demo } = item; | |
| 194 | if (kind === "/cover.png") { | |
| 195 | const bytes = demo.cover === undefined ? undefined : await readCover(repoDir(app.reposRoot, repo.ownerName, repo.name), demo.cover); | |
| 196 | return bytes === undefined ? missing() : answer(bytes, coverType(bytes) ?? "application/octet-stream"); | |
| 197 | } | |
| 198 | if (kind === "/art.png") { | |
| 199 | const bytes = readArt(app.config.dataDir, repo, pin.oid, demo.page); | |
| 200 | return bytes === undefined ? missing() : answer(bytes, "image/png"); | |
| 201 | } | |
| 202 | const html = readCapture(app.config.dataDir, repo, pin.oid, demo.page); | |
| 203 | return html === undefined ? missing() : answer(html, "text/html; charset=utf-8", { "content-security-policy": cartAncestors(app) }); | |
| 204 | } | |
| 205 | ||
| 206 | /** A cart may frame only inside a display: this origin's or the forge's own. */ | |
| 207 | function cartAncestors(app: App): string { | |
| 208 | const forge = appsRuntime(app)?.options.forgeUrl; | |
| 209 | return `frame-ancestors 'self'${forge === undefined ? "" : ` ${new URL(forge).origin}`}`; | |
| 210 | } | |
| 211 | ||
| 212 | const errorPage = (message: string): Response => | |
| 213 | new Response(`<!doctype html><meta charset="utf-8"><title>Display</title><p>${escapeText(message)}</p>`, { | |
| 214 | status: 422, | |
| 215 | headers: { "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'", "x-content-type-options": "nosniff" }, | |
| 216 | }); | |
| 217 | ||
| 218 | /** Answer one request to the Arcade's host; every answer carries the security floor. */ | |
| 219 | export async function serveArcade(app: App, request: Request): Promise<Response> { | |
| 220 | return securityFloor(await arcadeAnswer(app, request)); | |
| 221 | } | |
| 222 | ||
| 223 | async function arcadeAnswer(app: App, request: Request): Promise<Response> { | |
| 224 | if (request.method !== "GET" && request.method !== "HEAD") | |
| 225 | return new Response("method not allowed", { status: 405, headers: { allow: "GET, HEAD" } }); | |
| 226 | const url = new URL(request.url); | |
| 227 | let path: string; | |
| 228 | try { | |
| 229 | path = decodeURIComponent(url.pathname.slice(1)); | |
| 230 | } catch { | |
| 231 | return missing(); | |
| 232 | } | |
| 233 | // Every display's carts play here, Arcade or not. | |
| 234 | if (path.startsWith("carts/")) return servePlayable(app, path, url.searchParams.get("g")); | |
| 235 | if (path.startsWith("displays/")) return serveShown(app, path, url.searchParams.get("g")); | |
| 236 | const display = await arcadeDisplay(app); | |
| 237 | if (display === undefined) return missing(); | |
| 238 | if (!display.config.ok) return errorPage(display.config.error); | |
| 239 | const config = display.config.value; | |
| 240 | // Grid and graph are drawn by the forge. | |
| 241 | if (config.layout !== "shelf") { | |
| 242 | const forge = appsRuntime(app)?.options.forgeUrl; | |
| 243 | if (forge === undefined || (path !== "" && path !== "index.html")) return missing(); | |
| 244 | return new Response(null, { status: 303, headers: { location: `${forge.replace(/\/$/, "")}/${display.repo.ownerName}/${display.repo.name}/display` } }); | |
| 245 | } | |
| 246 | if (path === "" || path === "index.html") | |
| 247 | { | |
| 248 | const nonce = nonceOf(); | |
| 249 | return answer(shelfPage({ title: config.title, producer: config.shelf.producer, nonce }), "text/html; charset=utf-8", { "content-security-policy": pagePolicy(nonce) }); | |
| 250 | } | |
| 251 | if (path === "boot/jbox-spin.js") return answer(bootScript(), "text/javascript; charset=utf-8"); | |
| 252 | if (path === "cover-template.png") return answer(coverTemplateBytes(), "image/png"); | |
| 253 | const shelf: Shelf = shelfOf(await displayItems(app, display.repo, config, undefined), config.shelf.producer); | |
| 254 | if (path === "games.json") return answer(JSON.stringify(shelf.games), "application/json"); | |
| 255 | // Export snapshot: the display's shelf, in one file that plays offline. | |
| 256 | if (path === "snapshot.html") { | |
| 257 | const made = await snapshotFile(app, config, shelf, new Date()); | |
| 258 | return answer(made.html, "text/html; charset=utf-8", { "content-disposition": `attachment; filename="${made.name}"` }); | |
| 259 | } | |
| 260 | const entry = shelf.entries.get(path); | |
| 261 | if (entry === undefined) return missing(); | |
| 262 | const { repo, pin, cart } = entry; | |
| 263 | if (path.startsWith("labels/") && cart.cover !== undefined) { | |
| 264 | const bytes = await readCover(repoDir(app.reposRoot, repo.ownerName, repo.name), cart.cover); | |
| 265 | return bytes === undefined ? missing() : answer(bytes, coverType(bytes) ?? "application/octet-stream"); | |
| 266 | } | |
| 267 | if (path.startsWith("art/")) { | |
| 268 | const bytes = readArt(app.config.dataDir, repo, pin.oid, cart.page); | |
| 269 | return bytes === undefined ? missing() : answer(bytes, "image/png"); | |
| 270 | } | |
| 271 | return missing(); | |
| 272 | } |
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/contract/openapi/routes/index.ts +1
| @@ -343,6 +343,7 @@ export { route as putApiV1Front } from "./putApiV1Front.ts"; | ||
| 343 | 343 | export { route as putApiV1ReposOwnerNameAppEnvVar } from "./putApiV1ReposOwnerNameAppEnvVar.ts"; |
| 344 | 344 | export { route as putApiV1ReposOwnerNameAppMembers } from "./putApiV1ReposOwnerNameAppMembers.ts"; |
| 345 | 345 | export { route as putApiV1ReposOwnerNameCrewUsername } from "./putApiV1ReposOwnerNameCrewUsername.ts"; |
| 346 | export { route as putApiV1ReposOwnerNameDisplayBuilds } from "./putApiV1ReposOwnerNameDisplayBuilds.ts"; | |
| 346 | 347 | export { route as putApiV1ReposOwnerNameIssuesNumberAssignee } from "./putApiV1ReposOwnerNameIssuesNumberAssignee.ts"; |
| 347 | 348 | export { route as putApiV1ReposOwnerNameIssuesNumberLabels } from "./putApiV1ReposOwnerNameIssuesNumberLabels.ts"; |
| 348 | 349 | export { route as putApiV1ReposOwnerNameIssuesNumberPlan } from "./putApiV1ReposOwnerNameIssuesNumberPlan.ts"; |
src/contract/openapi/routes/putApiV1ReposOwnerNameDisplayBuilds.ts added +19
| @@ -0,0 +1,19 @@ | ||
| 1 | import { REPO, type Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "put", | |
| 5 | path: `${REPO}/display/builds`, | |
| 6 | summary: "Set a display's chosen builds and their order: `builds` in its display.json, a list of `owner/name:label`, written as one commit on the default branch; null removes it, so the display holds every showcased pin of its sources again. A build need not be showcased; one that is not is seen only by readers of its repository (rw scope, a person who writes the display repository); answers the commit and the list", | |
| 7 | auth: true, | |
| 8 | body: { builds: "array" }, | |
| 9 | refusals: { | |
| 10 | forbidden: "403: not a person who writes the display repository (an agent is refused)", | |
| 11 | not_found: "404: no such repository, or the caller cannot read it", | |
| 12 | no_display: "404: the repository has no display.json on its default branch", | |
| 13 | invalid_builds: "422: builds is not a list of distinct owner/name:label, or names more than 500", | |
| 14 | invalid_display: "422: the display.json on the default branch does not parse", | |
| 15 | moved: "409: the default branch moved while it was being written", | |
| 16 | protected_branch: "409: the default branch is protected", | |
| 17 | commit_failed: "422: git refused the commit", | |
| 18 | }, | |
| 19 | }; |
src/core/event_audience.ts +3
| @@ -156,6 +156,9 @@ const READER_KINDS: ReadonlySet<string> = new Set([ | ||
| 156 | 156 | "build.noted", |
| 157 | 157 | // A pin's screenshots are read by its repository's readers (`actions/build_shots.ts`). |
| 158 | 158 | "build.shots", |
| 159 | // A display shelf is read by its repository's readers (`actions/displays.ts`). | |
| 160 | "display.builds", | |
| 161 | "display.captured", | |
| 159 | 162 | "invite.used", |
| 160 | 163 | "user.updated", |
| 161 | 164 | "user.key_added", |
src/core/reserved.ts +1
| @@ -69,6 +69,7 @@ export const SYSTEM_NAMES: readonly string[] = [ | ||
| 69 | 69 | "pipeline", |
| 70 | 70 | "events", |
| 71 | 71 | "bring", |
| 72 | "displays", | |
| 72 | 73 | "explore", |
| 73 | 74 | "family", |
| 74 | 75 | "favicon.ico", |
src/display/launch.ts added +97
| @@ -0,0 +1,97 @@ | ||
| 1 | /** | |
| 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. | |
| 14 | */ | |
| 15 | ||
| 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"; | |
| 22 | 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`; | |
| 87 | ||
| 88 | /** A pin's screenshots, on its repository. */ | |
| 89 | export const repoShotsUrl = (repo: Pick<Repo, "ownerName" | "name">, pin: Pick<BuildPin, "label">): string => | |
| 90 | `/${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): | ||
| 647 | 647 | return kept.code === 0 ? ok(oid) : err("git_failed"); |
| 648 | 648 | } |
| 649 | 649 | |
| 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 | ||
| 650 | 659 | /** |
| 651 | 660 | * Every pin, newest first, read in one `for-each-ref`; or the one `label`. |
| 652 | 661 | * A pin's note is its notes file on `refs/forge/notes` when it has one, |
src/http/api.ts +2
| @@ -354,6 +354,7 @@ import { forgeOriginRoutes } from "./api/forge_origin.ts"; | ||
| 354 | 354 | import { userRoutes } from "./api/user.ts"; |
| 355 | 355 | import { appRoutes } from "./api/app.ts"; |
| 356 | 356 | import { buildRoutes } from "./api/builds.ts"; |
| 357 | import { displayRoutes } from "./api/display.ts"; | |
| 357 | 358 | import { buildShotRoutes } from "./api/build_shots.ts"; |
| 358 | 359 | import { buildCartRoutes } from "./api/build_cart.ts"; |
| 359 | 360 | import { iterationRoutes } from "./api/iterations.ts"; |
| @@ -3649,6 +3650,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 3649 | 3650 | |
| 3650 | 3651 | appRoutes(router); |
| 3651 | 3652 | buildRoutes(router); |
| 3653 | displayRoutes(router); | |
| 3652 | 3654 | buildShotRoutes(router); |
| 3653 | 3655 | buildCartRoutes(router); |
| 3654 | 3656 | iterationRoutes(router); |
src/http/api/display.ts added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | /** | |
| 2 | * A display over the API: its chosen builds, `builds` in display.json, | |
| 3 | * written as one commit (`actions/displays.ts`). Needs the `rw` scope and a | |
| 4 | * person who writes the display repository. | |
| 5 | */ | |
| 6 | ||
| 7 | import { setDisplayBuilds } from "../../actions/displays.ts"; | |
| 8 | import { loadRepo } from "../api.ts"; | |
| 9 | import type { Handler } from "../context.ts"; | |
| 10 | import { body, json, notFound, requireScope, respondAccess } from "../respond.ts"; | |
| 11 | import type { Router } from "../router.ts"; | |
| 12 | ||
| 13 | const STATUS: Record<string, number> = { moved: 409, protected_branch: 409, no_display: 404 }; | |
| 14 | ||
| 15 | export function displayRoutes(router: Router<Handler>): void { | |
| 16 | router.add("PUT", "/api/v1/repos/:owner/:name/display/builds", async (ctx) => { | |
| 17 | const denied = requireScope(ctx, "rw"); | |
| 18 | if (denied) return denied; | |
| 19 | const repo = loadRepo(ctx); | |
| 20 | if (!repo) return notFound(); | |
| 21 | const input = await body(ctx.request); | |
| 22 | const builds = input.builds; | |
| 23 | if (builds !== null && (!Array.isArray(builds) || builds.some((b) => typeof b !== "string"))) | |
| 24 | return json({ error: "invalid_builds", message: "builds must be a list of owner/name:label, or null" }, 422); | |
| 25 | const done = await setDisplayBuilds(ctx.app, ctx.auth.user, repo, builds as readonly string[] | null); | |
| 26 | if (done.ok) return json(done.value); | |
| 27 | const e = done.error; | |
| 28 | if (typeof e === "string") return respondAccess(e, 422); | |
| 29 | return json({ error: e.kind, ...("message" in e ? { message: e.message } : {}) }, STATUS[e.kind] ?? 422); | |
| 30 | }); | |
| 31 | } |
src/http/server.ts +22
| @@ -185,6 +185,10 @@ import { | ||
| 185 | 185 | branchesPage, |
| 186 | 186 | } from "../web/pages/branches.ts"; |
| 187 | 187 | import { iterationsPage, noteSubmit } from "../web/pages/iterations.ts"; |
| 188 | import { displayBuildsSubmit, displayCaptureSubmit, displayCreateSubmit, displayPage, displaySnapshot, displayTitleSubmit, shownCover, shownDownload, shownGallery, shownShot } from "../web/pages/display.ts"; | |
| 189 | import { displaysPage, newDisplayPage } from "../web/pages/displays.ts"; | |
| 190 | import { coverTemplate } from "../web/pages/cover_response.ts"; | |
| 191 | import { isArcadeHost, serveArcade } from "../arcade/host.ts"; | |
| 188 | 192 | import { buildsPage, deletePinSubmit, newBuildPage, pinBuildSubmit, previewBuildSubmit } from "../web/pages/builds.ts"; |
| 189 | 193 | import { shotImage, shotsPage } from "../web/pages/build_shots.ts"; |
| 190 | 194 | import { cartArt, cartPage } from "../web/pages/build_cart.ts"; |
| @@ -744,6 +748,10 @@ export function buildRouter(): Router<Handler> { | ||
| 744 | 748 | router.add("GET", "/front", studioDoor); |
| 745 | 749 | // Apps and people ranked by real numbers, narrowed in one line (#607). |
| 746 | 750 | router.add("GET", "/explore", explorePage); |
| 751 | // Every display the viewer may read, New display's picker, and the house cover's frame (`web/pages/displays.ts`). | |
| 752 | router.add("GET", "/displays", displaysPage); | |
| 753 | router.add("GET", "/displays/new", newDisplayPage); | |
| 754 | router.add("GET", "/-/cover-template.png", coverTemplate); | |
| 747 | 755 | router.add("POST", "/front", frontUpdate); |
| 748 | 756 | router.add("POST", "/home/archive", homeArchive); |
| 749 | 757 | router.add("POST", "/flow/keeper/answer", keeperAnswer); |
| @@ -1286,6 +1294,17 @@ export function buildRouter(): Router<Handler> { | ||
| 1286 | 1294 | router.add("GET", "/:owner/:name/builds/:label/cart", cartPage); |
| 1287 | 1295 | router.add("GET", "/:owner/:name/builds/:label/cart.png", cartArt); |
| 1288 | 1296 | router.add("GET", "/:owner/:name/iterations", iterationsPage); |
| 1297 | // A display: the demos display.json names, in its layout (`display/config.ts`). | |
| 1298 | router.add("GET", "/:owner/:name/display", displayPage); | |
| 1299 | router.add("GET", "/:owner/:name/display/snapshot.html", displaySnapshot); | |
| 1300 | router.add("POST", "/:owner/:name/display/create", displayCreateSubmit); | |
| 1301 | router.add("POST", "/:owner/:name/display/builds", displayBuildsSubmit); | |
| 1302 | router.add("POST", "/:owner/:name/display/title", displayTitleSubmit); | |
| 1303 | router.add("POST", "/:owner/:name/display/capture", displayCaptureSubmit); | |
| 1304 | router.add("GET", "/:owner/:name/display/demo/:id/shots", shownGallery); | |
| 1305 | router.add("GET", "/:owner/:name/display/demo/:id/shots/:file", shownShot); | |
| 1306 | router.add("GET", "/:owner/:name/display/demo/:id/cover", shownCover); | |
| 1307 | router.add("GET", "/:owner/:name/display/demo/:id/download", shownDownload); | |
| 1289 | 1308 | router.add("POST", "/:owner/:name/builds", pinBuildSubmit); |
| 1290 | 1309 | router.add("POST", "/:owner/:name/builds/preview", previewBuildSubmit); |
| 1291 | 1310 | router.add("POST", "/:owner/:name/builds/:label/delete", deletePinSubmit); |
| @@ -2340,6 +2359,9 @@ export async function serve(app: App): Promise<Servers> { | ||
| 2340 | 2359 | // through, since it reads every `--<its host>` label as its own slug. |
| 2341 | 2360 | let ownUnknown = false; |
| 2342 | 2361 | if (runtime !== undefined) { |
| 2362 | // The Arcade's host is the forge's own shelf, never an app (`arcade/host.ts`). | |
| 2363 | if (isArcadeHost(request.headers.get("host"), runtime.options.domain)) | |
| 2364 | return serveArcade(app, request); | |
| 2343 | 2365 | const target = resolveAppHost(app, runtime.options.domain, request); |
| 2344 | 2366 | // A preview's headers are the app's business: what `proxyApp` |
| 2345 | 2367 | // carries back leaves exactly as the app wrote it, which is why the |
src/looks/service.ts +1 −2
| @@ -435,8 +435,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle { | ||
| 435 | 435 | if (shot.ok) { |
| 436 | 436 | const size = shot.value.size === undefined ? {} : { size: shot.value.size }; |
| 437 | 437 | vitals.push({ look, entries: shot.value.entries, ...size }); |
| 438 | } | |
| 439 | else if (isNoBrowser(shot.error)) | |
| 438 | } else if (isNoBrowser(shot.error)) | |
| 440 | 439 | vitals.push({ look, skipped: "no browser" }); |
| 441 | 440 | } |
| 442 | 441 | const taken = |
src/tui/forge.ts +7
| @@ -30,6 +30,7 @@ import { | ||
| 30 | 30 | openOnWeb, |
| 31 | 31 | runAsync, |
| 32 | 32 | } from "./screens/common.ts"; |
| 33 | import { displaysScreen } from "./screens/displays.ts"; | |
| 33 | 34 | import { chainScreen } from "./screens/chain.ts"; |
| 34 | 35 | import { canSeeMemory } from "../boards/memory.ts"; |
| 35 | 36 | import { askedScreen } from "./screens/asked.ts"; |
| @@ -176,6 +177,12 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] { | ||
| 176 | 177 | hint: "your repositories", |
| 177 | 178 | run: () => ctx.push(dashboardScreen(session, ctx)), |
| 178 | 179 | }, |
| 180 | { | |
| 181 | id: "displays", | |
| 182 | title: "Displays", | |
| 183 | hint: "shelves of builds: read one, choose its builds", | |
| 184 | run: () => ctx.push(displaysScreen(session, ctx)), | |
| 185 | }, | |
| 179 | 186 | { |
| 180 | 187 | // Browsing other people and forges is the web explorer's (#607): |
| 181 | 188 | // the terminal hands over its address. |
src/tui/screens/displays.ts added +135
| @@ -0,0 +1,135 @@ | ||
| 1 | /** | |
| 2 | * Displays in the terminal: what /displays and a display's page list on the | |
| 3 | * web. The list shows every display the person may read; enter opens one and | |
| 4 | * shows the builds its sources hold, the chosen ones ticked. A person who | |
| 5 | * writes the display (`writesDisplay`, never an agent) ticks and unticks | |
| 6 | * with space; that is `setDisplayBuilds`, the same write as the page's form | |
| 7 | * and `PUT …/display/builds`, so its `display.builds` event reaches web | |
| 8 | * viewers live. Anyone else reads. | |
| 9 | */ | |
| 10 | ||
| 11 | import { setDisplayBuilds } from "../../actions/displays.ts"; | |
| 12 | import { canRead } from "../../core/repos.ts"; | |
| 13 | import { demoKey } from "../../display/config.ts"; | |
| 14 | import { selectionKeys, sourceRepos } from "../../display/items.ts"; | |
| 15 | import { listedDisplays, type ListedDisplay } from "../../display/known.ts"; | |
| 16 | import { writesDisplay } from "../../display/selections.ts"; | |
| 17 | import { listBuildPins } from "../../git/builds.ts"; | |
| 18 | import { repoDir } from "../../git/repos.ts"; | |
| 19 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 20 | import { binding } from "../app/keys.ts"; | |
| 21 | import { style } from "../term/style.ts"; | |
| 22 | import { truncate } from "../term/width.ts"; | |
| 23 | import type { Session } from "../session.ts"; | |
| 24 | import { fill, len, split } from "../ui/layout.ts"; | |
| 25 | import { emptyState } from "../ui/widgets.ts"; | |
| 26 | import { ListState, drawList, type ListRow } from "./common.ts"; | |
| 27 | ||
| 28 | const LAYOUT_WORD = { shelf: "shelf", grid: "grid", graph: "graph" } as const; | |
| 29 | ||
| 30 | /** One display's builds: the sources' pins, the chosen ones first in their order. */ | |
| 31 | export function displayScreen(f: Session, ctx: Ctx, shown: ListedDisplay): Screen { | |
| 32 | const state = new ListState(); | |
| 33 | const config = shown.config.ok ? shown.config.value : undefined; | |
| 34 | let chosen: string[] = []; | |
| 35 | let keys: string[] = []; | |
| 36 | let loaded = false; | |
| 37 | const writer = (): boolean => writesDisplay(f.app, shown.repo, f.user); | |
| 38 | ||
| 39 | const load = async (): Promise<void> => { | |
| 40 | if (config === undefined) return; | |
| 41 | chosen = await selectionKeys(f.app, config, f.user); | |
| 42 | const pool: string[] = []; | |
| 43 | for (const r of sourceRepos(f.app, config).filter((r) => canRead(f.app.db, r, f.user))) { | |
| 44 | for (const p of await listBuildPins(repoDir(f.app.reposRoot, r.ownerName, r.name))) pool.push(demoKey(r.ownerName, r.name, p.label)); | |
| 45 | } | |
| 46 | keys = [...chosen, ...pool.filter((k) => !chosen.includes(k))]; | |
| 47 | state.clamp(keys.length); | |
| 48 | loaded = true; | |
| 49 | ctx.invalidate(); | |
| 50 | }; | |
| 51 | void load(); | |
| 52 | ||
| 53 | const screen: Screen = { | |
| 54 | title: config?.title ?? `${shown.repo.ownerName}/${shown.repo.name}`, | |
| 55 | keys: [binding(["j", "k"], "move cursor"), binding(["space"], "choose or drop a build")], | |
| 56 | render(area, s) { | |
| 57 | const c = ctx.theme.c; | |
| 58 | const [head, body] = split(area, "v", [len(1), fill(1)]); | |
| 59 | if (config === undefined) { | |
| 60 | emptyState(s, body!, c, { title: "display.json does not parse." }); | |
| 61 | return; | |
| 62 | } | |
| 63 | const line = writer() ? "space chooses or drops a build" : "you read this display"; | |
| 64 | s.text(head!.x, head!.y, truncate(line, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 65 | if (!loaded) return; | |
| 66 | if (keys.length === 0) { | |
| 67 | emptyState(s, body!, c, { title: "No builds." }); | |
| 68 | return; | |
| 69 | } | |
| 70 | const rows: ListRow[] = keys.map((k) => ({ title: k, secondary: chosen.includes(k) ? "on the display" : "", meta: chosen.includes(k) ? `#${chosen.indexOf(k) + 1}` : "" })); | |
| 71 | drawList(s, body!, c, state, rows); | |
| 72 | }, | |
| 73 | key(e) { | |
| 74 | if (state.key(e, keys.length)) return true; | |
| 75 | if (e.ctrl || e.alt || e.key !== " " || !writer()) return false; | |
| 76 | const key = keys[state.index]; | |
| 77 | if (key === undefined) return false; | |
| 78 | const next = chosen.includes(key) ? chosen.filter((k) => k !== key) : [...chosen, key]; | |
| 79 | void setDisplayBuilds(f.app, f.user, shown.repo, next).then((done) => { | |
| 80 | if (done.ok) { | |
| 81 | chosen = [...next]; | |
| 82 | keys = [...chosen, ...keys.filter((k) => !chosen.includes(k))]; | |
| 83 | ctx.toast("saved", "success"); | |
| 84 | } else ctx.toast("that could not be saved", "danger"); | |
| 85 | ctx.invalidate(); | |
| 86 | }); | |
| 87 | return true; | |
| 88 | }, | |
| 89 | }; | |
| 90 | return screen; | |
| 91 | } | |
| 92 | ||
| 93 | /** Every display the person may read. */ | |
| 94 | export function displaysScreen(f: Session, ctx: Ctx): Screen { | |
| 95 | const state = new ListState(); | |
| 96 | let rows: ListedDisplay[] = []; | |
| 97 | let loaded = false; | |
| 98 | void listedDisplays(f.app, f.user).then((r) => { | |
| 99 | rows = r; | |
| 100 | loaded = true; | |
| 101 | state.clamp(rows.length); | |
| 102 | ctx.invalidate(); | |
| 103 | }); | |
| 104 | const screen: Screen = { | |
| 105 | title: "Displays", | |
| 106 | keys: [binding(["j", "k"], "move cursor"), binding(["enter"], "open")], | |
| 107 | render(area, s) { | |
| 108 | const c = ctx.theme.c; | |
| 109 | if (!loaded) return; | |
| 110 | if (rows.length === 0) { | |
| 111 | emptyState(s, area, c, { title: "No displays." }); | |
| 112 | return; | |
| 113 | } | |
| 114 | drawList( | |
| 115 | s, | |
| 116 | area, | |
| 117 | c, | |
| 118 | state, | |
| 119 | rows.map((d) => ({ | |
| 120 | title: d.config.ok ? d.config.value.title : "display.json failed", | |
| 121 | secondary: `${d.repo.ownerName}/${d.repo.name}`, | |
| 122 | meta: d.config.ok ? `${LAYOUT_WORD[d.config.value.layout]} · ${d.demos ?? 0} demos` : "", | |
| 123 | })), | |
| 124 | ); | |
| 125 | }, | |
| 126 | key(e) { | |
| 127 | if (state.key(e, rows.length)) return true; | |
| 128 | const d = rows[state.index]; | |
| 129 | if (e.ctrl || e.alt || e.key !== "enter" || d === undefined) return false; | |
| 130 | ctx.push(displayScreen(f, ctx, d)); | |
| 131 | return true; | |
| 132 | }, | |
| 133 | }; | |
| 134 | return screen; | |
| 135 | } |
src/web/pages/build_info.ts +2 −1
| @@ -102,7 +102,7 @@ function notesOf(b: IterationBuild, back: string): Html { | ||
| 102 | 102 | <p class="it-saved" data-saved role="status" hidden></p></section>`; |
| 103 | 103 | } |
| 104 | 104 | |
| 105 | export function infoOf(ctx: Ctx, b: IterationBuild, forkOf: string | null, link: string, back: string): Html { | |
| 105 | export function infoOf(ctx: Ctx, b: IterationBuild, forkOf: string | null, link: string, back: string, held?: readonly string[]): Html { | |
| 106 | 106 | const name = b.repo.split("/")[1] ?? b.repo; |
| 107 | 107 | const lineage = [ |
| 108 | 108 | ...(forkOf === null ? [] : [`fork of ${forkOf}`]), |
| @@ -121,6 +121,7 @@ export function infoOf(ctx: Ctx, b: IterationBuild, forkOf: string | null, link: | ||
| 121 | 121 | ${fact("Repository", html`<a href="/${b.repo}">${b.repo}</a>`)} |
| 122 | 122 | ${fact("Lineage", lineage.length === 0 ? "first pin" : lineage.join(" · "))} |
| 123 | 123 | ${fact("Pinned", `${b.by} · ${b.at.slice(0, 10)}`)} |
| 124 | ${held === undefined ? null : html`<dt>In</dt><dd data-in>${held.length === 0 ? "None" : held.join(", ")}</dd>`} | |
| 124 | 125 | ${fact("Plays", playsText(b))} |
| 125 | 126 | </dl></section> |
| 126 | 127 | ${notesOf(b, back)} |
src/web/pages/build_shots.ts +8 −3
| @@ -9,6 +9,7 @@ import { readBuildPin } from "../../git/builds.ts"; | ||
| 9 | 9 | import { readShotBytes, readShots } from "../../git/shots.ts"; |
| 10 | 10 | import { repoDir } from "../../git/repos.ts"; |
| 11 | 11 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 12 | import type { Repo } from "../../core/repos.ts"; | |
| 12 | 13 | import type { Ctx } from "../../http/context.ts"; |
| 13 | 14 | import { crumbsFor, loadRepo, notFoundPage, repoBase, repoHeader, repoPalette } from "../chrome.ts"; |
| 14 | 15 | import { html, type Html } from "../html.ts"; |
| @@ -45,14 +46,18 @@ export async function shotsPage(ctx: Ctx): Promise<Response> { | ||
| 45 | 46 | ); |
| 46 | 47 | } |
| 47 | 48 | |
| 48 | // GET /:owner/:name/builds/:label/shots/:file — one screenshot. Typed by | |
| 49 | // its first bytes, never by its name, and never sniffed into anything else. | |
| 49 | // GET /:owner/:name/builds/:label/shots/:file — one screenshot. | |
| 50 | 50 | export async function shotImage(ctx: Ctx): Promise<Response> { |
| 51 | 51 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 52 | 52 | const repo = loadRepo(ctx); |
| 53 | 53 | if (!repo) return notFoundPage(ctx); |
| 54 | return shotResponse(ctx, repo, ctx.params.label ?? "", ctx.params.file ?? ""); | |
| 55 | } | |
| 56 | ||
| 57 | /** One screenshot of a pin, as every route that serves one answers it. Typed by its first bytes, never by its name, and never sniffed into anything else. */ | |
| 58 | export async function shotResponse(ctx: Ctx, repo: Repo, label: string, file: string): Promise<Response> { | |
| 54 | 59 | const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name); |
| 55 | const shot = await timePhase(ctx.request, "read", () => readShotBytes(dir, ctx.params.label ?? "", ctx.params.file ?? "")); | |
| 60 | const shot = await timePhase(ctx.request, "read", () => readShotBytes(dir, label, file)); | |
| 56 | 61 | if (shot === undefined) return notFoundPage(ctx); |
| 57 | 62 | // A name moves to another picture on a reorder; the blob it is does not. |
| 58 | 63 | const etag = `"${shot.oid}"`; |
src/web/pages/cover_response.ts added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | /** A demo's picture: its uploaded cover, else the picture of its captured page. */ | |
| 2 | ||
| 3 | import { readArt } from "../../arcade/carts.ts"; | |
| 4 | import { coverTemplateBytes } from "../../arcade/host.ts"; | |
| 5 | import type { Repo } from "../../core/repos.ts"; | |
| 6 | import { coverType, readCover, type Demo } from "../../git/builds.ts"; | |
| 7 | import { repoDir } from "../../git/repos.ts"; | |
| 8 | import type { Ctx } from "../../http/context.ts"; | |
| 9 | import { notFoundPage } from "../chrome.ts"; | |
| 10 | ||
| 11 | /** The answer every route that serves a demo's cover gives. */ | |
| 12 | export async function coverResponse(ctx: Ctx, repo: Repo, oid: string, demo: Demo): Promise<Response> { | |
| 13 | const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name); | |
| 14 | const uploaded = demo.cover === undefined ? undefined : await readCover(dir, demo.cover); | |
| 15 | const bytes = uploaded ?? readArt(ctx.app.config.dataDir, repo, oid, demo.page); | |
| 16 | if (bytes === undefined) return notFoundPage(ctx); | |
| 17 | return new Response(bytes, { | |
| 18 | headers: { | |
| 19 | "content-type": coverType(bytes) ?? "application/octet-stream", | |
| 20 | "cache-control": "private, max-age=60", | |
| 21 | "x-content-type-options": "nosniff", | |
| 22 | }, | |
| 23 | }); | |
| 24 | } | |
| 25 | ||
| 26 | // GET /-/cover-template.png — the house cover's frame, which a demo's cover is drawn in. | |
| 27 | export function coverTemplate(_ctx: Ctx): Response { | |
| 28 | return new Response(coverTemplateBytes(), { | |
| 29 | headers: { "content-type": "image/png", "cache-control": "public, max-age=86400", "x-content-type-options": "nosniff" }, | |
| 30 | }); | |
| 31 | } |
src/web/pages/display.ts added +568
| @@ -0,0 +1,568 @@ | ||
| 1 | /** | |
| 2 | * A repository's display page, `/<owner>/<repo>/display`: the builds its | |
| 3 | * `display.json` holds (`display/config.ts`), as whoever is looking may read | |
| 4 | * them, drawn from stock components and working with scripts off: | |
| 5 | * | |
| 6 | * - The display's builds are rows; a row is a link (`?build=<key>`) and the | |
| 7 | * chosen build's player and info panel (`build_info.ts`) are drawn under | |
| 8 | * the list on the server. | |
| 9 | * - A person who writes the display also gets Rename, Up and Remove on each | |
| 10 | * row and, below, every pinned build of its sources that they read, | |
| 11 | * grouped by fork, each with an Add or Remove button. Each is a post form | |
| 12 | * (`POST …/display/builds` with `add`, `drop` or `up`, one commit through | |
| 13 | * `setDisplayBuilds`) that redirects back with a flash. | |
| 14 | * - Other displays the viewer reads are links in a disclosure. | |
| 15 | * | |
| 16 | * A `shelf` display is drawn here like any other; its shelf look, the | |
| 17 | * Arcade's carousel and jbox boot (`arcade/arcade.html`) from the same | |
| 18 | * builds, shows on the Arcade host and at `/display?look=shelf`, whose bar | |
| 19 | * leads its writer back to this page ("Edit display"). | |
| 20 | * | |
| 21 | * A bad `display.json` shows its error here, never a guess. | |
| 22 | * | |
| 23 | * Showcase publishes the demo (`display/items.ts`): a viewer who reads the | |
| 24 | * display sees every showcased demo on it. One whose repository the viewer | |
| 25 | * cannot read shows its name and version alone — no repository, link, pin | |
| 26 | * or commit — and its pictures, screenshots and captured page come through | |
| 27 | * the display's own routes, `/<owner>/<display>/display/demo/<id>/…`, by | |
| 28 | * its opaque id. | |
| 29 | */ | |
| 30 | ||
| 31 | import { captureDisplay, saveDisplay, setDisplayBuilds, setDisplayTitle } from "../../actions/displays.ts"; | |
| 32 | import { shelfPage } from "../../arcade/host.ts"; | |
| 33 | import { shelfOf, slug } from "../../arcade/shelf.ts"; | |
| 34 | import { snapshotFile } from "../../arcade/snapshot.ts"; | |
| 35 | import { readCapture } from "../../arcade/carts.ts"; | |
| 36 | import { canRead, type Repo } from "../../core/repos.ts"; | |
| 37 | import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts"; | |
| 38 | import { checkDisplay, demoKey, DISPLAY_FILE, isDemoKey, readDisplay, type DisplayConfig } from "../../display/config.ts"; | |
| 39 | import { displayItem, displayItems, keepUnnamed, selectionKeys, sourceRepos, type DisplayItem } from "../../display/items.ts"; | |
| 40 | import { coverUrl, displayOrigin, downloadUrl, playUrl, shotsUrl } from "../../display/launch.ts"; | |
| 41 | import { displaySelections, selectionsHolding, writesDisplay, type DisplaySelection } from "../../display/selections.ts"; | |
| 42 | import { isCopiedPin, listBuildPins, type BuildPin } from "../../git/builds.ts"; | |
| 43 | import { repoDir } from "../../git/repos.ts"; | |
| 44 | import { readShots } from "../../git/shots.ts"; | |
| 45 | import type { Ctx } from "../../http/context.ts"; | |
| 46 | import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, repoHeader, repoPalette, signInFirst } from "../chrome.ts"; | |
| 47 | import { field, prefersJson, readForm } from "../form.ts"; | |
| 48 | import { html, type Html } from "../html.ts"; | |
| 49 | import { flashTo, page } from "../layout.ts"; | |
| 50 | import { clearFlashCookie, readFlash, type Flash } from "../flash.ts"; | |
| 51 | import { btn, card, disclosure, empty, icon, listCard, row } from "../ui.ts"; | |
| 52 | import { buildOf, repoFactsOf } from "../../core/iterations.ts"; | |
| 53 | import { infoOf, INFO_CSS, INFO_JS, playerOf } from "./build_info.ts"; | |
| 54 | import { shotResponse } from "./build_shots.ts"; | |
| 55 | import { coverResponse } from "./cover_response.ts"; | |
| 56 | ||
| 57 | const DISPLAY_CSS = INFO_CSS + /* css */ ` | |
| 58 | .display-shots{list-style:none;margin:12px 0 0;padding:0;display:flex;flex-direction:column;gap:16px} | |
| 59 | .display-shots img{display:block;max-width:100%;border:1px solid var(--border);border-radius:6px} | |
| 60 | `; | |
| 61 | ||
| 62 | /** The picture a row leads with: the uploaded cover, else the captured page's, else the first screenshot; none otherwise. */ | |
| 63 | async function coverOf(ctx: Ctx, item: DisplayItem): Promise<Html | undefined> { | |
| 64 | const alt = `${item.demo.name} ${item.demo.version}`; | |
| 65 | if (item.demo.cover !== undefined || item.art) return html`<img src="${coverUrl(item)}" width="48" height="36" alt="${alt}" loading="lazy" />`; | |
| 66 | const shots = await readShots(repoDir(ctx.app.reposRoot, item.repo.ownerName, item.repo.name), item.pin.label); | |
| 67 | const first = shots.items[0]; | |
| 68 | return first === undefined ? undefined : html`<img src="${shotsUrl(item)}/${first.file}?v=${first.oid.slice(0, 12)}" width="48" height="36" alt="${alt}" loading="lazy" />`; | |
| 69 | } | |
| 70 | ||
| 71 | /** An item's name on the page: its key to a reader of its repository, its opaque id to anyone else. */ | |
| 72 | const shownKey = (item: DisplayItem): string => (item.open ? item.key : `id:${item.id}`); | |
| 73 | ||
| 74 | /** The player of a build whose repository the viewer cannot read: its published page, or why there is none. */ | |
| 75 | function hiddenPlayer(ctx: Ctx, item: DisplayItem): Html { | |
| 76 | const title = html`<b>${item.demo.name} ${item.demo.version}</b>`; | |
| 77 | const play = item.launch === "file" && item.captured !== undefined ? playUrl(ctx.app, item) : undefined; | |
| 78 | if (play !== undefined) | |
| 79 | return html`<div class="it-bar">${title}<span class="it-sp"><a class="btn" data-size="sm" href="${play}" target="_blank" rel="noopener noreferrer">Full screen</a><a class="btn" data-size="sm" href="${downloadUrl(item)}">Download</a></span></div> | |
| 80 | <iframe class="it-frame" src="${play}" title="${item.demo.name} ${item.demo.version}" allow="fullscreen; autoplay; gamepad"></iframe>`; | |
| 81 | if (item.launch === "shots") | |
| 82 | return html`<div class="it-bar">${title}</div><div class="it-empty"><a class="btn" data-size="sm" href="${shotsUrl(item)}">Screenshots</a></div>`; | |
| 83 | return html`<div class="it-bar">${title}</div><div class="it-empty">${item.launch === "file" ? "Not built yet" : "Preview needs app access"}</div>`; | |
| 84 | } | |
| 85 | ||
| 86 | /** The info panel of a build whose repository the viewer cannot read: its name and version, nothing of where it lives. */ | |
| 87 | const hiddenInfo = (item: DisplayItem): Html => | |
| 88 | html`<h3>${item.demo.name} ${item.demo.version}</h3><section data-section="build"><h4>Build</h4><p>Published on this display. Its repository is private.</p></section>`; | |
| 89 | ||
| 90 | /** The pins of `repos` a person may tick, each once: a fork's copy of its parent's pin shows in the parent. */ | |
| 91 | async function poolOf(ctx: Ctx, repos: readonly Repo[]): Promise<{ repo: Repo; pins: BuildPin[] }[]> { | |
| 92 | const pinsOf = new Map( | |
| 93 | await Promise.all(repos.map(async (r) => [r.id, await listBuildPins(repoDir(ctx.app.reposRoot, r.ownerName, r.name))] as const)), | |
| 94 | ); | |
| 95 | const groups = repos.map((repo) => { | |
| 96 | const parentPins = repo.forkParentId === null ? undefined : pinsOf.get(repo.forkParentId); | |
| 97 | const pins = (pinsOf.get(repo.id) ?? []) | |
| 98 | .filter((p) => parentPins === undefined || !isCopiedPin(p, parentPins)) | |
| 99 | .sort((a, b) => (a.pinnedAt < b.pinnedAt ? -1 : 1)); | |
| 100 | return { repo, pins }; | |
| 101 | }); | |
| 102 | // Roots first, then each fork one step after the repository it was forked from; within a step, the oldest pin first. | |
| 103 | const ids = new Set(repos.map((r) => r.id)); | |
| 104 | const byId = new Map(repos.map((r) => [r.id, r])); | |
| 105 | const depth = (r: Repo): number => { | |
| 106 | let d = 0; | |
| 107 | for (let at: Repo | undefined = r; at !== undefined && at.forkParentId !== null && ids.has(at.forkParentId) && d < repos.length; at = byId.get(at.forkParentId)) d++; | |
| 108 | return d; | |
| 109 | }; | |
| 110 | const first = (g: { pins: BuildPin[] }) => g.pins[0]?.pinnedAt ?? "~"; | |
| 111 | return groups.sort((a, b) => depth(a.repo) - depth(b.repo) || (first(a) < first(b) ? -1 : first(a) > first(b) ? 1 : 0)); | |
| 112 | } | |
| 113 | ||
| 114 | /** The info panel's own script (its dialogs and notes), run on the build shown. */ | |
| 115 | const DISPLAY_JS = ` | |
| 116 | (function () { | |
| 117 | ${INFO_JS} | |
| 118 | var player = document.getElementById('it-player'), info = document.getElementById('it-info'); | |
| 119 | if (player && info) panel(player, info, null); | |
| 120 | })(); | |
| 121 | `; | |
| 122 | ||
| 123 | /** The display's error, where its page would be. */ | |
| 124 | function brokenPage(ctx: Ctx, repo: Repo, message: string): Response { | |
| 125 | return page({ | |
| 126 | ctx, | |
| 127 | title: `Display · ${repo.name}`, | |
| 128 | crumbs: crumbsFor(repo), | |
| 129 | palette: repoPalette(ctx, repo), | |
| 130 | body: html`${repoHeader(ctx, repo, "none")} | |
| 131 | <div class="mt"> | |
| 132 | ${card(html`<p class="mono">${message}</p> | |
| 133 | <p class="muted small">Fix <a href="${repoBase(repo)}/blob/${repo.defaultBranch}/display.json">display.json</a> on ${repo.defaultBranch}.</p>`, { | |
| 134 | head: html`${icon("alert")}<h2>Display failed</h2>`, | |
| 135 | tone: "danger", | |
| 136 | })} | |
| 137 | </div>`, | |
| 138 | }); | |
| 139 | } | |
| 140 | ||
| 141 | /** | |
| 142 | * The forge's bar above the shelf, outside the arcade's frame, for a | |
| 143 | * signed-in viewer: the way back to Displays, and for a writer Edit display | |
| 144 | * and the flash a save left. Styled from the arcade page's own colours. | |
| 145 | */ | |
| 146 | function shelfBar(ctx: Ctx, repo: Repo, writer: boolean, flash: Flash | undefined): string { | |
| 147 | return html`<nav id="display-writer" aria-label="Display" style="position:relative;z-index:6;display:flex;gap:12px;align-items:center;padding:8px 16px;background:var(--line);color:var(--ink)"> | |
| 148 | <a href="/displays" style="color:var(--sun)">← Displays</a> | |
| 149 | ${flash === undefined ? null : html`<span role="status" style="color:var(--sun)">${flash.message}</span>`} | |
| 150 | <span style="margin-left:auto"></span> | |
| 151 | ${writer ? html`<a href="${repoBase(repo)}/display" style="color:var(--sun)">Edit display</a>` : null} | |
| 152 | </nav>`.toString(); | |
| 153 | } | |
| 154 | ||
| 155 | /** The forge's shelf page: the Arcade's page with its shelf inside, carts on the display origin. */ | |
| 156 | function shelfResponse(ctx: Ctx, repo: Repo, config: DisplayConfig, items: readonly DisplayItem[]): Response { | |
| 157 | const origin = displayOrigin(ctx.app); | |
| 158 | if (origin === undefined) return brokenPage(ctx, repo, "Play needs apps on this forge: the shelf plays carts at arcade.<app domain>."); | |
| 159 | const shelf = shelfOf(items, config.shelf.producer); | |
| 160 | const games = shelf.games.map((g) => ({ | |
| 161 | ...g, | |
| 162 | builds: g.builds.map((b) => { | |
| 163 | const item = shelf.entries.get(b.file)!.item; | |
| 164 | return { | |
| 165 | ...b, | |
| 166 | file: playUrl(ctx.app, item) ?? b.file, | |
| 167 | save: downloadUrl(item), | |
| 168 | ...(b.label === undefined ? {} : { label: coverUrl(item) }), | |
| 169 | ...(b.art === undefined ? {} : { art: coverUrl(item) }), | |
| 170 | }; | |
| 171 | }), | |
| 172 | })); | |
| 173 | const writer = writesDisplay(ctx.app, repo, ctx.auth.user); | |
| 174 | const flash = writer ? readFlash(ctx.request) : undefined; | |
| 175 | const body = shelfPage({ | |
| 176 | title: config.title, | |
| 177 | producer: config.shelf.producer, | |
| 178 | data: { exportHref: `${repoBase(repo)}/display/snapshot.html`, games, carts: {}, labels: { "cover-template.png": "/-/cover-template.png" } }, | |
| 179 | ...(ctx.auth.user !== undefined ? { bar: shelfBar(ctx, repo, writer, flash) } : {}), | |
| 180 | }); | |
| 181 | return new Response(body, { | |
| 182 | headers: { | |
| 183 | ...(flash === undefined ? {} : { "set-cookie": clearFlashCookie(ctx.url, ctx.app.config.url) }), | |
| 184 | "content-type": "text/html; charset=utf-8", | |
| 185 | "cache-control": "private, no-cache", | |
| 186 | "content-security-policy": | |
| 187 | "default-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline' https://fonts.googleapis.com; " + | |
| 188 | `font-src https://fonts.gstatic.com; img-src 'self' data: blob:; frame-src ${origin}; media-src 'self' blob: data:; ` + | |
| 189 | "base-uri 'none'; form-action 'none'; frame-ancestors 'none'", | |
| 190 | }, | |
| 191 | }); | |
| 192 | } | |
| 193 | ||
| 194 | /** The repository and its display, as `ctx`'s viewer reads them; a Response when there is none to show. */ | |
| 195 | async function opened(ctx: Ctx): Promise<{ repo: Repo; config: DisplayConfig } | Response> { | |
| 196 | const repo = loadRepo(ctx); | |
| 197 | if (!repo) return notFoundPage(ctx); | |
| 198 | const config = await timePhase(ctx.request, "read", () => readDisplay(ctx.app, repo)); | |
| 199 | if (config === undefined) { | |
| 200 | await checkDisplay(ctx.app, repo); | |
| 201 | return timePhase(ctx.request, "render", () => notFoundPage(ctx)); | |
| 202 | } | |
| 203 | if (!config.ok) return timePhase(ctx.request, "render", () => brokenPage(ctx, repo, config.error)); | |
| 204 | return { repo, config: config.value }; | |
| 205 | } | |
| 206 | ||
| 207 | /** A button in a form of its own: every mutation on this page is a post. */ | |
| 208 | const act = (action: string, name: string, key: string, label: string, text: string): Html => | |
| 209 | html`<form method="post" action="${action}">${btn(text, { size: "sm", label, name, value: key })}</form>`; | |
| 210 | ||
| 211 | /** A writer's rename, tucked in a disclosure so it works with scripts off. */ | |
| 212 | const renameOf = (base: string, title: string): Html => | |
| 213 | disclosure( | |
| 214 | "Rename", | |
| 215 | html`<form class="row-actions" method="post" action="${base}/display/title"> | |
| 216 | <input class="input" name="title" value="${title}" maxlength="80" required aria-label="Title" /> | |
| 217 | ${btn("Save", { variant: "primary", size: "sm" })} | |
| 218 | </form>`, | |
| 219 | { small: true }, | |
| 220 | ); | |
| 221 | ||
| 222 | /** Every display the viewer reads, as links. */ | |
| 223 | function otherDisplays(repo: Repo, displays: readonly DisplaySelection[]): Html | null { | |
| 224 | const here = `${repo.ownerName}/${repo.name}`; | |
| 225 | const others = displays.filter((d) => d.id !== here); | |
| 226 | if (others.length === 0) return null; | |
| 227 | return disclosure("Other displays", listCard(others.map((d) => row({ href: `${repoBase(d.repo)}/display`, title: d.title, meta: html`${d.id}` }))), { small: true }); | |
| 228 | } | |
| 229 | ||
| 230 | /** The display: its builds as rows, the chosen one played and described below, a writer's pool of builds beside. */ | |
| 231 | async function displayView(ctx: Ctx, repo: Repo, config: DisplayConfig): Promise<Response> { | |
| 232 | const viewer = ctx.auth.user; | |
| 233 | const writer = writesDisplay(ctx.app, repo, viewer); | |
| 234 | const items = await timePhaseAsync(ctx.request, "items", () => displayItems(ctx.app, repo, config, viewer)); | |
| 235 | const onDisplay = new Set(items.map((i) => i.key)); | |
| 236 | // A writer's pool: every pin of the sources they read, grouped by fork. | |
| 237 | const pool = writer | |
| 238 | ? await timePhaseAsync(ctx.request, "pool", () => | |
| 239 | poolOf( | |
| 240 | ctx, | |
| 241 | sourceRepos(ctx.app, config).filter((r) => canRead(ctx.app.db, r, viewer)), | |
| 242 | ), | |
| 243 | ) | |
| 244 | : []; | |
| 245 | const displays = await timePhaseAsync(ctx.request, "selections", () => displaySelections(ctx.app, viewer)); | |
| 246 | const base = repoBase(repo); | |
| 247 | const builds = `${base}/display/builds`; | |
| 248 | const back = (key: string) => `${base}/display?build=${encodeURIComponent(key)}`; | |
| 249 | const link = (key: string) => `${ctx.url.origin}${back(key)}`; | |
| 250 | const asked = ctx.url.searchParams.get("build"); | |
| 251 | const current = items.find((i) => shownKey(i) === asked) ?? items[0]; | |
| 252 | ||
| 253 | const rows: Html[] = []; | |
| 254 | for (const [i, item] of items.entries()) { | |
| 255 | const name = item.open ? item.repo.name : item.demo.name; | |
| 256 | const version = item.open ? item.pin.label : item.demo.version; | |
| 257 | const lead = await coverOf(ctx, item); | |
| 258 | rows.push( | |
| 259 | row({ | |
| 260 | href: back(shownKey(item)), | |
| 261 | title: name, | |
| 262 | meta: html`<span class="mono">${version}</span>`, | |
| 263 | ...(lead === undefined ? {} : { lead }), | |
| 264 | current: item === current, | |
| 265 | data: { key: shownKey(item) }, | |
| 266 | ...(writer && item.open | |
| 267 | ? { after: html`${i > 0 ? act(builds, "up", item.key, `Move ${name} ${version} up`, "Up") : null}${act(builds, "drop", item.key, `Remove ${name} ${version}`, "Remove")}` } | |
| 268 | : {}), | |
| 269 | }), | |
| 270 | ); | |
| 271 | } | |
| 272 | ||
| 273 | // The shown build: its player and its panel, drawn here, not swapped in by a script. | |
| 274 | let shown: Html | null = null; | |
| 275 | if (current !== undefined) { | |
| 276 | if (!current.open) shown = html`<div class="it-player" id="it-player">${hiddenPlayer(ctx, current)}</div><aside class="it-info" id="it-info">${hiddenInfo(current)}</aside>`; | |
| 277 | else { | |
| 278 | const rf = await repoFactsOf(ctx, current.repo, false); | |
| 279 | const parent = current.pin.parent === undefined ? null : current.pin.parent.includes(":") ? current.pin.parent : `${rf.name}:${current.pin.parent}`; | |
| 280 | const edge = current.pin.parent === undefined ? null : current.pin.parent.includes(":") ? "concept" : "git"; | |
| 281 | const up = current.repo.forkParentId === null ? undefined : pool.find((g) => g.repo.id === current.repo.forkParentId)?.repo; | |
| 282 | const b = await buildOf(ctx, rf, current.pin, parent, edge); | |
| 283 | shown = html`<div class="it-player" id="it-player">${playerOf(b)}</div> | |
| 284 | <aside class="it-info" id="it-info">${infoOf(ctx, b, up === undefined ? null : `${up.ownerName}/${up.name}`, link(b.key), back(b.key), selectionsHolding(b.key, current.demo.showcase === true, displays))}</aside>`; | |
| 285 | } | |
| 286 | } | |
| 287 | ||
| 288 | // The side list: one row per source repository, its builds under it, each added or removed by a button. | |
| 289 | const clash = (n: string) => pool.filter((g) => g.repo.name === n).length > 1; | |
| 290 | const groups = pool.filter((g) => g.pins.length > 0); | |
| 291 | const side = writer | |
| 292 | ? card( | |
| 293 | groups.length === 0 | |
| 294 | ? html`<p class="muted small">No pinned builds in this display's sources.</p>` | |
| 295 | : html`<ul class="list">${groups.map((g) => { | |
| 296 | const keys = g.pins.map((p) => demoKey(g.repo.ownerName, g.repo.name, p.label)); | |
| 297 | const on = keys.filter((k) => onDisplay.has(k)).length; | |
| 298 | return row({ | |
| 299 | title: clash(g.repo.name) ? `${g.repo.ownerName}/${g.repo.name}` : g.repo.name, | |
| 300 | meta: html`${String(on)} of ${String(keys.length)}`, | |
| 301 | data: { repo: `${g.repo.ownerName}/${g.repo.name}` }, | |
| 302 | children: g.pins.map((p, k) => | |
| 303 | row({ | |
| 304 | title: html`<span class="mono">${p.label}</span>`, | |
| 305 | after: onDisplay.has(keys[k]!) | |
| 306 | ? act(builds, "drop", keys[k]!, `Remove ${p.label}`, "Remove") | |
| 307 | : act(builds, "add", keys[k]!, `Add ${p.label}`, "Add"), | |
| 308 | }), | |
| 309 | ), | |
| 310 | }); | |
| 311 | })}</ul>`, | |
| 312 | { head: html`<h2>Builds in ${config.title}</h2>`, pad: groups.length === 0 }, | |
| 313 | ) | |
| 314 | : null; | |
| 315 | ||
| 316 | const body = html`${repoHeader(ctx, repo, "none")} | |
| 317 | ${pageHead(config.title, { actions: btn("Snapshot", { href: `${base}/display/snapshot.html`, size: "sm", icon: "download" }) })} | |
| 318 | ${writer ? renameOf(base, config.title) : null}${otherDisplays(repo, displays)} | |
| 319 | <div class="mt"> | |
| 320 | ${rows.length === 0 | |
| 321 | ? empty({ icon: "pin", title: "No builds on this display", ...(writer ? { note: "Add builds from the list below." } : {}) }) | |
| 322 | : listCard(rows, { head: html`<h2>Builds</h2>` })} | |
| 323 | </div> | |
| 324 | ${shown === null ? null : html`<div class="mt">${shown}</div>`} | |
| 325 | ${side === null ? null : html`<div class="mt">${side}</div>`}`; | |
| 326 | return timePhase(ctx.request, "render", () => | |
| 327 | page({ | |
| 328 | ctx, | |
| 329 | title: `${config.title} · ${repo.name}`, | |
| 330 | crumbs: crumbsFor(repo), | |
| 331 | palette: repoPalette(ctx, repo), | |
| 332 | body, | |
| 333 | styleCss: DISPLAY_CSS, | |
| 334 | scriptJs: DISPLAY_JS, | |
| 335 | frameSrc: displayOrigin(ctx.app), | |
| 336 | }), | |
| 337 | ); | |
| 338 | } | |
| 339 | ||
| 340 | // GET /:owner/:name/display — the display page (round 1101 E) for every layout. The | |
| 341 | // shelf look is the Arcade's own page; ?look=shelf shows it here too. | |
| 342 | export async function displayPage(ctx: Ctx): Promise<Response> { | |
| 343 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 344 | const got = await opened(ctx); | |
| 345 | if (got instanceof Response) return got; | |
| 346 | const { repo, config } = got; | |
| 347 | void checkDisplay(ctx.app, repo); | |
| 348 | if (config.layout === "shelf" && ctx.url.searchParams.get("look") === "shelf") { | |
| 349 | const items = await timePhase(ctx.request, "items", () => displayItems(ctx.app, repo, config, ctx.auth.user)); | |
| 350 | return timePhase(ctx.request, "render", () => shelfResponse(ctx, repo, config, items)); | |
| 351 | } | |
| 352 | return displayView(ctx, repo, config); | |
| 353 | } | |
| 354 | ||
| 355 | const BUILDS_ERRORS: Record<string, string> = { | |
| 356 | moved: "Not saved: the display changed meanwhile. Reload and try again.", | |
| 357 | protected_branch: "Not saved: the default branch is protected.", | |
| 358 | invalid_builds: "Not saved: a display holds at most 500 distinct builds.", | |
| 359 | invalid_display: "Not saved: display.json does not parse. Fix it first.", | |
| 360 | no_display: "Not saved: this repository has no display.json.", | |
| 361 | }; | |
| 362 | ||
| 363 | // POST /:owner/:name/display/builds — a writer's new selection from the page, in order; builds they cannot name keep their place. | |
| 364 | export async function displayBuildsSubmit(ctx: Ctx): Promise<Response> { | |
| 365 | const repo = loadRepo(ctx); | |
| 366 | if (!repo) return notFoundPage(ctx); | |
| 367 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 368 | const form = await readForm(ctx, "rw"); | |
| 369 | if (form instanceof Response) return form; | |
| 370 | const read = await readDisplay(ctx.app, repo); | |
| 371 | if (read === undefined || !read.ok) { | |
| 372 | const kind = read === undefined ? "no_display" : "invalid_display"; | |
| 373 | return Response.json({ error: kind, message: BUILDS_ERRORS[kind] }, { status: 422 }); | |
| 374 | } | |
| 375 | const one = (name: string): string | undefined => { | |
| 376 | const v = form.get(name); | |
| 377 | return typeof v === "string" && isDemoKey(v) ? v : undefined; | |
| 378 | }; | |
| 379 | const [add, drop, up] = [one("add"), one("drop"), one("up")]; | |
| 380 | let named: string[]; | |
| 381 | if (form.has("add") || form.has("drop") || form.has("up")) { | |
| 382 | if (add === undefined && drop === undefined && up === undefined) { | |
| 383 | const message = "Not saved: that is not a build."; | |
| 384 | return prefersJson(ctx) ? Response.json({ error: "invalid_builds", message }, { status: 422 }) : flashTo(ctx, `${repoBase(repo)}/display`, { tone: "danger", message }); | |
| 385 | } | |
| 386 | // One build at a time, from the page's buttons: applied to the selection as it stands. | |
| 387 | named = await selectionKeys(ctx.app, read.value, ctx.auth.user); | |
| 388 | if (add !== undefined && !named.includes(add)) named.push(add); | |
| 389 | if (drop !== undefined) named = named.filter((k) => k !== drop); | |
| 390 | const at = up === undefined ? -1 : named.indexOf(up); | |
| 391 | if (at > 0) [named[at - 1], named[at]] = [named[at]!, named[at - 1]!]; | |
| 392 | } else named = form.getAll("build").filter((v): v is string => typeof v === "string"); | |
| 393 | const builds = await keepUnnamed(ctx.app, read.value, named, ctx.auth.user); | |
| 394 | const done = await setDisplayBuilds(ctx.app, ctx.auth.user, repo, builds); | |
| 395 | const to = `${repoBase(repo)}/display`; | |
| 396 | if (!done.ok) { | |
| 397 | const e = done.error; | |
| 398 | if (e === "not_found" || e === "unauthorized" || e === "forbidden") return notFoundPage(ctx); | |
| 399 | const message = BUILDS_ERRORS[e.kind] ?? "Not saved: git refused the change."; | |
| 400 | if (prefersJson(ctx)) return Response.json({ error: e.kind, message }, { status: e.kind === "moved" ? 409 : 422 }); | |
| 401 | return flashTo(ctx, to, { tone: "danger", message }); | |
| 402 | } | |
| 403 | if (prefersJson(ctx)) return Response.json({ commit: done.value.commit, count: named.length }); | |
| 404 | return flashTo(ctx, to, { message: "Saved." }); | |
| 405 | } | |
| 406 | ||
| 407 | const TITLE_ERRORS: Record<string, string> = { | |
| 408 | moved: "Not saved: the display changed meanwhile. Reload and try again.", | |
| 409 | protected_branch: "Not saved: the default branch is protected.", | |
| 410 | no_display: "Not saved: this repository has no display.json.", | |
| 411 | }; | |
| 412 | ||
| 413 | // POST /:owner/:name/display/title — a writer's new title for the display, as one commit. | |
| 414 | export async function displayTitleSubmit(ctx: Ctx): Promise<Response> { | |
| 415 | const repo = loadRepo(ctx); | |
| 416 | if (!repo) return notFoundPage(ctx); | |
| 417 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 418 | const form = await readForm(ctx, "rw"); | |
| 419 | if (form instanceof Response) return form; | |
| 420 | const to = `${repoBase(repo)}/display`; | |
| 421 | const done = await setDisplayTitle(ctx.app, ctx.auth.user, repo, field(form, "title").trim()); | |
| 422 | if (!done.ok) { | |
| 423 | const e = done.error; | |
| 424 | if (e === "not_found" || e === "unauthorized" || e === "forbidden") return notFoundPage(ctx); | |
| 425 | const message = TITLE_ERRORS[e.kind] ?? `Not saved: ${"message" in e ? e.message : "git refused the change"}.`; | |
| 426 | if (prefersJson(ctx)) return Response.json({ error: e.kind, message }, { status: e.kind === "moved" ? 409 : 422 }); | |
| 427 | return flashTo(ctx, to, { tone: "danger", message }); | |
| 428 | } | |
| 429 | if (prefersJson(ctx)) return Response.json({ commit: done.value.commit, title: done.value.title }); | |
| 430 | return flashTo(ctx, to, { message: "Saved." }); | |
| 431 | } | |
| 432 | ||
| 433 | // POST /:owner/:name/display/create — New display: display.json naming the owner's repositories as its source, then the page. | |
| 434 | export async function displayCreateSubmit(ctx: Ctx): Promise<Response> { | |
| 435 | const repo = loadRepo(ctx); | |
| 436 | if (!repo) return notFoundPage(ctx); | |
| 437 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 438 | const form = await readForm(ctx, "rw"); | |
| 439 | if (form instanceof Response) return form; | |
| 440 | const text = `${JSON.stringify({ title: repo.name, layout: "grid", sources: [repo.ownerName] }, null, 2)}\n`; | |
| 441 | if ((await readDisplay(ctx.app, repo)) !== undefined) return flashTo(ctx, `${repoBase(repo)}/display`, { tone: "attn", message: `${repo.name} already has a display.` }); | |
| 442 | const saved = await saveDisplay(ctx.app, ctx.auth.user, repo, text, undefined); | |
| 443 | if (!saved.ok) { | |
| 444 | const e = saved.error; | |
| 445 | if (e === "not_found" || e === "unauthorized" || e === "forbidden") return notFoundPage(ctx); | |
| 446 | return flashTo(ctx, "/displays/new", { | |
| 447 | tone: "danger", | |
| 448 | message: e.kind === "protected_branch" ? `Create failed: ${repo.defaultBranch} is protected.` : `Create failed: ${"message" in e ? e.message : e.kind}.`, | |
| 449 | }); | |
| 450 | } | |
| 451 | return flashTo(ctx, `${repoBase(repo)}/display`, { message: `Created ${DISPLAY_FILE} on ${repo.defaultBranch} at ${saved.value.commit.slice(0, 7)}.` }); | |
| 452 | } | |
| 453 | ||
| 454 | // POST /:owner/:name/display/capture — capture every showcased file demo of the display that has none. | |
| 455 | export async function displayCaptureSubmit(ctx: Ctx): Promise<Response> { | |
| 456 | const repo = loadRepo(ctx); | |
| 457 | if (!repo) return notFoundPage(ctx); | |
| 458 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 459 | const form = await readForm(ctx, "rw"); | |
| 460 | if (form instanceof Response) return form; | |
| 461 | const done = await captureDisplay(ctx.app, ctx.auth.user, repo); | |
| 462 | const to = `${repoBase(repo)}/display`; | |
| 463 | if (!done.ok) { | |
| 464 | if (done.error === "not_found" || done.error === "unauthorized" || done.error === "forbidden") return notFoundPage(ctx); | |
| 465 | return flashTo(ctx, to, { tone: "danger", message: `Capture failed: fix ${DISPLAY_FILE} first.` }); | |
| 466 | } | |
| 467 | const n = done.value.started.length; | |
| 468 | return flashTo(ctx, to, { message: `Started ${String(n)} ${n === 1 ? "capture" : "captures"}.` }); | |
| 469 | } | |
| 470 | ||
| 471 | // GET /:owner/:name/display/snapshot.html — the display's playable demos in one offline file. | |
| 472 | export async function displaySnapshot(ctx: Ctx): Promise<Response> { | |
| 473 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 474 | const got = await opened(ctx); | |
| 475 | if (got instanceof Response) return got; | |
| 476 | const items = await timePhase(ctx.request, "items", () => displayItems(ctx.app, got.repo, got.config, ctx.auth.user)); | |
| 477 | const shelf = shelfOf(items, got.config.shelf.producer); | |
| 478 | const made = await timePhase(ctx.request, "render", () => snapshotFile(ctx.app, got.config, shelf, new Date())); | |
| 479 | return new Response(made.html, { | |
| 480 | headers: { | |
| 481 | "content-type": "text/html; charset=utf-8", | |
| 482 | "content-disposition": `attachment; filename="${made.name}"`, | |
| 483 | "cache-control": "private, no-cache", | |
| 484 | "content-security-policy": "sandbox", | |
| 485 | }, | |
| 486 | }); | |
| 487 | } | |
| 488 | ||
| 489 | /** A screenshots page: the display's chrome when shown through a display, the repository's own otherwise. */ | |
| 490 | function galleryPage( | |
| 491 | ctx: Ctx, | |
| 492 | repo: Repo, | |
| 493 | name: string, | |
| 494 | sub: Html, | |
| 495 | base: string, | |
| 496 | items: readonly { file: string; oid: string; caption: string }[], | |
| 497 | ): Response { | |
| 498 | const shots = { items }; | |
| 499 | return page({ | |
| 500 | ctx, | |
| 501 | title: `Screenshots · ${name}`, | |
| 502 | crumbs: crumbsFor(repo), | |
| 503 | palette: repoPalette(ctx, repo), | |
| 504 | styleCss: DISPLAY_CSS, | |
| 505 | body: html`${repoHeader(ctx, repo, "none")} | |
| 506 | <div class="page-head mt"><h2>Screenshots · ${name}</h2>${sub}</div> | |
| 507 | ${shots.items.length === 0 | |
| 508 | ? html`<p class="muted">No screenshots</p>` | |
| 509 | : html`<ol class="display-shots"> | |
| 510 | ${shots.items.map( | |
| 511 | (s, i) => html`<li> | |
| 512 | <img src="${base}/${s.file}?v=${s.oid.slice(0, 12)}" alt="${s.caption === "" ? `Screenshot ${String(i + 1)}` : s.caption}" loading="lazy" /> | |
| 513 | ${s.caption === "" ? null : html`<p class="small">${s.caption}</p>`} | |
| 514 | </li>`, | |
| 515 | )} | |
| 516 | </ol>`}`, | |
| 517 | }); | |
| 518 | } | |
| 519 | ||
| 520 | /** The display and the published demo its id names there; a 404 when there is none — unshowcased, gone, or another display's id. */ | |
| 521 | async function shownItem(ctx: Ctx): Promise<{ repo: Repo; item: DisplayItem } | Response> { | |
| 522 | const got = await opened(ctx); | |
| 523 | if (got instanceof Response) return got; | |
| 524 | const item = await displayItem(ctx.app, got.repo, got.config, ctx.params.id ?? ""); | |
| 525 | return item === undefined ? notFoundPage(ctx) : { repo: got.repo, item }; | |
| 526 | } | |
| 527 | ||
| 528 | // GET /:owner/:name/display/demo/:id/shots — a published demo's screenshots, through its display. | |
| 529 | export async function shownGallery(ctx: Ctx): Promise<Response> { | |
| 530 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 531 | const got = await shownItem(ctx); | |
| 532 | if (got instanceof Response) return got; | |
| 533 | const { repo, item } = got; | |
| 534 | const shots = await readShots(repoDir(ctx.app.reposRoot, item.repo.ownerName, item.repo.name), item.pin.label); | |
| 535 | return galleryPage(ctx, repo, `${item.demo.name} ${item.demo.version}`, html`<a class="small" href="${repoBase(repo)}/display">Back to the display</a>`, shotsUrl({ ...item, open: false }), shots.items); | |
| 536 | } | |
| 537 | ||
| 538 | // GET /:owner/:name/display/demo/:id/shots/:file — one of its screenshots. | |
| 539 | export async function shownShot(ctx: Ctx): Promise<Response> { | |
| 540 | const got = await shownItem(ctx); | |
| 541 | if (got instanceof Response) return got; | |
| 542 | return shotResponse(ctx, got.item.repo, got.item.pin.label, ctx.params.file ?? ""); | |
| 543 | } | |
| 544 | ||
| 545 | // GET /:owner/:name/display/demo/:id/cover — its cover, or the picture of its captured page. | |
| 546 | export async function shownCover(ctx: Ctx): Promise<Response> { | |
| 547 | const got = await shownItem(ctx); | |
| 548 | if (got instanceof Response) return got; | |
| 549 | return coverResponse(ctx, got.item.repo, got.item.pin.oid, got.item.demo); | |
| 550 | } | |
| 551 | ||
| 552 | // GET /:owner/:name/display/demo/:id/download — its captured page, as a file. Never a running build's. | |
| 553 | export async function shownDownload(ctx: Ctx): Promise<Response> { | |
| 554 | const got = await shownItem(ctx); | |
| 555 | if (got instanceof Response) return got; | |
| 556 | const { item } = got; | |
| 557 | const kept = readCapture(ctx.app.config.dataDir, item.repo, item.pin.oid, item.demo.page); | |
| 558 | if (kept === undefined) return notFoundPage(ctx); | |
| 559 | return new Response(kept, { | |
| 560 | headers: { | |
| 561 | "content-type": "application/octet-stream", | |
| 562 | "content-disposition": `attachment; filename="${slug(item.demo.name)}-${slug(item.demo.version)}.html"`, | |
| 563 | "x-content-type-options": "nosniff", | |
| 564 | "content-security-policy": "sandbox", | |
| 565 | "cache-control": "private, no-cache", | |
| 566 | }, | |
| 567 | }); | |
| 568 | } |
src/web/pages/displays.ts added +98
| @@ -0,0 +1,98 @@ | ||
| 1 | /** | |
| 2 | * `/displays`: every display the viewer may read — each repository with a | |
| 3 | * `display.json` on its default branch (`display/config.ts`) — one row | |
| 4 | * each: title, layout, repository, and how many showcased demos it shows. | |
| 5 | * A row opens the display. New display asks for a repository the person | |
| 6 | * writes that has no display yet (`/displays/new`), writes its | |
| 7 | * `display.json` and opens the display, where its builds are ticked. | |
| 8 | * | |
| 9 | * Both read through the display cache (`display/known.ts`), so a warm page | |
| 10 | * reads no git. | |
| 11 | */ | |
| 12 | ||
| 13 | import { listReposWritableTo } from "../../core/repos.ts"; | |
| 14 | import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts"; | |
| 15 | import { listedDisplays, withoutDisplay } from "../../display/known.ts"; | |
| 16 | import type { Ctx } from "../../http/context.ts"; | |
| 17 | import { pageHead, repoBase, signInFirst } from "../chrome.ts"; | |
| 18 | import { html } from "../html.ts"; | |
| 19 | import { page } from "../layout.ts"; | |
| 20 | import { btn, empty, listCard, row } from "../ui.ts"; | |
| 21 | ||
| 22 | const LAYOUT_WORD = { shelf: "Shelf", grid: "Grid", graph: "Graph" } as const; | |
| 23 | ||
| 24 | /** Whether the viewer is a person who may make a display: signed in, not an agent. */ | |
| 25 | const maker = (ctx: Ctx): boolean => ctx.auth.user !== undefined && ctx.auth.user.kind !== "agent"; | |
| 26 | ||
| 27 | // GET /displays — every display the viewer may read. | |
| 28 | export async function displaysPage(ctx: Ctx): Promise<Response> { | |
| 29 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 30 | const rows = await timePhaseAsync(ctx.request, "displays", () => listedDisplays(ctx.app, ctx.auth.user)); | |
| 31 | return timePhase(ctx.request, "render", () => | |
| 32 | page({ | |
| 33 | ctx, | |
| 34 | title: "Displays", | |
| 35 | body: html`${pageHead("Displays", maker(ctx) ? { actions: btn("New display", { href: "/displays/new", variant: "primary", size: "sm", icon: "plus" }) } : {})} | |
| 36 | ${rows.length === 0 | |
| 37 | ? empty({ icon: "pin", title: "No displays" }) | |
| 38 | : html`<div class="table-scroll" role="region" tabindex="0" aria-label="Displays"> | |
| 39 | <table class="table" data-dense data-by="displays"> | |
| 40 | <thead> | |
| 41 | <tr> | |
| 42 | <th scope="col">Title</th> | |
| 43 | <th scope="col">Layout</th> | |
| 44 | <th scope="col">Repository</th> | |
| 45 | <th scope="col">Demos</th> | |
| 46 | </tr> | |
| 47 | </thead> | |
| 48 | <tbody> | |
| 49 | ${rows.map((d) => { | |
| 50 | const base = repoBase(d.repo); | |
| 51 | const name = `${d.repo.ownerName}/${d.repo.name}`; | |
| 52 | return html`<tr data-display="${name}"> | |
| 53 | <td><a href="${base}/display">${d.config.ok ? d.config.value.title : "display.json failed"}</a></td> | |
| 54 | <td>${d.config.ok ? LAYOUT_WORD[d.config.value.layout] : "None"}</td> | |
| 55 | <td><a class="mono" href="${base}">${name}</a></td> | |
| 56 | <td data-demos>${d.demos === undefined ? "None" : String(d.demos)}</td> | |
| 57 | </tr>`; | |
| 58 | })} | |
| 59 | </tbody> | |
| 60 | </table> | |
| 61 | </div>`}`, | |
| 62 | }), | |
| 63 | ); | |
| 64 | } | |
| 65 | ||
| 66 | // GET /displays/new — the repositories a person writes with no display yet; Create display writes its display.json. | |
| 67 | export async function newDisplayPage(ctx: Ctx): Promise<Response> { | |
| 68 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 69 | if (ctx.auth.user === undefined) return signInFirst(ctx); | |
| 70 | const user = ctx.auth.user; | |
| 71 | const repos = await timePhaseAsync(ctx.request, "repos", async () => | |
| 72 | user.kind === "agent" ? [] : withoutDisplay(ctx.app, listReposWritableTo(ctx.app.db, user, { limit: 200, withoutArchived: true })), | |
| 73 | ); | |
| 74 | return timePhase(ctx.request, "render", () => | |
| 75 | page({ | |
| 76 | ctx, | |
| 77 | title: "New display", | |
| 78 | crumbs: [{ label: "Displays", href: "/displays" }], | |
| 79 | body: html`${pageHead("New display")} | |
| 80 | ${repos.length === 0 | |
| 81 | ? empty({ icon: "folder", title: "No repositories you write without a display" }) | |
| 82 | : html`${repos.map( | |
| 83 | (r, i) => html`<form method="post" action="${repoBase(r)}/display/create" id="dn-${String(i)}" hidden></form>`, | |
| 84 | )} | |
| 85 | ${listCard( | |
| 86 | repos.map((r, i) => | |
| 87 | row({ | |
| 88 | title: html`<span class="mono">${r.ownerName}/${r.name}</span>`, | |
| 89 | meta: html`${r.visibility === "private" ? "Private" : "Public"} · default branch ${r.defaultBranch}`, | |
| 90 | trail: btn("Create display", { form: `dn-${String(i)}`, size: "sm", label: `Create a display in ${r.ownerName}/${r.name}` }), | |
| 91 | data: { repo: `${r.ownerName}/${r.name}` }, | |
| 92 | }), | |
| 93 | ), | |
| 94 | { head: html`<h2>Repositories you write</h2><span class="muted small">${String(repos.length)}</span>` }, | |
| 95 | )}`}`, | |
| 96 | }), | |
| 97 | ); | |
| 98 | } |
test/cookie-flags.test.ts +1
| @@ -43,6 +43,7 @@ const UNREACHED: Record<string, { sites: number; why: string }> = { | ||
| 43 | 43 | "src/apps/scaffold.ts": { sites: 7, why: "the `notice` cookie lives in the template generated into new apps, not in the forge's own responses" }, |
| 44 | 44 | "src/apps/feedback.ts": { sites: 2, why: "the visitor cookie is set on a deployed app's own host from its feedback widget; covered by the feedback tests" }, |
| 45 | 45 | "src/web/pages/claim.ts": { sites: 1, why: "claiming the first admin seat needs a fresh forge with a claim link; same sessionCookie() as the walked doors" }, |
| 46 | "src/web/pages/display.ts": { sites: 1, why: "clears forge_flash after a display build; the same clearFlashCookie() as the walked layout redirect" }, | |
| 46 | 47 | "src/web/pages/first-admin.ts": { sites: 1, why: "first-admin recovery needs a forge with no admin; same sessionCookie() as the walked doors" }, |
| 47 | 48 | "src/web/pages/signup-passkey.ts": { sites: 2, why: "sign-up by passkey needs an invite; same sessionCookie() as the walked doors" }, |
| 48 | 49 | "src/web/pages/everyday.ts": { sites: 2, why: "the admin/everyday switch needs a paired account; same sessionCookie() as the walked doors" }, |
test/design-audit.test.ts +1 −1
| @@ -15,7 +15,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8"); | ||
| 15 | 15 | |
| 16 | 16 | /** Routes that answer a file, a fragment, a redirect hop or a callback. */ |
| 17 | 17 | const NOT_PAGES = |
| 18 | /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|manifest\.webmanifest$|opensearch\.xml$|llms\.txt$|openapi\.json$|releases\.json$|changelog\.atom$|audit\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|settings\/origins\/callback$|home\/archived\/|settings\/backups\/live$|api\/v1\/)/; | |
| 18 | /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|manifest\.webmanifest$|opensearch\.xml$|llms\.txt$|openapi\.json$|releases\.json$|changelog\.atom$|audit\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|settings\/origins\/callback$|home\/archived\/|-\/cover-template\.png$|settings\/backups\/live$|api\/v1\/)/; | |
| 19 | 19 | |
| 20 | 20 | const getRoutes = [ |
| 21 | 21 | ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g), |
test/displays.test.ts added +273
| @@ -0,0 +1,273 @@ | ||
| 1 | /** | |
| 2 | * Displays are reachable: `/displays` lists the ones the viewer may read, | |
| 3 | * `/:owner/:name/display` draws one server-side, and `PUT | |
| 4 | * /api/v1/repos/:owner/:name/display/builds` sets its builds: validated | |
| 5 | * (422), scoped (rw), and refused across origins. | |
| 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 { createApp, type App } from "../src/app.ts"; | |
| 12 | import { pinBuild } from "../src/actions/builds.ts"; | |
| 13 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { createRepo as createRepoRow, getRepo } from "../src/core/repos.ts"; | |
| 15 | import { createUser, type User } from "../src/core/users.ts"; | |
| 16 | import { readDisplay } from "../src/display/config.ts"; | |
| 17 | import { arcadePage, serveArcade, shelfPage } from "../src/arcade/host.ts"; | |
| 18 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 19 | import { tokenFor } from "./helpers/tokens.ts"; | |
| 20 | ||
| 21 | describe("displays", () => { | |
| 22 | let dataDir: string; | |
| 23 | let app: App; | |
| 24 | let servers: Servers; | |
| 25 | let base: string; | |
| 26 | let alice: User; | |
| 27 | let token: string; | |
| 28 | let bobToken: string; | |
| 29 | const put = (body: unknown, auth = token, extra: Record<string, string> = {}) => | |
| 30 | fetch(`${base}/api/v1/repos/alice/shelf/display/builds`, { | |
| 31 | method: "PUT", | |
| 32 | headers: { authorization: `Bearer ${auth}`, "content-type": "application/json", ...extra }, | |
| 33 | body: JSON.stringify(body), | |
| 34 | }); | |
| 35 | ||
| 36 | /** The display's builds once the display cache has followed the write. */ | |
| 37 | const buildsBecome = async (want: readonly string[] | undefined): Promise<readonly string[] | undefined> => { | |
| 38 | let got: readonly string[] | undefined; | |
| 39 | for (let i = 0; i < 40; i++) { | |
| 40 | const read = await readDisplay(app, getRepo(app.db, "alice", "shelf")!); | |
| 41 | got = read?.ok ? read.value.builds : undefined; | |
| 42 | if (JSON.stringify(got) === JSON.stringify(want)) return got; | |
| 43 | await new Promise((r) => setTimeout(r, 50)); | |
| 44 | } | |
| 45 | return got; | |
| 46 | }; | |
| 47 | ||
| 48 | beforeAll(async () => { | |
| 49 | dataDir = await mkdtemp(join(tmpdir(), "forge-displays-")); | |
| 50 | app = createApp({ dataDir, port: 0 }); | |
| 51 | servers = await serve(app); | |
| 52 | base = servers.url; | |
| 53 | for (const name of ["alice", "bob"]) { | |
| 54 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase", adminIfFirst: true }); | |
| 55 | if (!made.ok) throw new Error(made.error); | |
| 56 | if (name === "alice") alice = made.value; | |
| 57 | } | |
| 58 | for (const name of ["game", "shelf", "plain"]) { | |
| 59 | const made = await createRepo(app, alice, { name, visibility: "public" }); | |
| 60 | if (!made.ok) throw new Error(String(made.error)); | |
| 61 | } | |
| 62 | const game = getRepo(app.db, "alice", "game")!; | |
| 63 | const c = await commitToBranch(app, alice, game, { branch: "main", message: "one", files: [{ path: "one.txt", content: "one\n" }] }); | |
| 64 | if (!c.ok) throw new Error(JSON.stringify(c.error)); | |
| 65 | const pinned = await pinBuild(app, alice, game, { label: "v1", oid: c.value.commitOid, note: "first <b>build</b>" }); | |
| 66 | if (!pinned.ok) throw new Error(JSON.stringify(pinned.error)); | |
| 67 | const shelf = getRepo(app.db, "alice", "shelf")!; | |
| 68 | const d = await commitToBranch(app, alice, shelf, { | |
| 69 | branch: "main", | |
| 70 | message: "display", | |
| 71 | files: [{ path: "display.json", content: JSON.stringify({ title: "Pocket & Shelf", layout: "grid", sources: ["alice/game"], builds: ["alice/game:v1"] }) }], | |
| 72 | }); | |
| 73 | if (!d.ok) throw new Error(JSON.stringify(d.error)); | |
| 74 | token = tokenFor(app, "alice", "rw"); | |
| 75 | bobToken = tokenFor(app, "bob", "rw"); | |
| 76 | }); | |
| 77 | ||
| 78 | afterAll(async () => { | |
| 79 | servers.stop(); | |
| 80 | app.close(); | |
| 81 | await rm(dataDir, { recursive: true, force: true }); | |
| 82 | }); | |
| 83 | ||
| 84 | test("the list shows the seeded display, escaped, and not a repository without one", async () => { | |
| 85 | const res = await fetch(`${base}/displays`); | |
| 86 | expect(res.status).toBe(200); | |
| 87 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 88 | expect(res.headers.get("content-security-policy")).toBeTruthy(); | |
| 89 | expect(res.headers.get("referrer-policy")).toBeTruthy(); | |
| 90 | const text = await res.text(); | |
| 91 | expect(text).toContain('data-display="alice/shelf"'); | |
| 92 | expect(text).toContain("Pocket & Shelf"); | |
| 93 | expect(text).not.toContain("Pocket & Shelf"); | |
| 94 | expect(text).toContain("Grid"); | |
| 95 | expect(text).not.toContain('data-display="alice/plain"'); | |
| 96 | }); | |
| 97 | ||
| 98 | test("a display page draws its title and its build, server-rendered", async () => { | |
| 99 | const res = await fetch(`${base}/alice/shelf/display`); | |
| 100 | expect(res.status).toBe(200); | |
| 101 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 102 | expect(res.headers.get("content-security-policy")).toBeTruthy(); | |
| 103 | const text = await res.text(); | |
| 104 | expect(text).toContain("Pocket & Shelf"); | |
| 105 | expect(text).toContain("alice/game"); | |
| 106 | expect(text).toContain("v1"); | |
| 107 | expect(text).not.toContain("first <b>build</b>"); | |
| 108 | }); | |
| 109 | ||
| 110 | test("a repository with no display is not a display page", async () => { | |
| 111 | expect((await fetch(`${base}/alice/plain/display`)).status).toBe(404); | |
| 112 | }); | |
| 113 | ||
| 114 | test("PUT builds writes the selection as one commit; null clears it", async () => { | |
| 115 | const res = await put({ builds: ["alice/game:v1"] }); | |
| 116 | expect(res.status).toBe(200); | |
| 117 | const body = (await res.json()) as { commit: string; builds: string[] }; | |
| 118 | expect(body.builds).toEqual(["alice/game:v1"]); | |
| 119 | const read = await readDisplay(app, getRepo(app.db, "alice", "shelf")!); | |
| 120 | expect(read?.ok && read.value.builds).toEqual(["alice/game:v1"]); | |
| 121 | const cleared = await put({ builds: null }); | |
| 122 | expect(cleared.status).toBe(200); | |
| 123 | const again = await readDisplay(app, getRepo(app.db, "alice", "shelf")!); | |
| 124 | expect(again?.ok && again.value.builds).toBeUndefined(); | |
| 125 | }); | |
| 126 | ||
| 127 | test("a bad PUT is a 422", async () => { | |
| 128 | for (const bad of [{ builds: "alice/game:v1" }, { builds: [1] }, { builds: ["alice/game:v1", "alice/game:v1"] }, { builds: ["--upload-pack"] }, {}]) { | |
| 129 | const res = await put(bad); | |
| 130 | expect(res.status).toBe(422); | |
| 131 | expect(((await res.json()) as { error: string }).error).toBe("invalid_builds"); | |
| 132 | } | |
| 133 | }); | |
| 134 | ||
| 135 | test("a PUT without a token, with a read-only token, or by someone who cannot write is refused", async () => { | |
| 136 | expect((await fetch(`${base}/api/v1/repos/alice/shelf/display/builds`, { method: "PUT", body: "{}" })).status).toBe(401); | |
| 137 | expect((await put({ builds: null }, tokenFor(app, "alice", "ro", "ro"))).status).toBe(403); | |
| 138 | expect([403, 404]).toContain((await put({ builds: null }, bobToken)).status); | |
| 139 | }); | |
| 140 | ||
| 141 | test("the page's form post across origins is refused", async () => { | |
| 142 | const signed = await fetch(`${base}/signin`, { method: "POST", body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), redirect: "manual" }); | |
| 143 | const cookie = (signed.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 144 | const res = await fetch(`${base}/alice/shelf/display/builds`, { | |
| 145 | method: "POST", | |
| 146 | headers: { cookie, origin: "https://evil.example", "content-type": "application/x-www-form-urlencoded" }, | |
| 147 | body: "build=alice/game:v1", | |
| 148 | redirect: "manual", | |
| 149 | }); | |
| 150 | expect(res.status).toBe(403); | |
| 151 | const read = await readDisplay(app, getRepo(app.db, "alice", "shelf")!); | |
| 152 | expect(read?.ok && read.value.builds).toBeUndefined(); | |
| 153 | }); | |
| 154 | ||
| 155 | test("a reader sees rows as links and no buttons; a writer's buttons are post forms that work without a script", async () => { | |
| 156 | expect((await put({ builds: ["alice/game:v1"] })).status).toBe(200); | |
| 157 | const anon = await (await fetch(`${base}/alice/shelf/display`)).text(); | |
| 158 | expect(anon).toContain('href="/alice/shelf/display?build=alice%2Fgame%3Av1"'); | |
| 159 | expect(anon).not.toContain("/alice/shelf/display/builds"); | |
| 160 | expect(anon).not.toContain("dp-"); | |
| 161 | ||
| 162 | const signed = await fetch(`${base}/signin`, { method: "POST", body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), redirect: "manual" }); | |
| 163 | const cookie = (signed.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 164 | const mine = await (await fetch(`${base}/alice/shelf/display`, { headers: { cookie } })).text(); | |
| 165 | expect(mine).toContain('<form method="post" action="/alice/shelf/display/builds">'); | |
| 166 | expect(mine).toMatch(/<button[^>]*name="drop"[^>]*value="alice\/game:v1"/); | |
| 167 | expect(mine).not.toContain("dp-"); | |
| 168 | ||
| 169 | const post = (field: string, value: string) => | |
| 170 | fetch(`${base}/alice/shelf/display/builds`, { | |
| 171 | method: "POST", | |
| 172 | headers: { cookie, origin: base, "content-type": "application/x-www-form-urlencoded" }, | |
| 173 | body: new URLSearchParams({ [field]: value }), | |
| 174 | redirect: "manual", | |
| 175 | }); | |
| 176 | const dropped = await post("drop", "alice/game:v1"); | |
| 177 | expect(dropped.status).toBe(303); | |
| 178 | expect(await buildsBecome([])).toEqual([]); | |
| 179 | const added = await post("add", "alice/game:v1"); | |
| 180 | expect(added.status).toBe(303); | |
| 181 | expect(await buildsBecome(["alice/game:v1"])).toEqual(["alice/game:v1"]); | |
| 182 | const bad = await post("add", "--upload-pack"); | |
| 183 | expect(bad.status).toBe(303); | |
| 184 | expect(decodeURIComponent(bad.headers.get("set-cookie") ?? "")).toContain("not a build"); | |
| 185 | expect(await buildsBecome(["alice/game:v1"])).toEqual(["alice/game:v1"]); | |
| 186 | await put({ builds: null }); | |
| 187 | await buildsBecome(undefined); | |
| 188 | }); | |
| 189 | ||
| 190 | test("a cookie-signed PUT from another origin is refused, and one from the same origin is not", async () => { | |
| 191 | const signed = await fetch(`${base}/signin`, { method: "POST", body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), redirect: "manual" }); | |
| 192 | const cookie = (signed.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 193 | const send = (origin: string) => | |
| 194 | fetch(`${base}/api/v1/repos/alice/shelf/display/builds`, { | |
| 195 | method: "PUT", | |
| 196 | headers: { cookie, origin, "content-type": "application/json" }, | |
| 197 | body: JSON.stringify({ builds: ["alice/game:v1"] }), | |
| 198 | }); | |
| 199 | expect((await send("https://evil.example")).status).toBe(403); | |
| 200 | expect(await buildsBecome(undefined)).toBeUndefined(); | |
| 201 | expect((await send(base)).status).toBe(200); | |
| 202 | expect(await buildsBecome(["alice/game:v1"])).toEqual(["alice/game:v1"]); | |
| 203 | await put({ builds: null }); | |
| 204 | }); | |
| 205 | ||
| 206 | test("an agent that owns the display may not write its builds", async () => { | |
| 207 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "robo", email: "[email protected]", password: "a-good-passphrase" }); | |
| 208 | if (!made.ok) throw new Error(made.error); | |
| 209 | const repo = await createRepoRow(app.db, app.reposRoot, { ownerId: made.value.id, name: "shelf", visibility: "public" }); | |
| 210 | if (!repo.ok) throw new Error(repo.error); | |
| 211 | // The owner is an agent from here on: the same account, no longer a person. | |
| 212 | app.db.query("UPDATE user SET is_agent = 1 WHERE username = 'robo'").run(); | |
| 213 | const res = await fetch(`${base}/api/v1/repos/robo/shelf/display/builds`, { | |
| 214 | method: "PUT", | |
| 215 | headers: { authorization: `Bearer ${tokenFor(app, "robo", "rw")}`, "content-type": "application/json" }, | |
| 216 | body: JSON.stringify({ builds: null }), | |
| 217 | }); | |
| 218 | expect(res.status).toBe(403); | |
| 219 | }); | |
| 220 | ||
| 221 | describe("the arcade host", () => { | |
| 222 | const ask = (path: string, init: RequestInit = {}) => serveArcade(app, new Request(`http://arcade.forge.test${path}`, init)); | |
| 223 | const floor = (res: Response) => { | |
| 224 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 225 | expect(res.headers.get("referrer-policy")).toBeTruthy(); | |
| 226 | }; | |
| 227 | ||
| 228 | test("the shelf page is self-contained and its inline scripts carry the nonce", () => { | |
| 229 | expect(arcadePage()).not.toContain("googleapis"); | |
| 230 | const page = shelfPage({ title: "T", producer: undefined, data: { games: [] }, nonce: "abc123" }); | |
| 231 | const tags = page.match(/<script[^>]*>/g) ?? []; | |
| 232 | expect(tags.length).toBeGreaterThanOrEqual(2); | |
| 233 | for (const t of tags) expect(t).toContain('nonce="abc123"'); | |
| 234 | }); | |
| 235 | ||
| 236 | test("a malformed escape in the path is a 404, not a 500", async () => { | |
| 237 | const res = await ask("/%E0%A4%A"); | |
| 238 | expect(res.status).toBe(404); | |
| 239 | floor(res); | |
| 240 | }); | |
| 241 | ||
| 242 | test("a method other than GET and HEAD is a 405 with the floor", async () => { | |
| 243 | const res = await ask("/", { method: "POST" }); | |
| 244 | expect(res.status).toBe(405); | |
| 245 | floor(res); | |
| 246 | }); | |
| 247 | ||
| 248 | test("a cart of a private repository needs a grant", async () => { | |
| 249 | const priv = await createRepo(app, alice, { name: "secret", visibility: "private" }); | |
| 250 | if (!priv.ok) throw new Error(String(priv.error)); | |
| 251 | const path = `/carts/alice/secret/${"a".repeat(40)}/index.html`; | |
| 252 | const res = await ask(path); | |
| 253 | expect(res.status).toBe(404); | |
| 254 | floor(res); | |
| 255 | expect((await ask(`${path}?g=forged`)).status).toBe(404); | |
| 256 | }); | |
| 257 | ||
| 258 | test("a published demo names a display that exists, with an id that fits", async () => { | |
| 259 | const id = "A".repeat(22); | |
| 260 | for (const path of [`/displays/alice/plain/${id}.html`, `/displays/alice/nobody/${id}.html`, `/displays/alice/shelf/short.html`]) { | |
| 261 | const res = await ask(path); | |
| 262 | expect(res.status).toBe(404); | |
| 263 | floor(res); | |
| 264 | } | |
| 265 | }); | |
| 266 | ||
| 267 | test("with no Arcade display the root is a 404 with the floor", async () => { | |
| 268 | const res = await ask("/"); | |
| 269 | expect(res.status).toBe(404); | |
| 270 | floor(res); | |
| 271 | }); | |
| 272 | }); | |
| 273 | }); |
test/forge-looks.test.ts +1
| @@ -22,6 +22,7 @@ quietLogs(); | ||
| 22 | 22 | const NOT_A_PAGE: Record<string, string> = { |
| 23 | 23 | "/deploy-to": "a form for a forge admin that fills from its link; covered by test/pinned-page.test.ts", |
| 24 | 24 | "/asked": "no picture: the cap of 24 looks went to /notes, the page that now leads with a person's thoughts; /asked is covered by test/asked.test.ts", |
| 25 | "/displays": "no picture: the cap of 24 looks is spent; the page is covered by test/displays.test.ts", | |
| 25 | 26 | "/forges": "no picture: the cap of 24 looks went to the preview's /waves and /milestones; the page is covered by its own tests", |
| 26 | 27 | "/family": "no picture: the cap of 24 looks went to the preview's /waves and /milestones; the page is covered by its own tests", |
| 27 | 28 | "/llms.txt": "plain markdown for machines, not a page to picture", |
test/palette-roster.test.ts +4
| @@ -46,6 +46,7 @@ afterAll(async () => { | ||
| 46 | 46 | test("a site-admin person is offered the whole roster", () => { |
| 47 | 47 | expect(roster(admin)).toEqual([ |
| 48 | 48 | ["home", "Home", "your repositories"], |
| 49 | ["displays", "Displays", "shelves of builds: read one, choose its builds"], | |
| 49 | 50 | ["explore", "Explore", "on the web"], |
| 50 | 51 | ["profile", "Open a profile", "username or org"], |
| 51 | 52 | ["repos", "Repositories", "the repositories you may write"], |
| @@ -145,6 +146,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 145 | 146 | test("a site-admin agent is offered the roster without the person-only entries", () => { |
| 146 | 147 | expect(roster({ ...admin, kind: "agent" })).toEqual([ |
| 147 | 148 | ["home", "Home", "your repositories"], |
| 149 | ["displays", "Displays", "shelves of builds: read one, choose its builds"], | |
| 148 | 150 | ["explore", "Explore", "on the web"], |
| 149 | 151 | ["profile", "Open a profile", "username or org"], |
| 150 | 152 | ["repos", "Repositories", "the repositories you may write"], |
| @@ -209,6 +211,7 @@ test("no agent is offered Connected origins", () => { | ||
| 209 | 211 | test("a member person is offered the signed-in roster without the admin entries", () => { |
| 210 | 212 | expect(roster(member)).toEqual([ |
| 211 | 213 | ["home", "Home", "your repositories"], |
| 214 | ["displays", "Displays", "shelves of builds: read one, choose its builds"], | |
| 212 | 215 | ["explore", "Explore", "on the web"], |
| 213 | 216 | ["profile", "Open a profile", "username or org"], |
| 214 | 217 | ["repos", "Repositories", "the repositories you may write"], |
| @@ -270,6 +273,7 @@ test("a member person is offered the signed-in roster without the admin entries" | ||
| 270 | 273 | test("signed out, the palette offers sign-in and the public entries", () => { |
| 271 | 274 | expect(roster()).toEqual([ |
| 272 | 275 | ["home", "Home", "your repositories"], |
| 276 | ["displays", "Displays", "shelves of builds: read one, choose its builds"], | |
| 273 | 277 | ["explore", "Explore", "on the web"], |
| 274 | 278 | ["profile", "Open a profile", "username or org"], |
| 275 | 279 | ["repo", "Open a repository", "owner/name"], |
test/security-floor-routes.test.ts +5
| @@ -51,7 +51,12 @@ const HOOK = "needs a webhook, which the seed does not register"; | ||
| 51 | 51 | /** GET patterns the seed cannot fill → why. Requested with a placeholder all the same. */ |
| 52 | 52 | const SHOT = "needs a pin with a picture kept by refs/shots; the seed pins nothing"; |
| 53 | 53 | const CART = "the seed pins no build with a cart (test/build-cart.test.ts covers its headers)"; |
| 54 | const DEMO = "needs a published demo on a display; the seed has no display (test/displays.test.ts covers one)"; | |
| 54 | 55 | const UNSEEDED: Record<string, string> = { |
| 56 | "/:owner/:name/display/demo/:id/cover": DEMO, | |
| 57 | "/:owner/:name/display/demo/:id/download": DEMO, | |
| 58 | "/:owner/:name/display/demo/:id/shots": DEMO, | |
| 59 | "/:owner/:name/display/demo/:id/shots/:file": DEMO, | |
| 55 | 60 | "/:owner/-/teams/:team": ORG, |
| 56 | 61 | "/talk/:id": TALK, |
| 57 | 62 | "/bring/:id/:job": "needs a bring job of the signed-in person; the seed brings nothing", |
test/tui-displays.test.ts added +114
| @@ -0,0 +1,114 @@ | ||
| 1 | /** | |
| 2 | * Displays in the terminal: listed from the palette; a writer ticks a build | |
| 3 | * with space and the display's file changes; a reader, and an agent, cannot. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App as Forge } from "../src/app.ts"; | |
| 10 | import { pinBuild } from "../src/actions/builds.ts"; | |
| 11 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { getRepo } from "../src/core/repos.ts"; | |
| 13 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 14 | import { readDisplay } from "../src/display/config.ts"; | |
| 15 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 16 | import type { TuiIdentity } from "../src/tui/session.ts"; | |
| 17 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | import { settleApp } from "./helpers/tui.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | describe("displays in the terminal", () => { | |
| 24 | let dataDir: string; | |
| 25 | let forge: Forge; | |
| 26 | ||
| 27 | function boot(username: string) { | |
| 28 | const terminal = headlessTerminal(140, 32); | |
| 29 | const user = getUserByName(forge.db, username)!; | |
| 30 | const identity: TuiIdentity = { sshUsername: "t", remoteAddress: "127.0.0.1", user }; | |
| 31 | const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false }); | |
| 32 | app.start(); | |
| 33 | const key = (k: string, ctrl = false) => app.dispatch({ type: "key", key: k, ctrl, alt: false, shift: false }); | |
| 34 | return { | |
| 35 | text: () => app.screen.toText(), | |
| 36 | press: async (...keys: string[]) => { | |
| 37 | keys.forEach((k) => key(k)); | |
| 38 | await settleApp(app); | |
| 39 | await new Promise((r) => setTimeout(r, 150)); | |
| 40 | await settleApp(app); | |
| 41 | }, | |
| 42 | open: async () => { | |
| 43 | key("k", true); | |
| 44 | for (const ch of "Displays") key(ch); | |
| 45 | key("enter"); | |
| 46 | await settleApp(app); | |
| 47 | await new Promise((r) => setTimeout(r, 150)); | |
| 48 | await settleApp(app); | |
| 49 | }, | |
| 50 | stop: () => app.stop(), | |
| 51 | }; | |
| 52 | } | |
| 53 | ||
| 54 | beforeAll(async () => { | |
| 55 | dataDir = await mkdtemp(join(tmpdir(), "forge-tui-displays-")); | |
| 56 | forge = createApp({ dataDir, port: 0 }); | |
| 57 | for (const [username, first] of [["alice", true], ["bob", false]] as const) { | |
| 58 | const made = await createUser(forge.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first }); | |
| 59 | if (!made.ok) throw new Error(made.error); | |
| 60 | } | |
| 61 | const alice = getUserByName(forge.db, "alice")!; | |
| 62 | for (const name of ["game", "shelf"]) { | |
| 63 | const made = await createRepo(forge, alice, { name, visibility: "public" }); | |
| 64 | if (!made.ok) throw new Error(String(made.error)); | |
| 65 | } | |
| 66 | const game = getRepo(forge.db, "alice", "game")!; | |
| 67 | const c = await commitToBranch(forge, alice, game, { branch: "main", message: "one", files: [{ path: "one.txt", content: "one\n" }] }); | |
| 68 | if (!c.ok) throw new Error(JSON.stringify(c.error)); | |
| 69 | const pinned = await pinBuild(forge, alice, game, { label: "v1", oid: c.value.commitOid, note: "" }); | |
| 70 | if (!pinned.ok) throw new Error(JSON.stringify(pinned.error)); | |
| 71 | const shelf = getRepo(forge.db, "alice", "shelf")!; | |
| 72 | const d = await commitToBranch(forge, alice, shelf, { | |
| 73 | branch: "main", | |
| 74 | message: "display", | |
| 75 | files: [{ path: "display.json", content: JSON.stringify({ title: "Pocket Shelf", layout: "grid", sources: ["alice/game"], builds: ["alice/game:v1"] }) }], | |
| 76 | }); | |
| 77 | if (!d.ok) throw new Error(JSON.stringify(d.error)); | |
| 78 | }); | |
| 79 | afterAll(async () => { | |
| 80 | forge.close(); | |
| 81 | await rm(dataDir, { recursive: true, force: true }); | |
| 82 | }); | |
| 83 | ||
| 84 | const builds = async () => { | |
| 85 | const read = await readDisplay(forge, getRepo(forge.db, "alice", "shelf")!); | |
| 86 | return read?.ok ? read.value.builds : undefined; | |
| 87 | }; | |
| 88 | ||
| 89 | test("the list names the display and opening it shows its build", async () => { | |
| 90 | const h = boot("bob"); | |
| 91 | await h.open(); | |
| 92 | expect(h.text()).toContain("Pocket Shelf"); | |
| 93 | await h.press("enter"); | |
| 94 | expect(h.text()).toContain("alice/game:v1"); | |
| 95 | expect(h.text()).toContain("you read this display"); | |
| 96 | h.stop(); | |
| 97 | }); | |
| 98 | ||
| 99 | test("a reader's space changes nothing; a writer's space drops the build and the file follows", async () => { | |
| 100 | const reader = boot("bob"); | |
| 101 | await reader.open(); | |
| 102 | await reader.press("enter", " "); | |
| 103 | expect(await builds()).toEqual(["alice/game:v1"]); | |
| 104 | reader.stop(); | |
| 105 | ||
| 106 | const writer = boot("alice"); | |
| 107 | await writer.open(); | |
| 108 | await writer.press("enter"); | |
| 109 | expect(writer.text()).toContain("space chooses or drops a build"); | |
| 110 | await writer.press(" "); | |
| 111 | expect(await builds()).toEqual([]); | |
| 112 | writer.stop(); | |
| 113 | }); | |
| 114 | }); |
new above
offline