arcadible 1.0.33 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,6 +29,12 @@ export function remoteUnreachable(name) {
29
29
  return `Unable to reach ${TITLE}, and ${remoteName(name)} isn't saved.\nThe game runs without it until ${TITLE} is back.`;
30
30
  }
31
31
  // [function]
32
+ // a link the game made, to open in another window as another player
33
+ // (`&player=<name>`).
34
+ export function linkMade(url) {
35
+ return `Link made: ${url}`;
36
+ }
37
+ // [function]
32
38
  export function reloaded() {
33
39
  return `Reloaded at ${new Date().toTimeString().slice(0, 8)}.`;
34
40
  }
@@ -75,6 +81,10 @@ export function urlInvalid() {
75
81
  return "`--url` must start with http:// or https://.";
76
82
  }
77
83
  // [function]
84
+ export function wiresDropInvalid() {
85
+ return "`--wires-drop` must be a number of seconds, up to 3600.";
86
+ }
87
+ // [function]
78
88
  // --url's server sent no headers that let the play page frame it. `link`
79
89
  // says how to add them.
80
90
  export function urlNotFrameable(url, link) {
@@ -5,12 +5,14 @@
5
5
  // the pipeline as a build is released, and by arc serve (./entry.ts), so no
6
6
  // build carries an entry of the day its `arc` was installed.
7
7
  // [import]
8
+ import { stat } from "node:fs/promises";
8
9
  import { join } from "node:path";
9
10
  // [import]
10
11
  import { build } from "esbuild";
11
12
  import { pathExists } from "fs-extra";
12
13
  // [import]
13
- import { BUILD_FAILED } from "../config/code.js";
14
+ import { BUILD_FAILED, FUNCTION_TOO_LARGE } from "../config/code.js";
15
+ import { FUNCTION_SIZE } from "../config/limit.js";
14
16
  import * as phrase from "../phrase/index.js";
15
17
  import { ArcError } from "../util/error.js";
16
18
  // [declare]
@@ -29,7 +31,9 @@ export const WRONG = {
29
31
  };
30
32
  // [function]
31
33
  // bundles the runner whose code is at `main`, a full path, into `outfile`;
32
- // code that isn't there, or doesn't build, fails as a build does.
34
+ // code that isn't there, or doesn't build, fails as a build does, and a
35
+ // bundle past what Arcadible runs fails as the release would
36
+ // (function_too_large), before it's ever uploaded.
33
37
  //
34
38
  // `onPackages`, when given, hears the `@arcadible/` packages the bundle took
35
39
  // in, by name, each once, so a build can say when a function imports one
@@ -59,6 +63,10 @@ export async function bundle({ main, onPackages, outfile, }) {
59
63
  catch (ex) {
60
64
  throw new ArcError(BUILD_FAILED, phrase.runnerBuildFailed(ex instanceof Error ? ex.message : String(ex)), { cause: ex });
61
65
  }
66
+ const { size } = await stat(outfile);
67
+ if (size > FUNCTION_SIZE) {
68
+ throw new ArcError(FUNCTION_TOO_LARGE, phrase.functionTooLarge(size));
69
+ }
62
70
  onPackages?.(packagesOf(inputs));
63
71
  return outfile;
64
72
  }
@@ -7,6 +7,7 @@
7
7
  // reloads the game, and only the game, when told to. Its tab shows the
8
8
  // game's store icon, as the play page's does, or Arcadible's.
9
9
  // [import]
10
+ import crypto from "node:crypto";
10
11
  import { readFile } from "node:fs/promises";
11
12
  // [import]
12
13
  import { endWith, pathOf } from "./game.js";
@@ -31,6 +32,15 @@ export const TICKETS = "/_arcadible/api/tickets";
31
32
  // its own server: a verb after it.
32
33
  export const VALUES = "/_arcadible/api/values";
33
34
  export const JWKS = "/.well-known/jwks.json";
35
+ // the game's links (plan/SDKLINKS.md), for the page (the game's host), as
36
+ // the play page asks its own server: a link is made here, kept for the run,
37
+ // and opened as the page's own address with `?l=<id>`.
38
+ export const LINKS = "/_arcadible/api/links";
39
+ // a link's id, as Arcadible makes one: twelve characters of 62; and the
40
+ // most its data is, as JSON, in bytes.
41
+ const LINK_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
42
+ const LINK_ID = /^[0-9A-Za-z]{12}$/u;
43
+ const LINK_DATA_MAX = 1024;
34
44
  // where the page logs a guest in, when its game asked for a log-in and the
35
45
  // player took it: there's no account here, so the run gets a local player.
36
46
  export const LOGIN = "/_arcadible/api/login";
@@ -58,6 +68,7 @@ const SERVER_ROUTES = [
58
68
  [/^\/deleted_players$/u, "GET"],
59
69
  [/^\/tickets\/check$/u, "POST"],
60
70
  [/^\/values\/(?:read|write|remove|list)$/u, "POST"],
71
+ [/^\/wires\/(?:open|send)$/u, "POST"],
61
72
  ];
62
73
  // the most a values request holds: a call's values together, with room for
63
74
  // its keys and its JSON, as the API's (app/value.py).
@@ -67,6 +78,17 @@ const VALUES_BODY_MAX = 512 * 1024;
67
78
  const VALUE_WRITES = ["game", "player", "server"];
68
79
  // what the API says of a request it refuses (app/lib/python/offst/error.py),
69
80
  // in an error's `data`, with its status as `code`.
81
+ // each refusal's code, the status's word, as the API's own (its
82
+ // app/result.py's CODES; ERRORS.md).
83
+ const REFUSAL_CODES = {
84
+ 400: "invalid",
85
+ 403: "denied",
86
+ 404: "not_found",
87
+ 405: "method_not_allowed",
88
+ 409: "conflict",
89
+ 413: "too_large",
90
+ 507: "full",
91
+ };
70
92
  const REFUSALS = {
71
93
  400: [
72
94
  "Bad Request",
@@ -169,7 +191,7 @@ export function policy(src) {
169
191
  // with the play page's styles and loading screen; without a host that can,
170
192
  // the page frames the game by itself, and the game stands alone, as off
171
193
  // Arcadible.
172
- export function html(game, pictures = { art: false, icon: false }, opened) {
194
+ export function html(game, pictures = { art: false, icon: false }, opened, link) {
173
195
  // a window named by its address asks under its own path, and offers no
174
196
  // log-in: it plays as the player its address names.
175
197
  const own = opened ? `${AS}/${opened.player ? opened.player.id : GUEST}` : "";
@@ -182,6 +204,12 @@ export function html(game, pictures = { art: false, icon: false }, opened) {
182
204
  channel: game.channel,
183
205
  game: game.id,
184
206
  icon: pictures.icon ? ICON_PNG : null,
207
+ // the link the window was opened with (`?l=`), and whether one was
208
+ // named that's gone; and where the game's links are made, by arc serve
209
+ // itself, as the play page asks its own server
210
+ link: link ?? null,
211
+ linkGone: link === null,
212
+ links: `${own}${LINKS}`,
185
213
  // where a guest logs in, when the game asks for a log-in
186
214
  ...(opened ? {} : { logIn: LOGIN }),
187
215
  // who the game runs for: a local player (`arc serve --player`), or null,
@@ -245,7 +273,11 @@ export function html(game, pictures = { art: false, icon: false }, opened) {
245
273
  `;
246
274
  }
247
275
  // [function]
248
- // a request's body as JSON, or null: larger than `max`, or not JSON.
276
+ // what `readJson` resolves with for a body larger than it takes, which a
277
+ // values call answers `413`, as the API does.
278
+ const OVERSIZE = Symbol("oversize");
279
+ // [function]
280
+ // a request's body as JSON; OVERSIZE, larger than `max`; or null, not JSON.
249
281
  function readJson(req, max = BODY_MAX) {
250
282
  return new Promise((resolve) => {
251
283
  const chunks = [];
@@ -259,7 +291,7 @@ function readJson(req, max = BODY_MAX) {
259
291
  req.on("error", () => resolve(null));
260
292
  req.on("end", () => {
261
293
  try {
262
- resolve(size > max ? null : JSON.parse(Buffer.concat(chunks).toString()));
294
+ resolve(size > max ? OVERSIZE : JSON.parse(Buffer.concat(chunks).toString()));
263
295
  }
264
296
  catch {
265
297
  resolve(null);
@@ -268,6 +300,65 @@ function readJson(req, max = BODY_MAX) {
268
300
  });
269
301
  }
270
302
  // [function]
303
+ // a link from the game, for the page (the game's host), as the play page
304
+ // asks its own server: the game's data kept under a new id, for this run of
305
+ // arc serve, by the window's player, or its guest by the id the page sends
306
+ // (the browser's own, taken at its word). Only JSON is taken, as for a
307
+ // ticket. 400 a body that isn't an object; 403 no one to make it; 413 data
308
+ // past 1 KB as JSON. None of Arcadible's rate is kept, nor its 30 days: a
309
+ // link lasts until arc serve stops.
310
+ async function sendLink(req, res, { links, onLink, origin, playing, }) {
311
+ const type = ((req.headers["content-type"] ?? "").split(";")[0] ?? "").trim();
312
+ const asked = type.toLowerCase() === "application/json" ? await readJson(req) : null;
313
+ if (!isTable(asked)) {
314
+ res.writeHead(400, HEADERS).end();
315
+ return;
316
+ }
317
+ const guest = asked["guest"];
318
+ const by = playing
319
+ ? { guest: false, id: playing.id, name: playing.name }
320
+ : typeof guest === "string" && PLAYER_ID.test(guest)
321
+ ? { guest: true, id: guest, name: null }
322
+ : null;
323
+ if (!by) {
324
+ res.writeHead(403, HEADERS).end();
325
+ return;
326
+ }
327
+ const data = asked["data"] ?? null;
328
+ if (Buffer.byteLength(JSON.stringify(data)) > LINK_DATA_MAX) {
329
+ res.writeHead(413, HEADERS).end();
330
+ return;
331
+ }
332
+ let id = "";
333
+ for (let i = 0; i < 12; i++) {
334
+ id += LINK_ALPHABET.charAt(crypto.randomInt(LINK_ALPHABET.length));
335
+ }
336
+ links.set(id, { by, data, id });
337
+ onLink(`${origin}/?l=${id}`);
338
+ res.writeHead(200, {
339
+ ...HEADERS,
340
+ "content-type": "application/json; charset=utf-8",
341
+ });
342
+ res.end(JSON.stringify({ id }));
343
+ }
344
+ // [function]
345
+ // the link a window's address names, `?l=<id>`: the link, when it's one
346
+ // made this run; null for one that's gone, which every other is (one made
347
+ // before arc serve last started, or never: the expired case, to test);
348
+ // undefined with none.
349
+ function linkAsked(req, links) {
350
+ let id;
351
+ try {
352
+ id = new URL(req.url ?? "", "http://page").searchParams.get("l");
353
+ }
354
+ catch {
355
+ return undefined;
356
+ }
357
+ if (id === null)
358
+ return undefined;
359
+ return (LINK_ID.test(id) && links.get(id)) || null;
360
+ }
361
+ // [function]
271
362
  // a ticket for one of the game's servers, for the page (the game's host), or
272
363
  // for a shell on this machine. Only JSON is taken: a page elsewhere can't
273
364
  // send that across origins without asking first, and isn't answered. The
@@ -288,7 +379,7 @@ async function sendTicket(req, res, { playerOf, playing, tickets, }) {
288
379
  res.writeHead(400, HEADERS).end();
289
380
  return;
290
381
  }
291
- const { status, ticket } = await tickets.mint(asked["server"], player);
382
+ const { status, ticket } = await tickets.mint(asked["server"], player, asked["guest"]);
292
383
  if (status !== 200) {
293
384
  res.writeHead(status, HEADERS).end();
294
385
  return;
@@ -459,7 +550,7 @@ async function sendGameValues(req, res, verb, { player, values }) {
459
550
  ? await readJson(req, VALUES_BODY_MAX)
460
551
  : null;
461
552
  if (!isTable(body)) {
462
- refuse(400);
553
+ refuse(body === OVERSIZE ? 413 : 400);
463
554
  return;
464
555
  }
465
556
  const write = verb === "write" || verb === "remove";
@@ -592,8 +683,9 @@ function windowOf(pathname, named) {
592
683
  function sendRefusal(req, res, status, conflicts) {
593
684
  const [title, message] = REFUSALS[status] ?? ["", ""];
594
685
  sendData(req, res, status, {
595
- code: status,
686
+ code: REFUSAL_CODES[status] ?? "invalid",
596
687
  message,
688
+ status,
597
689
  title,
598
690
  type: "HttpError",
599
691
  ...(conflicts ? { conflicts } : {}),
@@ -609,7 +701,7 @@ function sendRefusal(req, res, status, conflicts) {
609
701
  async function sendValues(req, res, verb, values) {
610
702
  const body = await readJson(req, VALUES_BODY_MAX);
611
703
  if (!values || !isTable(body)) {
612
- sendRefusal(req, res, values ? 400 : 404);
704
+ sendRefusal(req, res, !values ? 404 : body === OVERSIZE ? 413 : 400);
613
705
  return;
614
706
  }
615
707
  // whether the call names one scope for all its keys; a list's does
@@ -675,7 +767,7 @@ async function sendValues(req, res, verb, values) {
675
767
  // refuses (app/src/web/arcadible-api's app/api/server.py). The game is the
676
768
  // project's, its channel is local, its players are the ones this run's
677
769
  // tickets named, and no one has deleted an account.
678
- async function sendServer(req, res, route, { game, tickets, values, }) {
770
+ async function sendServer(req, res, route, { game, tickets, values, wires, }) {
679
771
  const known = SERVER_ROUTES.find(([path]) => path.test(route));
680
772
  if (!known) {
681
773
  sendRefusal(req, res, 404);
@@ -719,6 +811,28 @@ async function sendServer(req, res, route, { game, tickets, values, }) {
719
811
  await sendValues(req, res, route.slice("/values/".length), values);
720
812
  return;
721
813
  }
814
+ // a function on a wire, as Arcadible's wires answer one
815
+ // (io-arcadible-wires' src/wires.js): a new wire's id, or a message
816
+ // passed on, marked as the server's
817
+ if (route.startsWith("/wires/")) {
818
+ if (!wires) {
819
+ sendRefusal(req, res, 404);
820
+ }
821
+ else if (route === "/wires/open") {
822
+ sendData(req, res, 200, { id: wires.open() });
823
+ }
824
+ else {
825
+ const sent = await readJson(req);
826
+ const status = isTable(sent) && Object.hasOwn(sent, "data")
827
+ ? wires.send(sent["wire"], sent["data"])
828
+ : 400;
829
+ if (status === 200)
830
+ sendData(req, res, 200, {});
831
+ else
832
+ sendRefusal(req, res, status);
833
+ }
834
+ return;
835
+ }
722
836
  const body = await readJson(req);
723
837
  // a list holds no ticket, and names no server.
724
838
  const asked = isTable(body) ? body : {};
@@ -738,7 +852,7 @@ async function sendServer(req, res, route, { game, tickets, values, }) {
738
852
  // `tickets` mints the game's, and publishes their key, and `playerOf(name)`
739
853
  // is a local player by name (./ticket.js). `faviconFile` is the play page's
740
854
  // favicon.ico, the package's own unless a test names another.
741
- export function pageHandler({ art = () => Promise.resolve(null), faviconFile = FAVICON, game, hostFile = null, icon = () => Promise.resolve(null), onRemote = () => null, playerOf = () => null, reloads, remote, tickets = null, values = null, }) {
855
+ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = FAVICON, game, hostFile = null, icon = () => Promise.resolve(null), onLink = () => undefined, onRemote = () => null, origin = "http://localhost", playerOf = () => null, reloads, remote, tickets = null, values = null, wires = null, }) {
742
856
  // the play page's favicon.ico, read once, or null when it can't be read,
743
857
  // which is tried again on the next request.
744
858
  let favicon = null;
@@ -751,6 +865,8 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
751
865
  };
752
866
  // the players windows were opened as, by id, so a window's path names one
753
867
  const named = new Map();
868
+ // the links made this run, by id
869
+ const links = new Map();
754
870
  return function (req, res) {
755
871
  // a target that can't be read as a URL (`//`) is no path of the page's.
756
872
  const whole = pathOf(req) ?? "";
@@ -767,6 +883,7 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
767
883
  game,
768
884
  tickets,
769
885
  values,
886
+ wires,
770
887
  });
771
888
  }
772
889
  if (values && pathname.startsWith(`${VALUES}/`)) {
@@ -795,6 +912,13 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
795
912
  }
796
913
  return sendTicket(req, res, { playerOf, playing, tickets });
797
914
  }
915
+ if (pathname === LINKS) {
916
+ if (req.method !== "POST") {
917
+ res.writeHead(405, { ...HEADERS, allow: "POST" }).end();
918
+ return Promise.resolve();
919
+ }
920
+ return sendLink(req, res, { links, onLink, origin, playing });
921
+ }
798
922
  if (opened) {
799
923
  // only the page's own API is under a window's path
800
924
  res.writeHead(404, HEADERS).end();
@@ -831,7 +955,7 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
831
955
  "content-security-policy": policy(game.src),
832
956
  "content-type": "text/html; charset=utf-8",
833
957
  });
834
- endWith(req, res, html(game, { art: Boolean(splash), icon: Boolean(mark) }, asked === undefined ? undefined : { player: asked }));
958
+ endWith(req, res, html(game, { art: Boolean(splash), icon: Boolean(mark) }, asked === undefined ? undefined : { player: asked }, linkAsked(req, links)));
835
959
  });
836
960
  }
