atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
8ab6a1382c4c997e5e0544c2af62018ca376c78b
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/ui.htmlHtml499 lines18.9 KB
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<meta charset="utf-8">
5
<title>jelqd</title>
6
<style>
7
.frame { border: 2px inset; background: #fff; height: 85vh; overflow: scroll; padding: 4px; }
8
#log { white-space: pre-wrap; margin: 0; }
9
pre, li, p, td, label { overflow-wrap: anywhere; }
10
</style>
11
</head>
12
<body>
13
14
<h1>jelqd</h1>
15
<p>A roguelike played over HTTP. Pick a resource, pick a method, send it. The log on the right is everything the server has said to you.
16
Language <select id="locale"><option>en-GB</option><option>en-US</option><option>en-AU</option></select></p>
17
18
<table width="100%" cellspacing="6">
19
<tr>
20
<td width="45%" valign="top">
21
<div class="frame">
22
23
<div id="alerts"></div>
24
25
<form id="form">
26
<h3>Method</h3>
27
<div id="methods"></div>
28
<datalist id="excuses"></datalist>
29
30
<h3>Request</h3>
31
<table id="fields" cellpadding="2"></table>
32
33
<p><input type="submit" id="send" value="Send" style="font-size: 1.3em"></p>
34
35
<h3>Stats</h3>
36
<table id="stats" border="1" cellspacing="0" cellpadding="3"></table>
37
38
<h3>Resource</h3>
39
<div id="targets"></div>
40
</form>
41
42
<p><small>Every request goes through <code>/ui/send</code>, which replays it inside the server, so the page can show redirects and send methods and headers that browsers refuse.</small></p>
43
</div>
44
</td>
45
<td valign="top">
46
<div class="frame" id="frame"><pre id="log"></pre></div>
47
</td>
48
</tr>
49
</table>
50
51
<script>
52
const REL = "https://jelq.dev/rels/";
53
const METHODS = ["JELQ", "HOLD", "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE"];
54
const ALL_LUBES = ["", "application/baby-oil", "application/coconut-oil", "application/lotion", "application/vaseline", "text/plain; charset=spit", "image/jpeg"];
55
const DEATHS = ["vascular-event", "caught", "opened", "banned", "degloved", "zip", "watermelon", "overstayed", "run-ended"];
56
let stocked = null;
57
let excuses = [];
58
let nonce = null;
59
let inventorySeq = 0;
60
const STATS = [
61
  ["x-floor", "Floor"],
62
  ["x-self-reported-length", "Self-reported length"],
63
  ["x-girth", "Girth"],
64
  ["x-foreskin", "Foreskin"],
65
  ["x-friction", "Friction"],
66
  ["x-eq", "EQ (aim for 50 to 70)"],
67
  ["x-stamina", "Stamina"],
68
  ["x-suspicion", "Suspicion"],
69
  ["x-shame", "Shame"],
70
  ["x-cash", "Cash"],
71
];
72
const MEASURED = ["x-length", "Length"];
73
const QUIET = new Set(["link", "set-cookie", "server", "x-powered-by", "cache-control", "content-length", "content-type", "date"].concat(STATS.map(s => s[0]), MEASURED[0]));
74
75
const FIELDS = {
76
  seed: { label: "seed (unranked)", kind: "text" },
77
  technique: { label: "technique", kind: "select" },
78
  also: { label: "combo with", kind: "select" },
79
  intensity: { label: "intensity, 1 to 10", kind: "number", value: "5" },
80
  lube: { label: "Content-Type", header: "Content-Type", kind: "select" },
81
  patch: { label: "body", kind: "textarea", value: '[{"op": "test", "path": "/length", "value": 6}]' },
82
  range: { label: "Range", header: "Range", kind: "text", placeholder: "inches=0-2" },
83
  ifMatch: { label: "If-Match", header: "If-Match", kind: "text" },
84
  ifNoneMatch: { label: "If-None-Match", header: "If-None-Match", kind: "text" },
85
  ifModifiedSince: { label: "If-Modified-Since", header: "If-Modified-Since", kind: "text", placeholder: "an HTTP-date" },
86
  proxy: { label: "Proxy-Authorization", header: "Proxy-Authorization", kind: "text", placeholder: "Ruler 5.4" },
87
  upgrade: { label: "Upgrade", header: "Upgrade", kind: "select", options: ["", "underhand", "overhand"] },
88
  authorization: { label: "Authorization", header: "Authorization", kind: "text", placeholder: 'Excuse "homework"' },
89
  extra: { label: "other headers, one per line", kind: "textarea", placeholder: "Expect: gains" },
90
};
91
const BY_TARGET = {
92
  "runs POST": ["seed"],
93
  "run PATCH": ["patch"],
94
  "length GET": ["range"],
95
  "length HEAD": ["range"],
96
  "foreskin DELETE": ["ifMatch"],
97
  "elder GET": ["proxy", "ifModifiedSince"],
98
  "grip GET": ["upgrade"],
99
  "diagnosis GET": ["authorization", "ifNoneMatch"],
100
};
101
const GROUPS = [
102
  ["play", "Play"],
103
  ["shop", "Shop"],
104
  ["you", "You"],
105
  ["said", "From the last response"],
106
  ["reading", "Reading"],
107
  ["meta", "Meta"],
108
];
109
const GROUP_OF = { run: "play", floor: "play", drawer: "play", shop: "play", "shop-item": "shop", kitchen: "play", portal: "play", elder: "play", diagnosis: "play", length: "you", foreskin: "you", grip: "you", inventory: "you", footage: "you", techniques: "reading", thread: "reading" };
110
const NAMES = { run: "the run", thread: "the 2009 forum thread" };
111
const GLOBALS = [
112
  { key: "runs", group: "play", name: "start a new run", path: "/runs", methods: ["POST"] },
113
  { key: "global", group: "meta", name: "leaderboard", path: "/leaderboard", methods: ["GET", "HEAD", "OPTIONS"] },
114
  { key: "global", group: "meta", name: "graveyard", path: "/graveyard", methods: ["GET", "HEAD", "OPTIONS"] },
115
];
116
117
let run = null;
118
let linked = [];
119
let techniques = [];
120
let offered = [];
121
let challenged = false;
122
const etags = {};
123
let target = "/runs";
124
let method = "POST";
125
const values = {};
126
127
const $ = id => document.getElementById(id);
128
129
function short(path) {
130
  return path.replace(/[0-9a-f]{32}/, id => id.slice(0, 6) + "…");
131
}
132
133
function el(tag, props, ...children) {
134
  const node = Object.assign(document.createElement(tag), props || {});
135
  for (const child of children) node.append(child);
136
  return node;
137
}
138
139
function titled(text) {
140
  return text.charAt(0).toUpperCase() + text.slice(1);
141
}
142
143
function technique(name) {
144
  return techniques.find(t => t.name === name);
145
}
146
147
function clashes(a, b) {
148
  const rules = [a.lubricant, b.lubricant];
149
  return rules.includes("required") && rules.includes("forbidden");
150
}
151
152
// The options a field can take right now, or null for free text.
153
function options(name) {
154
  if (name === "technique") return techniques.map(t => t.name);
155
  if (name === "also") {
156
    const first = technique(fieldValue("technique"));
157
    if (!first || !first.lubricant) return [""];
158
    const partners = techniques.filter(t => t.lubricant && t.name !== first.name && !clashes(first, t));
159
    return [""].concat(partners.map(t => t.name));
160
  }
161
  if (name === "lube") {
162
    const lubes = stocked === null ? ALL_LUBES : ALL_LUBES.filter(l => l === "" || l.includes("/") && !l.startsWith("application/") || stocked.includes(l.replace("application/", "")));
163
    return lubeRule() === "required" ? lubes.filter(Boolean) : lubes;
164
  }
165
  return FIELDS[name].options || null;
166
}
167
168
function raw(name) {
169
  return values[name] ?? FIELDS[name].value ?? "";
170
}
171
172
function fieldValue(name) {
173
  const allowed = options(name);
174
  const value = raw(name);
175
  if (allowed && !allowed.includes(value)) return allowed[0] ?? "";
176
  return value;
177
}
178
179
function lubeRule() {
180
  const picked = [technique(fieldValue("technique")), technique(fieldValue("also"))].filter(Boolean);
181
  if (!picked.some(t => t.lubricant)) return "none";
182
  for (const rule of ["forbidden", "required"]) {
183
    if (picked.some(t => t.lubricant === rule)) return rule;
184
  }
185
  return "optional";
186
}
187
188
function allowedMethods(t) {
189
  return t.key === "run" && !techniques.length ? t.methods.filter(m => m !== "JELQ") : t.methods;
190
}
191
192
function targets() {
193
  const listed = run ? linked : [];
194
  const known = new Set(listed.concat(GLOBALS).map(t => t.path));
195
  const fresh = offered.filter((t, i) => !known.has(t.path) && offered.findIndex(o => o.path === t.path) === i);
196
  return listed.concat(fresh, GLOBALS);
197
}
198
199
function current() {
200
  return targets().find(t => t.path === target) || GLOBALS[0];
201
}
202
203
function chooseTarget(t) {
204
  const allowed = allowedMethods(t);
205
  target = t.path;
206
  method = allowed.includes("JELQ") ? "JELQ" : allowed.find(m => m !== "HEAD" && m !== "OPTIONS") || allowed[0];
207
  render();
208
}
209
210
function renderStats(headers) {
211
  const table = $("stats");
212
  table.replaceChildren();
213
  const stats = STATS.map(s => s[0] === "x-self-reported-length" && headers && MEASURED[0] in headers ? MEASURED : s);
214
  for (let i = 0; i < stats.length; i += 2) {
215
    const row = el("tr");
216
    for (const [name, label] of stats.slice(i, i + 2)) {
217
      const value = headers ? headers[name] : undefined;
218
      row.append(el("th", { align: "left", textContent: label }), el("td", { textContent: value === undefined ? "—" : value }));
219
    }
220
    table.append(row);
221
  }
222
}
223
224
function renderAlerts(list) {
225
  const box = $("alerts");
226
  box.replaceChildren();
227
  const alerts = [];
228
  for (const [name, value] of list || []) {
229
    if (name === "via") alerts.push(titled(value.split(" ").pop()) + " is at the door.");
230
    if (name === "x-observed-by") alerts.push((value === "cat" ? "The cat" : titled(value)) + " is watching.");
231
    if (name === "warning") {
232
      const text = (value.match(/"([^"]*)"/) || [, value])[1];
233
      alerts.push(titled(text) + (/[.!?]$/.test(text) ? "" : "."));
234
    }
235
  }
236
  const stamina = (list || []).find(([name]) => name === "x-stamina");
237
  if (stamina && stamina[1].startsWith("0/")) alerts.push("Exhausted. HOLD for the refractory period.");
238
  for (const alert of alerts) box.append(el("h2", { textContent: alert }));
239
}
240
241
function renderTargets() {
242
  const box = $("targets");
243
  box.replaceChildren();
244
  const all = targets();
245
  for (const [group, title] of GROUPS) {
246
    const members = all.filter(t => t.group === group);
247
    if (!members.length) continue;
248
    box.append(el("h4", { textContent: title }));
249
    for (const t of members) {
250
      const radio = el("input", { type: "radio", name: "target", checked: t.path === target, onchange: () => chooseTarget(t) });
251
      box.append(el("label", {}, radio, " " + t.name + " ", el("small", { textContent: short(t.path) })), el("br"));
252
    }
253
  }
254
}
255
256
function renderMethods() {
257
  const box = $("methods");
258
  box.replaceChildren();
259
  const allowed = allowedMethods(current());
260
  for (const m of METHODS.filter(m => allowed.includes(m))) {
261
    const radio = el("input", { type: "radio", name: "method", checked: m === method, onchange: () => { method = m; render(); } });
262
    const label = el("label", {}, radio, " ");
263
    label.append(m === "JELQ" ? el("big", {}, el("b", { textContent: "JELQ" })) : m);
264
    box.append(label, " ");
265
  }
266
}
267
268
function fieldNames() {
269
  const t = current();
270
  const key = t.key + " " + method;
271
  let names = BY_TARGET[key] || [];
272
  if (key === "run JELQ") {
273
    const chosen = technique(fieldValue("technique"));
274
    names = ["technique"];
275
    if (options("also").length > 1) names.push("also");
276
    if (chosen && chosen.lubricant) names.push("intensity");
277
    if (["required", "optional"].includes(lubeRule())) names.push("lube");
278
  }
279
  const scoped = run && !["runs", "global"].includes(t.key);
280
  const asked = challenged && scoped && !names.includes("authorization");
281
  return (asked ? ["authorization"] : []).concat(names);
282
}
283
284
function renderExcuses() {
285
  const said = excuses.concat(["the truth"]);
286
  $("excuses").replaceChildren(...said.map(e => el("option", {
287
    value: nonce ? 'Digest username="' + e + '", nonce="' + nonce + '"' : 'Excuse "' + e + '"',
288
  })));
289
}
290
291
function renderFields() {
292
  const table = $("fields");
293
  table.replaceChildren();
294
  for (const name of fieldNames()) {
295
    const f = FIELDS[name];
296
    let value = fieldValue(name);
297
    if (name === "ifMatch" && !value) value = values.ifMatch = etags[current().path] || "";
298
    const choices = options(name);
299
    let input;
300
    if (choices) {
301
      input = el("select", {}, ...choices.map(o => el("option", { value: o, textContent: o || "(none)", selected: o === value })));
302
    } else if (f.kind === "textarea") {
303
      input = el("textarea", { rows: 3, cols: 40, value, placeholder: f.placeholder || "" });
304
    } else {
305
      input = el("input", { type: f.kind, value, placeholder: f.placeholder || "", size: 30 });
306
    }
307
    input.oninput = () => { values[name] = input.value; };
308
    input.onchange = () => { values[name] = input.value; if (choices) renderFields(); };
309
    if (name === "authorization") input.setAttribute("list", "excuses");
310
    table.append(el("tr", {}, el("td", { align: "right", valign: "top", textContent: f.label }), el("td", {}, input)));
311
  }
312
  const extra = el("textarea", { rows: 3, cols: 40, value: raw("extra"), placeholder: FIELDS.extra.placeholder });
313
  extra.oninput = () => { values.extra = extra.value; };
314
  const more = el("details", { open: Boolean(values.extra) }, el("summary", { textContent: "more headers" }), extra);
315
  table.append(el("tr", {}, el("td"), el("td", {}, more)));
316
  $("send").value = method + " " + short(current().path);
317
}
318
319
function render() {
320
  if (!allowedMethods(current()).includes(method)) return chooseTarget(current());
321
  renderTargets();
322
  renderMethods();
323
  renderFields();
324
}
325
326
function parseLinks(header) {
327
  const resources = [];
328
  const moves = [];
329
  for (const match of header.matchAll(/<([^>]*)>((?:\s*;\s*[a-z-]+="[^"]*")*)/g)) {
330
    const params = Object.fromEntries([...match[2].matchAll(/([a-z-]+)="([^"]*)"/g)].map(p => [p[1], p[2]]));
331
    const name = (params.rel || "").replace(REL, "");
332
    if (name === "technique") {
333
      moves.push({ name: params.title, lubricant: params.lubricant || null });
334
      continue;
335
    }
336
    const methods = (params.allow || "GET").split(",").map(s => s.trim());
337
    resources.push({ key: name, group: GROUP_OF[name] || "play", name: NAMES[name] || params.title || name, path: match[1], methods });
338
  }
339
  return [resources, moves];
340
}
341
342
function hrefs(value, found) {
343
  if (value && typeof value === "object") {
344
    if (typeof value.href === "string") {
345
      const name = value.title || value.item || value.name || value.href.split("/").pop();
346
      found.push({ key: "offered", group: "said", name, path: value.href, methods: [value.method || "GET"] });
347
    }
348
    for (const key in value) hrefs(value[key], found);
349
  }
350
  return found;
351
}
352
353
function log(text) {
354
  $("log").prepend(text + "\n\n");
355
  $("frame").scrollTop = 0;
356
}
357
358
function describe(r) {
359
  const lines = ["< " + r.status + " " + r.reason];
360
  for (const [name, value] of r.headers) {
361
    if (!QUIET.has(name)) lines.push("< " + name + ": " + short(value));
362
  }
363
  let body = null;
364
  try { body = JSON.parse(r.body); } catch (e) {}
365
  if (body && typeof body === "object") {
366
    const rest = Object.assign({}, body);
367
    if (rest.detail) lines.push("  " + rest.detail);
368
    for (const key of ["type", "title", "status", "detail"]) delete rest[key];
369
    if (Object.keys(rest).length) lines.push(short(JSON.stringify(rest, null, 2)).replace(/^/gm, "  "));
370
  } else if (r.body) {
371
    const range = (r.headers.find(h => h[0] === "content-range") || [])[1] || "";
372
    const partial = r.status === 206 && range.match(/^bytes (\d+)-(\d+)\/(\d+)$/);
373
    lines.push("  " + r.body);
374
    if (partial) lines.push("  [bytes " + partial[1] + "-" + partial[2] + " of " + partial[3] + ". Half-mast.]");
375
  }
376
  return lines.join("\n");
377
}
378
379
function absorb(r, sentMethod, sentPath) {
380
  const headers = Object.fromEntries(r.headers.map(([n, v]) => [n.toLowerCase(), v]));
381
  if (headers.etag) etags[sentPath] = headers.etag;
382
  const digest = (headers["www-authenticate"] || "").match(/nonce="([^"]*)"/);
383
  if (digest && !(values.authorization || "").includes(digest[1])) {
384
    values.authorization = 'Digest username="", nonce="' + digest[1] + '"';
385
  }
386
  if ("www-authenticate" in headers) nonce = digest ? digest[1] : null;
387
  renderExcuses();
388
  let body = null;
389
  try { body = JSON.parse(r.body); } catch (e) {}
390
  const problem = body && typeof body.type === "string" ? body.type.split("/").pop() : null;
391
  const started = r.status === 201 && (sentPath === "/runs" || sentPath.startsWith("/runs?"));
392
393
  if (started) {
394
    run = headers.location;
395
    log("--- a new run has started at " + short(run) + " ---");
396
  }
397
  if ("x-eq" in headers) {
398
    renderStats(headers);
399
    renderAlerts(r.headers);
400
    challenged = r.status === 401 || "via" in headers;
401
  }
402
  if (headers.link) [linked, techniques] = parseLinks(headers.link);
403
  if (run) {
404
    const active = run;
405
    const seq = ++inventorySeq;
406
    fetch("/ui/send", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ method: "GET", path: run + "/inventory", headers: [], body: "" }) })
407
      .then(r => r.json())
408
      .then(r => {
409
        if (run !== active || seq !== inventorySeq) return;
410
        try {
411
          const held = JSON.parse(r.body);
412
          stocked = (held.items || []).map(i => i.name);
413
          excuses = held.excuses || [];
414
          renderExcuses();
415
          render();
416
        } catch (e) {}
417
      });
418
  }
419
  offered = body ? hrefs(body, []) : [];
420
  if (headers.location && !started) {
421
    offered.unshift({ key: "offered", group: "said", name: short(headers.location).split("/").pop() + " (Location)", path: headers.location, methods: ["GET"] });
422
  }
423
  const abandoned = sentMethod === "DELETE" && sentPath === run && r.status === 204;
424
  if (run && (abandoned || DEATHS.includes(problem))) {
425
    log("--- the run has ended ---");
426
    renderAlerts(null);
427
    challenged = false;
428
    run = null;
429
    linked = [];
430
    techniques = [];
431
  }
432
  if (started || !targets().some(t => t.path === target)) {
433
    const home = linked.find(t => t.key === "run");
434
    chooseTarget(home || GLOBALS[0]);
435
  } else {
436
    render();
437
  }
438
}
439
440
async function go(event) {
441
  event.preventDefault();
442
  const t = current();
443
  const key = t.key + " " + method;
444
  const value = name => fieldValue(name).trim();
445
  const headers = [];
446
  let path = t.path;
447
  let body = "";
448
  for (const name of fieldNames()) {
449
    const f = FIELDS[name];
450
    if (f.header && value(name)) headers.push([f.header, value(name)]);
451
  }
452
  if (fieldNames().includes("upgrade") && value("upgrade")) headers.push(["Connection", "upgrade"]);
453
  for (const line of raw("extra").split("\n")) {
454
    const at = line.indexOf(":");
455
    if (at > 0) headers.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);
456
  }
