atagen

jelq

public

an http based roguelike rpg about jelqing

Star0
Watch0
cddf59e37d5f7b2a7e0f8b644252196caf5a7e97
1
ssh://brewery@pls.lobotomise.me:33/atagen/jelq.git
src/ui.htmlHtml498 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
      const hint = name === "authorization" && nonce ? 'Digest username="helping Nan", nonce="' + nonce + '"' : f.placeholder || "";
306
      input = el("input", { type: f.kind, value, placeholder: hint, size: 30 });
307
    }
308
    input.oninput = () => { values[name] = input.value; };
309
    input.onchange = () => { values[name] = input.value; if (choices) renderFields(); };
310
    if (name === "authorization") input.setAttribute("list", "excuses");
311
    table.append(el("tr", {}, el("td", { align: "right", valign: "top", textContent: f.label }), el("td", {}, input)));
312
  }
313
  const extra = el("textarea", { rows: 3, cols: 40, value: raw("extra"), placeholder: FIELDS.extra.placeholder });
314
  extra.oninput = () => { values.extra = extra.value; };
315
  const more = el("details", { open: Boolean(values.extra) }, el("summary", { textContent: "more headers" }), extra);
316
  table.append(el("tr", {}, el("td"), el("td", {}, more)));
317
  $("send").value = method + " " + short(current().path);
318
}
319
320
function render() {
321
  if (!allowedMethods(current()).includes(method)) return chooseTarget(current());
322
  renderTargets();
323
  renderMethods();
324
  renderFields();
325
}
326
327
function parseLinks(header) {
328
  const resources = [];
329
  const moves = [];
330
  for (const match of header.matchAll(/<([^>]*)>((?:\s*;\s*[a-z-]+="[^"]*")*)/g)) {
331
    const params = Object.fromEntries([...match[2].matchAll(/([a-z-]+)="([^"]*)"/g)].map(p => [p[1], p[2]]));
332
    const name = (params.rel || "").replace(REL, "");
333
    if (name === "technique") {
334
      moves.push({ name: params.title, lubricant: params.lubricant || null });
335
      continue;
336
    }
337
    const methods = (params.allow || "GET").split(",").map(s => s.trim());
338
    resources.push({ key: name, group: GROUP_OF[name] || "play", name: NAMES[name] || params.title || name, path: match[1], methods });
339
  }
340
  return [resources, moves];
341
}
342
343
function hrefs(value, found) {
344
  if (value && typeof value === "object") {
345
    if (typeof value.href === "string") {
346
      const name = value.title || value.item || value.name || value.href.split("/").pop();
347
      found.push({ key: "offered", group: "said", name, path: value.href, methods: [value.method || "GET"] });
348
    }
349
    for (const key in value) hrefs(value[key], found);
350
  }
351
  return found;
352
}
353
354
function log(text) {
355
  $("log").prepend(text + "\n\n");
356
  $("frame").scrollTop = 0;
357
}
358
359
function describe(r) {
360
  const lines = ["< " + r.status + " " + r.reason];
361
  for (const [name, value] of r.headers) {
362
    if (!QUIET.has(name)) lines.push("< " + name + ": " + short(value));
363
  }
364
  let body = null;
365
  try { body = JSON.parse(r.body); } catch (e) {}
366
  if (body && typeof body === "object") {
367
    const rest = Object.assign({}, body);
368
    if (rest.detail) lines.push("  " + rest.detail);
369
    for (const key of ["type", "title", "status", "detail"]) delete rest[key];
370
    if (Object.keys(rest).length) lines.push(short(JSON.stringify(rest, null, 2)).replace(/^/gm, "  "));
371
  } else if (r.body) {
372
    const range = (r.headers.find(h => h[0] === "content-range") || [])[1] || "";
373
    const partial = r.status === 206 && range.match(/^bytes (\d+)-(\d+)\/(\d+)$/);
374
    lines.push("  " + r.body);
375
    if (partial) lines.push("  [bytes " + partial[1] + "-" + partial[2] + " of " + partial[3] + ". Half-mast.]");
376
  }
377
  return lines.join("\n");
378
}
379
380
function absorb(r, sentMethod, sentPath) {
381
  const headers = Object.fromEntries(r.headers.map(([n, v]) => [n.toLowerCase(), v]));
382
  if (headers.etag) etags[sentPath] = headers.etag;
383
  const digest = (headers["www-authenticate"] || "").match(/nonce="([^"]*)"/);
384
  if ("www-authenticate" in headers) nonce = digest ? digest[1] : null;
385
  renderExcuses();
386
  let body = null;
387
  try { body = JSON.parse(r.body); } catch (e) {}
388
  const problem = body && typeof body.type === "string" ? body.type.split("/").pop() : null;
389
  const started = r.status === 201 && (sentPath === "/runs" || sentPath.startsWith("/runs?"));
390
391
  if (started) {
392
    run = headers.location;
393
    log("--- a new run has started at " + short(run) + " ---");
394
  }
395
  if ("x-eq" in headers) {
396
    renderStats(headers);
397
    renderAlerts(r.headers);
398
    challenged = r.status === 401 || "via" in headers;
399
  }
400
  if (headers.link) [linked, techniques] = parseLinks(headers.link);
401
  if (run) {
402
    const active = run;
403
    const seq = ++inventorySeq;
404
    fetch("/ui/send", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ method: "GET", path: run + "/inventory", headers: [], body: "" }) })
405
      .then(r => r.json())
406
      .then(r => {
407
        if (run !== active || seq !== inventorySeq) return;
408
        try {
409
          const held = JSON.parse(r.body);
410
          stocked = (held.items || []).map(i => i.name);
411
          excuses = held.excuses || [];
412
          renderExcuses();
413
          render();
414
        } catch (e) {}
415
      });
416
  }
