atagen

jelq

public

an http based roguelike rpg about jelqing

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