457
  if (key === "run JELQ") {
458
    const names = fieldNames();
459
    const chosen = [value("technique")].concat(names.includes("also") && value("also") ? [value("also")] : []);
460
    path += "?technique=" + encodeURIComponent(chosen.join(","));
461
    if (names.includes("intensity")) path += "&intensity=" + encodeURIComponent(value("intensity"));
462
  }
463
  if (key === "runs POST" && value("seed")) path += "?seed=" + encodeURIComponent(value("seed"));
464
  if (method === "PATCH") {
465
    headers.push(["Content-Type", "application/json-patch+json"]);
466
    body = value("patch");
467
  }
468
469
  const sent = ["> " + method + " " + short(path)].concat(headers.map(([name, v]) => "> " + name + ": " + v)).join("\n");
470
  headers.push(["Accept-Language", $("locale").value]);
471
  let r;
472
  try {
473
    const response = await fetch("/ui/send", {
474
      method: "POST",
475
      headers: { "Content-Type": "application/json" },
476
      body: JSON.stringify({ method, path, headers, body }),
477
    });
478
    r = await response.json();
479
  } catch (error) {
480
    log(sent + "\n! The server did not answer. Is jelqd still running? (" + error.message + ")");
481
    return;
482
  }
483
  if (!Array.isArray(r.headers)) {
484
    log(sent + "\n! The page could not read that reply:\n  " + JSON.stringify(r));
485
    return;
486
  }
487
  log(sent + "\n" + describe(r));
488
  absorb(r, method, path);
489
}
490
491
$("form").onsubmit = go;
492
$("locale").value = localStorage.getItem("locale") || "en-GB";
493
$("locale").onchange = () => localStorage.setItem("locale", $("locale").value);
494
renderStats(null);
495
render();
496
log("Welcome. Choose \"start a new run\" and send POST to begin. The newest turn is always at the top.");
497
</script>
498
</body>
499
</html>