417
  offered = body ? hrefs(body, []) : [];
418
  if (headers.location && !started) {
419
    offered.unshift({ key: "offered", group: "said", name: short(headers.location).split("/").pop() + " (Location)", path: headers.location, methods: ["GET"] });
420
  }
421
  const abandoned = sentMethod === "DELETE" && sentPath === run && r.status === 204;
422
  if (run && (abandoned || DEATHS.includes(problem))) {
423
    log("--- the run has ended ---");
424
    renderAlerts(null);
425
    challenged = false;
426
    run = null;
427
    linked = [];
428
    techniques = [];
429
  }
430
  if (started || !targets().some(t => t.path === target)) {
431
    const home = linked.find(t => t.key === "run");
432
    chooseTarget(home || GLOBALS[0]);
433
  } else {
434
    render();
435
  }
436
}
437
438
async function go(event) {
439
  event.preventDefault();
440
  const t = current();
441
  const key = t.key + " " + method;
442
  const value = name => fieldValue(name).trim();
443
  const headers = [];
444
  let path = t.path;
445
  let body = "";
446
  for (const name of fieldNames()) {
447
    const f = FIELDS[name];
448
    if (f.header && value(name)) headers.push([f.header, value(name)]);
449
  }
450
  if (fieldNames().includes("upgrade") && value("upgrade")) headers.push(["Connection", "upgrade"]);
451
  for (const line of raw("extra").split("\n")) {
452
    const at = line.indexOf(":");
453
    if (at > 0) headers.push([line.slice(0, at).trim(), line.slice(at + 1).trim()]);
454
  }
455
  if (key === "run JELQ") {
456
    const names = fieldNames();
457
    const chosen = [value("technique")].concat(names.includes("also") && value("also") ? [value("also")] : []);
458
    path += "?technique=" + encodeURIComponent(chosen.join(","));
459
    if (names.includes("intensity")) path += "&intensity=" + encodeURIComponent(value("intensity"));
460
  }
461
  if (key === "runs POST" && value("seed")) path += "?seed=" + encodeURIComponent(value("seed"));
462
  if (method === "PATCH") {
463
    headers.push(["Content-Type", "application/json-patch+json"]);
464
    body = value("patch");
465
  }
466
467
  const sent = ["> " + method + " " + short(path)].concat(headers.map(([name, v]) => "> " + name + ": " + v)).join("\n");
468
  delete values.authorization;
469
  headers.push(["Accept-Language", $("locale").value]);
470
  let r;
471
  try {
472
    const response = await fetch("/ui/send", {
473
      method: "POST",
474
      headers: { "Content-Type": "application/json" },
475
      body: JSON.stringify({ method, path, headers, body }),
476
    });
477
    r = await response.json();
478
  } catch (error) {
479
    log(sent + "\n! The server did not answer. Is jelqd still running? (" + error.message + ")");
480
    return;
481
  }
482
  if (!Array.isArray(r.headers)) {
483
    log(sent + "\n! The page could not read that reply:\n  " + JSON.stringify(r));
484
    return;
485
  }
486
  log(sent + "\n" + describe(r));
487
  absorb(r, method, path);
488
}
489
490
$("form").onsubmit = go;
491
$("locale").value = localStorage.getItem("locale") || "en-GB";
492
$("locale").onchange = () => localStorage.setItem("locale", $("locale").value);
493
renderStats(null);
494
render();
495
log("Welcome. Choose \"start a new run\" and send POST to begin. The newest turn is always at the top.");
496
</script>
497
</body>
498
</html>