837
961
  if (pathname === ICON) {
@@ -22,6 +22,9 @@ export const PREFIX = "/arcadible/runner";
22
22
  // players.primary): the player's id, or empty for a guest. Whatever a request
23
23
  // brings by that name is dropped.
24
24
  export const PLAYER = "x-arcadible-player";
25
+ // and a guest's id, beside it, as the dispatcher sets it: empty for a
26
+ // player and for no one.
27
+ export const GUEST = "x-arcadible-guest";
25
28
  // what a request can't bring to a function, as on Arcadible, where the
26
29
  // dispatcher drops each (app/src/cloudflare/io-arcadible-runner-dispatch):
27
30
  // its ticket, which the code never sees, and the headers Arcadible's own
@@ -90,6 +93,28 @@ const CORS = {
90
93
  "access-control-max-age": "600",
91
94
  };
92
95
  // [function]
96
+ // Arcadible's own answer, marked as the dispatcher marks it: a status, and
97
+ // a code the SDK's `functions.fetch` rejects with.
98
+ function refuse(res, status, code) {
99
+ res.writeHead(status, {
100
+ ...CORS,
101
+ "content-type": "application/json",
102
+ [REFUSAL]: code,
103
+ });
104
+ res.end(JSON.stringify({ code }));
105
+ }
106
+ // [function]
107
+ /**
108
+ * The answer under PREFIX for a project with no function, as the
109
+ * dispatcher's for a build with none: `404`, `no_function`.
110
+ */
111
+ export const noFunction = function (req, res) {
112
+ if (req.method === "OPTIONS")
113
+ res.writeHead(204, CORS).end();
114
+ else
115
+ refuse(res, 404, "no_function");
116
+ return Promise.resolve();
117
+ };
93
118
  // a port nothing listens on, on this machine.
94
119
  function freePort() {
95
120
  return new Promise((resolve, reject) => {
@@ -299,24 +324,22 @@ export async function runner({ dir, handler, hosts = [], main, origin, secrets =
299
324
  ? await tickets.check(ticket, origin)
300
325
  : { data: { code: "invalid" }, status: 422 };
301
326
  if (checked.status !== 200) {
302
- res.writeHead(401, {
303
- ...CORS,
304
- "content-type": "application/json",
305
- [REFUSAL]: checked.data.code,
306
- });
307
- res.end(JSON.stringify({ code: checked.data.code }));
327
+ refuse(res, 401, checked.data.code);
308
328
  return;
309
329
  }
310
330
  // a body past what a function may be sent, said or streamed, as the
311
- // dispatcher refuses it: a streamed one is read here, to hold it
312
- const body = await bodyOf(req);
331
+ // dispatcher refuses it: a streamed one is read here, to hold it. One
332
+ // that couldn't be read is `invalid`, as there.
333
+ let body;
334
+ try {
335
+ body = await bodyOf(req);
336
+ }
337
+ catch {
338
+ refuse(res, 400, "invalid");
339
+ return;
340
+ }
313
341
  if (body === null) {
314
- res.writeHead(413, {
315
- ...CORS,
316
- "content-type": "application/json",
317
- [REFUSAL]: TOO_LARGE,
318
- });
319
- res.end(JSON.stringify({ code: TOO_LARGE }));
342
+ refuse(res, 413, TOO_LARGE);
320
343
  return;
321
344
  }
322
345
  // the game's answer when its function failed, as the dispatcher's: why
@@ -336,10 +359,12 @@ export async function runner({ dir, handler, hosts = [], main, origin, secrets =
336
359
  return;
337
360
  }
338
361
  const player = checked.data.player;
362
+ const guest = checked.data.guest;
339
363
  const dropped = [...DROPPED, "host"];
340
364
  const headers = {
341
365
  ...Object.fromEntries(Object.entries(req.headers).filter(([name]) => !dropped.includes(name))),
342
366
  [PLAYER]: typeof player === "string" ? player : "",
367
+ [GUEST]: typeof guest === "string" ? guest : "",
343
368
  };
344
369
  if (body !== true) {
345
370
  delete headers["transfer-encoding"];
@@ -8,9 +8,10 @@ import http, {} from "node:http";
8
8
  import { gameHandler, pathOf } from "./game.js";
9
9
  import { pageHandler } from "./page.js";
10
10
  import { reloader } from "./reload.js";
11
- import { PREFIX as RUNNER, runner as startRunner, } from "./runner.js";
11
+ import { noFunction, PREFIX as RUNNER, runner as startRunner, } from "./runner.js";
12
12
  import { playerOf, tickets as ticketsFor } from "./ticket.js";
13
13
  import { values as valuesFor } from "./values.js";
14
+ import { PREFIX as WIRES, wires as wiresFor } from "./wires.js";
14
15
  // [declare]
15
16
  // the hostnames a browser may use for the page, on IPv4 and IPv6. `localhost`
16
17
  // is IPv6's ::1 on some systems, so both are listened on.
@@ -39,7 +40,7 @@ function listen(handler, port, address) {
39
40
  // or a guest. Resolves with
40
41
  // `{ page, game, reload(), close() }`: the page's origin, the game's URL,
41
42
  // and the controls.
42
- export async function serve({ art, files, hostFile = null, icon, info, keyFile, onRemote, player = null, port, remote, root, runner: runs = null, servers = [], connect = [], src, }) {
43
+ export async function serve({ art, files, hostFile = null, icon, info, keyFile, onLink, onRemote, player = null, port, remote, root, runner: runs = null, servers = [], connect = [], src, wiresDrop = null, }) {
43
44
  const origins = {
44
45
  game: `http://127.0.0.1:${port}`,
45
46
  page: `http://localhost:${port}`,
@@ -77,6 +78,16 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
77
78
  const values = root && tickets
78
79
  ? valuesFor({ isPlayer: (id) => tickets.player(id) !== null, root })
79
80
  : null;
81
+ // the game's wires, kept here: on the game's own origin for the game,
82
+ // and through the local server API for its function
83
+ const wires = tickets
84
+ ? wiresFor({
85
+ drop: wiresDrop,
86
+ game: info.id,
87
+ origin: origins.game,
88
+ tickets,
89
+ })
90
+ : null;
80
91
  const forPage = pageHandler({
81
92
  art,
82
93
  game: {
@@ -87,12 +98,15 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
87
98
  },
88
99
  hostFile,
89
100
  icon,
101
+ onLink,
90
102
  onRemote,
103
+ origin: origins.page,
91
104
  playerOf: (name) => playerOf(info.id, name),
92
105
  reloads,
93
106
  remote,
94
107
  tickets,
95
108
  values,
109
+ wires,
96
110
  });
97
111
  // a Map, so a Host named for one of an object's own members (`toString`)
98
112
  // is an unknown host like any other.
@@ -109,10 +123,17 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
109
123
  // what's under the runner's folder, as Arcadible's edge sends it on:
110
124
  // /arcadible/runner itself, like /arcadible/runnerx, is a file of
111
125
  // Arcadible's, like any other there, and isn't found.
112
- const forRunner = runner && onGame && pathname !== null && pathname.startsWith(`${RUNNER}/`)
113
- ? runner.handle
126
+ // A project with no function is answered as Arcadible answers a build
127
+ // with none.
128
+ const forRunner = onGame && pathname !== null && pathname.startsWith(`${RUNNER}/`)
129
+ ? (runner?.handle ?? noFunction)
114
130
  : null;
115
- const pick = forRunner ?? (host === undefined ? null : hosts.get(host));
131
+ // a game opens a wire at Arcadible's path on its own origin, whether
132
+ // its files are served here or framed from another server (--url)
133
+ const forWires = wires && onGame && (pathname === WIRES || pathname === `${WIRES}/`)
134
+ ? wires.handle
135
+ : null;
136
+ const pick = forRunner ?? forWires ?? (host === undefined ? null : hosts.get(host));
116
137
  if (!pick) {
117
138
  res.writeHead(421, { "content-type": "text/plain; charset=utf-8" });
118
139
  res.end("Misdirected Request\n");
@@ -136,7 +157,21 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
136
157
  failed();
137
158
  }
138
159
  };
160
+ // a connection to a wire: a WebSocket to its id under Arcadible's path,
161
+ // on the game's origin. Nothing else here is upgraded.
162
+ const upgrade = function (req, socket, head) {
163
+ const pathname = pathOf(req);
164
+ if (wires &&
165
+ req.headers.host === `127.0.0.1:${port}` &&
166
+ pathname !== null &&
167
+ pathname.startsWith(`${WIRES}/`)) {
168
+ wires.upgrade(req, socket, head);
169
+ return;
170
+ }
171
+ socket.end("HTTP/1.1 404 Not Found\r\nconnection: close\r\n\r\n");
172
+ };
139
173
  const ipv4 = await listen(handler, port, LOOPBACK[0]);
174
+ ipv4.on("upgrade", upgrade);
140
175
  // the IPv6 loopback is a bonus: a system without it still has 127.0.0.1.
141
176
  let ipv6 = null;
142
177
  try {
@@ -148,8 +183,10 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
148
183
  throw ex;
149
184
  }
150
185
  }
186
+ ipv6?.on("upgrade", upgrade);
151
187
  return {
152
188
  close() {
189
+ wires?.close();
153
190
  if (runner) {
154
191
  runner.close();
155
192
  }
@@ -171,6 +171,13 @@ export function tickets({ file, game, issuer, now = () => Date.now(), servers =
171
171
  if (sub !== undefined && (typeof sub !== "string" || !UUID.test(sub))) {
172
172
  return refused("invalid");
173
173
  }
174
+ // a guest's id, when the page named one: a claim of its own, and
175
+ // never beside a player
176
+ const guest = claims["guest"];
177
+ if (guest !== undefined &&
178
+ (typeof guest !== "string" || !UUID.test(guest))) {
179
+ return refused("invalid");
180
+ }
174
181
  const exp = claims["exp"];
175
182
  // good until its time and the leeway a clock is allowed, as the
176
183
  // Server SDK's `tickets.check` and the API's check give it
@@ -183,6 +190,7 @@ export function tickets({ file, game, issuer, now = () => Date.now(), servers =
183
190
  // an ISO time, as the API answers one, never the ticket's seconds
184
191
  expires_at: typeof exp === "number" ? new Date(exp * 1000).toISOString() : null,
185
192
  game: claims["game"],
193
+ guest: sub === undefined ? (guest ?? null) : null,
186
194
  id: claims["jti"],
187
195
  player: sub ?? null,
188
196
  site: claims["site"],
@@ -199,7 +207,9 @@ export function tickets({ file, game, issuer, now = () => Date.now(), servers =
199
207
  ],
200
208
  };
201
209
  },
202
- async mint(server, player = null) {
210
+ // `guest` is the id the page's device made for its guest, taken at its
211
+ // word, where Arcadible signs one: anything but an id names no one.
212
+ async mint(server, player = null, guest = null) {
203
213
  const origin = originOf(server);
204
214
  if (!origin) {
205
215
  return { status: 400, ticket: null };
@@ -222,7 +232,11 @@ export function tickets({ file, game, issuer, now = () => Date.now(), servers =
222
232
  jti: crypto.randomUUID(),
223
233
  site: uuidOf(`site:${String(game)}`),
224
234
  version: version ?? "0.0.0",
225
- ...(player ? { sub: player.id } : {}),
235
+ ...(player
236
+ ? { sub: player.id }
237
+ : typeof guest === "string" && UUID.test(guest)
238
+ ? { guest }
239
+ : {}),
226
240
  };
227
241
  const signing = [
228
242
  b64(JSON.stringify({ alg: "EdDSA", kid, typ: TYPE })),