arcadible 1.0.33 → 1.0.34
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.
- package/dist/action/serve/tool.js +1 -0
- package/dist/action/wire/tool.js +36 -0
- package/dist/api.js +12 -0
- package/dist/command/serve.js +27 -8
- package/dist/command/wire/index.js +14 -0
- package/dist/command/wire/usage.js +43 -0
- package/dist/commands.js +7 -1
- package/dist/phrase/serve.js +4 -0
- package/dist/serve/page.js +112 -5
- package/dist/serve/runner.js +5 -0
- package/dist/serve/server.js +35 -2
- package/dist/serve/ticket.js +16 -2
- package/dist/serve/wires.js +231 -0
- package/dist/wires/room.js +214 -0
- package/npm-shrinkwrap.json +6 -5
- package/package.json +2 -1
|
@@ -204,6 +204,7 @@ export async function serveTool(conf) {
|
|
|
204
204
|
server_origins: servers,
|
|
205
205
|
}),
|
|
206
206
|
...(conf.host ? { hostFile: resolvePath(root, conf.host) } : {}),
|
|
207
|
+
wiresDrop: conf.wiresDrop ?? null,
|
|
207
208
|
};
|
|
208
209
|
// the runner's code, watched: a change runs the new code
|
|
209
210
|
const watchRunner = function (served) {
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// arc wire: a game's wires (plan/SDKWIRES.md), live messages between its
|
|
2
|
+
// players. What its owner sees of them is their usage: wires keep nothing,
|
|
3
|
+
// and nothing about one is set from here.
|
|
4
|
+
import { gameWireUsages } from "../../api.js";
|
|
5
|
+
import { GAME_UNAVAILABLE } from "../../config/code.js";
|
|
6
|
+
import { ArcError } from "../../util/error.js";
|
|
7
|
+
import { channelOf, CHANNELS, gameOf, headersOf, } from "../game.js";
|
|
8
|
+
import { gameUnavailable } from "../../phrase/index.js";
|
|
9
|
+
// [function]
|
|
10
|
+
// what the game's wires carried on each channel, or on one: this month's,
|
|
11
|
+
// and today's of it.
|
|
12
|
+
export async function usage(current, { channel, ...conf }) {
|
|
13
|
+
const where = channelOf(channel);
|
|
14
|
+
const id = await gameOf(conf);
|
|
15
|
+
const rows = (await gameWireUsages(id, null, headersOf(current))) ?? [];
|
|
16
|
+
// its owner always reads today's row for each channel: no rows at all is
|
|
17
|
+
// a game that isn't the caller's
|
|
18
|
+
if (rows.length === 0) {
|
|
19
|
+
throw new ArcError(GAME_UNAVAILABLE, gameUnavailable(id));
|
|
20
|
+
}
|
|
21
|
+
const today = new Date().toISOString().slice(0, 10);
|
|
22
|
+
const sum = (of) => ({
|
|
23
|
+
connections: of.reduce((total, each) => total + Number(each.connections ?? 0), 0),
|
|
24
|
+
messages: of.reduce((total, each) => total + Number(each.messages ?? 0), 0),
|
|
25
|
+
});
|
|
26
|
+
return {
|
|
27
|
+
channels: CHANNELS.filter((each) => !where || each === where).map((each) => {
|
|
28
|
+
const own = rows.filter((row) => row.channel === each);
|
|
29
|
+
return {
|
|
30
|
+
channel: each,
|
|
31
|
+
month: sum(own),
|
|
32
|
+
today: sum(own.filter((row) => row.day === today)),
|
|
33
|
+
};
|
|
34
|
+
}),
|
|
35
|
+
};
|
|
36
|
+
}
|
package/dist/api.js
CHANGED
|
@@ -105,6 +105,12 @@ const isValueCalls = shaped({
|
|
|
105
105
|
writes: num,
|
|
106
106
|
});
|
|
107
107
|
const isPause = shaped({ channel: str, reason: str });
|
|
108
|
+
const isWireUsage = shaped({
|
|
109
|
+
channel: str,
|
|
110
|
+
connections: opt(nul(either(num, str))),
|
|
111
|
+
day: str,
|
|
112
|
+
messages: opt(nul(either(num, str))),
|
|
113
|
+
});
|
|
108
114
|
const isUsage = shaped({
|
|
109
115
|
allowance: either(num, str),
|
|
110
116
|
channel: str,
|
|
@@ -300,6 +306,12 @@ export function gameFunctionUsages(id, params, headers) {
|
|
|
300
306
|
return answer(listed(isUsage), "a function's usage", get(endpoint(pathOf `/games/${id}/function_usages`, params), headers));
|
|
301
307
|
}
|
|
302
308
|
// [function]
|
|
309
|
+
// the usage of the caller's own game's wires this month: a row a channel
|
|
310
|
+
// and a day.
|
|
311
|
+
export function gameWireUsages(id, params, headers) {
|
|
312
|
+
return answer(listed(isWireUsage), "a game's wires' usage", get(endpoint(pathOf `/games/${id}/wire_usages`, params), headers));
|
|
313
|
+
}
|
|
314
|
+
// [function]
|
|
303
315
|
// pauses the function of the caller's own game on a channel.
|
|
304
316
|
export function putGameFunctionPause(id, channel, params, headers) {
|
|
305
317
|
return answer(isPause, "a pause", put(endpoint(pathOf `/games/${id}/function_pauses/${channel}`, params), null, headers));
|
package/dist/command/serve.js
CHANGED
|
@@ -41,6 +41,19 @@ function checkUrl(url) {
|
|
|
41
41
|
return Promise.reject(new ArcError(ARGUMENT_INVALID, phrase.urlInvalid()));
|
|
42
42
|
}
|
|
43
43
|
// [function]
|
|
44
|
+
// the seconds --wires-drop names, or null without it; a failure for what
|
|
45
|
+
// isn't a time to wait.
|
|
46
|
+
function checkDrop(seconds) {
|
|
47
|
+
if (seconds === null || typeof seconds === "undefined") {
|
|
48
|
+
return Promise.resolve(null);
|
|
49
|
+
}
|
|
50
|
+
const drop = Number(seconds);
|
|
51
|
+
if (Number.isFinite(drop) && drop > 0 && drop <= 3600) {
|
|
52
|
+
return Promise.resolve(drop);
|
|
53
|
+
}
|
|
54
|
+
return Promise.reject(new ArcError(ARGUMENT_INVALID, phrase.wiresDropInvalid()));
|
|
55
|
+
}
|
|
56
|
+
// [function]
|
|
44
57
|
// warns once for each of Arcadible's files that's a kept copy, or can't be
|
|
45
58
|
// had, rather than on every request.
|
|
46
59
|
function remoteWarnings({ quiet }) {
|
|
@@ -60,25 +73,25 @@ function remoteWarnings({ quiet }) {
|
|
|
60
73
|
export default defineCommand({
|
|
61
74
|
name: "serve",
|
|
62
75
|
options: {
|
|
63
|
-
port: {
|
|
76
|
+
"port": {
|
|
64
77
|
alias: "p",
|
|
65
78
|
default: PORT,
|
|
66
79
|
describe: "Serve on this port",
|
|
67
80
|
rc: true,
|
|
68
81
|
type: "number",
|
|
69
82
|
},
|
|
70
|
-
build: {
|
|
83
|
+
"build": {
|
|
71
84
|
default: true,
|
|
72
85
|
describe: "Run the build command first",
|
|
73
86
|
rc: true,
|
|
74
87
|
type: "boolean",
|
|
75
88
|
},
|
|
76
|
-
url: {
|
|
89
|
+
"url": {
|
|
77
90
|
describe: "Frame another server's page instead of deploy_dir",
|
|
78
91
|
rc: true,
|
|
79
92
|
type: "string",
|
|
80
93
|
},
|
|
81
|
-
open: {
|
|
94
|
+
"open": {
|
|
82
95
|
alias: "o",
|
|
83
96
|
default: false,
|
|
84
97
|
describe: "Open the play page in a web browser",
|
|
@@ -88,12 +101,16 @@ export default defineCommand({
|
|
|
88
101
|
// run the game for a logged-in player of this name, the same one each
|
|
89
102
|
// run; without it, a guest. Left out of the help until tickets ship,
|
|
90
103
|
// with the docs.
|
|
91
|
-
player: { hidden: true, rc: true, type: "string" },
|
|
104
|
+
"player": { hidden: true, rc: true, type: "string" },
|
|
92
105
|
// serve a play page's host built here, for working on the host itself;
|
|
93
106
|
// without it, Arcadible's own. Left out of the help.
|
|
94
|
-
host: { hidden: true, rc: true, type: "string" },
|
|
95
|
-
|
|
96
|
-
|
|
107
|
+
"host": { hidden: true, rc: true, type: "string" },
|
|
108
|
+
// drop each wire's connection this many seconds after it comes on, to
|
|
109
|
+
// try a game's rejoin. Left out of the help until wires ship, with the
|
|
110
|
+
// docs.
|
|
111
|
+
"wires-drop": { hidden: true, rc: true, type: "number" },
|
|
112
|
+
"quiet": QUIET,
|
|
113
|
+
"cwd": CWD,
|
|
97
114
|
},
|
|
98
115
|
// resolves with nothing, so the process goes on serving until it's
|
|
99
116
|
// stopped.
|
|
@@ -106,6 +123,7 @@ export default defineCommand({
|
|
|
106
123
|
aborting.sw = sw;
|
|
107
124
|
await checkPort(port);
|
|
108
125
|
const url = await checkUrl(argv.url);
|
|
126
|
+
const wiresDrop = await checkDrop(argv["wires-drop"]);
|
|
109
127
|
const served = await serveTool({
|
|
110
128
|
build: argv.build,
|
|
111
129
|
handler: {
|
|
@@ -135,6 +153,7 @@ export default defineCommand({
|
|
|
135
153
|
port,
|
|
136
154
|
root,
|
|
137
155
|
url,
|
|
156
|
+
wiresDrop,
|
|
138
157
|
});
|
|
139
158
|
sw.stop(true);
|
|
140
159
|
const stop = () => {
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// arc wire: a game's wires (plan/SDKWIRES.md), live messages between its
|
|
2
|
+
// players, relayed and never kept. A game makes and joins them itself, so
|
|
3
|
+
// what's here is what they came to: their usage, by channel. Left out of
|
|
4
|
+
// `arc --help` until wires ship, with the docs.
|
|
5
|
+
// [import]
|
|
6
|
+
import { defineCommand } from "../../cli/command.js";
|
|
7
|
+
import usage from "./usage.js";
|
|
8
|
+
// [export]
|
|
9
|
+
export default defineCommand({
|
|
10
|
+
commands: [usage],
|
|
11
|
+
hidden: true,
|
|
12
|
+
name: "wire",
|
|
13
|
+
summary: "Show what the game's wires carried",
|
|
14
|
+
});
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// [import]
|
|
2
|
+
import { defineCommand } from "../../cli/command.js";
|
|
3
|
+
import { p } from "../../util/log.js";
|
|
4
|
+
import { CHANNEL_SHOWS, CWD, JSON_OUTPUT, QUIET } from "../../cli/options.js";
|
|
5
|
+
import { run } from "../function/run.js";
|
|
6
|
+
import { table } from "../../util/table.js";
|
|
7
|
+
import { usage } from "../../action/wire/tool.js";
|
|
8
|
+
// [function]
|
|
9
|
+
// a count as it's read: 1,000,000.
|
|
10
|
+
function count(value) {
|
|
11
|
+
return value.toLocaleString("en-US");
|
|
12
|
+
}
|
|
13
|
+
// [function]
|
|
14
|
+
// each channel's wires as a table, a row each: today's, then the month's.
|
|
15
|
+
function rows(channels) {
|
|
16
|
+
return table([
|
|
17
|
+
[
|
|
18
|
+
"CHANNEL",
|
|
19
|
+
"MESSAGES TODAY",
|
|
20
|
+
"CONNECTIONS TODAY",
|
|
21
|
+
"MESSAGES THIS MONTH",
|
|
22
|
+
"CONNECTIONS THIS MONTH",
|
|
23
|
+
],
|
|
24
|
+
...channels.map((each) => [
|
|
25
|
+
each.channel,
|
|
26
|
+
count(each.today.messages),
|
|
27
|
+
count(each.today.connections),
|
|
28
|
+
count(each.month.messages),
|
|
29
|
+
count(each.month.connections),
|
|
30
|
+
]),
|
|
31
|
+
]);
|
|
32
|
+
}
|
|
33
|
+
// [export]
|
|
34
|
+
export default defineCommand({
|
|
35
|
+
name: "usage",
|
|
36
|
+
options: { ...CHANNEL_SHOWS, json: JSON_OUTPUT, quiet: QUIET, cwd: CWD },
|
|
37
|
+
run(argv, aborting) {
|
|
38
|
+
return run(argv, aborting, usage, ({ channels }) => {
|
|
39
|
+
p(rows(channels));
|
|
40
|
+
});
|
|
41
|
+
},
|
|
42
|
+
summary: "Show what the game's wires carried today and this month",
|
|
43
|
+
});
|
package/dist/commands.js
CHANGED
|
@@ -77,7 +77,7 @@ export const COMMANDS = [
|
|
|
77
77
|
name: "logout",
|
|
78
78
|
summary: `Log out of ${title}`,
|
|
79
79
|
},
|
|
80
|
-
// left out of `arc --help` until functions, keys, and
|
|
80
|
+
// left out of `arc --help` until functions, keys, values, and wires ship, with the
|
|
81
81
|
// docs.
|
|
82
82
|
{
|
|
83
83
|
hidden: true,
|
|
@@ -97,4 +97,10 @@ export const COMMANDS = [
|
|
|
97
97
|
name: "value",
|
|
98
98
|
summary: "Set, get, list, and remove the values you publish for the game",
|
|
99
99
|
},
|
|
100
|
+
{
|
|
101
|
+
hidden: true,
|
|
102
|
+
load: () => import("./command/wire/index.js"),
|
|
103
|
+
name: "wire",
|
|
104
|
+
summary: "Show what the game's wires carried",
|
|
105
|
+
},
|
|
100
106
|
];
|
package/dist/phrase/serve.js
CHANGED
|
@@ -75,6 +75,10 @@ export function urlInvalid() {
|
|
|
75
75
|
return "`--url` must start with http:// or https://.";
|
|
76
76
|
}
|
|
77
77
|
// [function]
|
|
78
|
+
export function wiresDropInvalid() {
|
|
79
|
+
return "`--wires-drop` must be a number of seconds, up to 3600.";
|
|
80
|
+
}
|
|
81
|
+
// [function]
|
|
78
82
|
// --url's server sent no headers that let the play page frame it. `link`
|
|
79
83
|
// says how to add them.
|
|
80
84
|
export function urlNotFrameable(url, link) {
|
package/dist/serve/page.js
CHANGED
|
@@ -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).
|
|
@@ -169,7 +180,7 @@ export function policy(src) {
|
|
|
169
180
|
// with the play page's styles and loading screen; without a host that can,
|
|
170
181
|
// the page frames the game by itself, and the game stands alone, as off
|
|
171
182
|
// Arcadible.
|
|
172
|
-
export function html(game, pictures = { art: false, icon: false }, opened) {
|
|
183
|
+
export function html(game, pictures = { art: false, icon: false }, opened, link) {
|
|
173
184
|
// a window named by its address asks under its own path, and offers no
|
|
174
185
|
// log-in: it plays as the player its address names.
|
|
175
186
|
const own = opened ? `${AS}/${opened.player ? opened.player.id : GUEST}` : "";
|
|
@@ -182,6 +193,12 @@ export function html(game, pictures = { art: false, icon: false }, opened) {
|
|
|
182
193
|
channel: game.channel,
|
|
183
194
|
game: game.id,
|
|
184
195
|
icon: pictures.icon ? ICON_PNG : null,
|
|
196
|
+
// the link the window was opened with (`?l=`), and whether one was
|
|
197
|
+
// named that's gone; and where the game's links are made, by arc serve
|
|
198
|
+
// itself, as the play page asks its own server
|
|
199
|
+
link: link ?? null,
|
|
200
|
+
linkGone: link === null,
|
|
201
|
+
links: `${own}${LINKS}`,
|
|
185
202
|
// where a guest logs in, when the game asks for a log-in
|
|
186
203
|
...(opened ? {} : { logIn: LOGIN }),
|
|
187
204
|
// who the game runs for: a local player (`arc serve --player`), or null,
|
|
@@ -268,6 +285,64 @@ function readJson(req, max = BODY_MAX) {
|
|
|
268
285
|
});
|
|
269
286
|
}
|
|
270
287
|
// [function]
|
|
288
|
+
// a link from the game, for the page (the game's host), as the play page
|
|
289
|
+
// asks its own server: the game's data kept under a new id, for this run of
|
|
290
|
+
// arc serve, by the window's player, or its guest by the id the page sends
|
|
291
|
+
// (the browser's own, taken at its word). Only JSON is taken, as for a
|
|
292
|
+
// ticket. 400 a body that isn't an object; 403 no one to make it; 413 data
|
|
293
|
+
// past 1 KB as JSON. None of Arcadible's rate is kept, nor its 30 days: a
|
|
294
|
+
// link lasts until arc serve stops.
|
|
295
|
+
async function sendLink(req, res, { links, playing }) {
|
|
296
|
+
const type = ((req.headers["content-type"] ?? "").split(";")[0] ?? "").trim();
|
|
297
|
+
const asked = type.toLowerCase() === "application/json" ? await readJson(req) : null;
|
|
298
|
+
if (!isTable(asked)) {
|
|
299
|
+
res.writeHead(400, HEADERS).end();
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const guest = asked["guest"];
|
|
303
|
+
const by = playing
|
|
304
|
+
? { guest: false, id: playing.id, name: playing.name }
|
|
305
|
+
: typeof guest === "string" && PLAYER_ID.test(guest)
|
|
306
|
+
? { guest: true, id: guest, name: null }
|
|
307
|
+
: null;
|
|
308
|
+
if (!by) {
|
|
309
|
+
res.writeHead(403, HEADERS).end();
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
const data = asked["data"] ?? null;
|
|
313
|
+
if (Buffer.byteLength(JSON.stringify(data)) > LINK_DATA_MAX) {
|
|
314
|
+
res.writeHead(413, HEADERS).end();
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
let id = "";
|
|
318
|
+
for (let i = 0; i < 12; i++) {
|
|
319
|
+
id += LINK_ALPHABET.charAt(crypto.randomInt(LINK_ALPHABET.length));
|
|
320
|
+
}
|
|
321
|
+
links.set(id, { by, data, id });
|
|
322
|
+
res.writeHead(200, {
|
|
323
|
+
...HEADERS,
|
|
324
|
+
"content-type": "application/json; charset=utf-8",
|
|
325
|
+
});
|
|
326
|
+
res.end(JSON.stringify({ id }));
|
|
327
|
+
}
|
|
328
|
+
// [function]
|
|
329
|
+
// the link a window's address names, `?l=<id>`: the link, when it's one
|
|
330
|
+
// made this run; null for one that's gone, which every other is (one made
|
|
331
|
+
// before arc serve last started, or never: the expired case, to test);
|
|
332
|
+
// undefined with none.
|
|
333
|
+
function linkAsked(req, links) {
|
|
334
|
+
let id;
|
|
335
|
+
try {
|
|
336
|
+
id = new URL(req.url ?? "", "http://page").searchParams.get("l");
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
return undefined;
|
|
340
|
+
}
|
|
341
|
+
if (id === null)
|
|
342
|
+
return undefined;
|
|
343
|
+
return (LINK_ID.test(id) && links.get(id)) || null;
|
|
344
|
+
}
|
|
345
|
+
// [function]
|
|
271
346
|
// a ticket for one of the game's servers, for the page (the game's host), or
|
|
272
347
|
// for a shell on this machine. Only JSON is taken: a page elsewhere can't
|
|
273
348
|
// send that across origins without asking first, and isn't answered. The
|
|
@@ -288,7 +363,7 @@ async function sendTicket(req, res, { playerOf, playing, tickets, }) {
|
|
|
288
363
|
res.writeHead(400, HEADERS).end();
|
|
289
364
|
return;
|
|
290
365
|
}
|
|
291
|
-
const { status, ticket } = await tickets.mint(asked["server"], player);
|
|
366
|
+
const { status, ticket } = await tickets.mint(asked["server"], player, asked["guest"]);
|
|
292
367
|
if (status !== 200) {
|
|
293
368
|
res.writeHead(status, HEADERS).end();
|
|
294
369
|
return;
|
|
@@ -675,7 +750,7 @@ async function sendValues(req, res, verb, values) {
|
|
|
675
750
|
// refuses (app/src/web/arcadible-api's app/api/server.py). The game is the
|
|
676
751
|
// project's, its channel is local, its players are the ones this run's
|
|
677
752
|
// tickets named, and no one has deleted an account.
|
|
678
|
-
async function sendServer(req, res, route, { game, tickets, values, }) {
|
|
753
|
+
async function sendServer(req, res, route, { game, tickets, values, wires, }) {
|
|
679
754
|
const known = SERVER_ROUTES.find(([path]) => path.test(route));
|
|
680
755
|
if (!known) {
|
|
681
756
|
sendRefusal(req, res, 404);
|
|
@@ -719,6 +794,28 @@ async function sendServer(req, res, route, { game, tickets, values, }) {
|
|
|
719
794
|
await sendValues(req, res, route.slice("/values/".length), values);
|
|
720
795
|
return;
|
|
721
796
|
}
|
|
797
|
+
// a function on a wire, as Arcadible's wires answer one
|
|
798
|
+
// (io-arcadible-wires' src/wires.js): a new wire's id, or a message
|
|
799
|
+
// passed on, marked as the server's
|
|
800
|
+
if (route.startsWith("/wires/")) {
|
|
801
|
+
if (!wires) {
|
|
802
|
+
sendRefusal(req, res, 404);
|
|
803
|
+
}
|
|
804
|
+
else if (route === "/wires/open") {
|
|
805
|
+
sendData(req, res, 200, { id: wires.open() });
|
|
806
|
+
}
|
|
807
|
+
else {
|
|
808
|
+
const sent = await readJson(req);
|
|
809
|
+
const status = isTable(sent) && Object.hasOwn(sent, "data")
|
|
810
|
+
? wires.send(sent["wire"], sent["data"])
|
|
811
|
+
: 400;
|
|
812
|
+
if (status === 200)
|
|
813
|
+
sendData(req, res, 200, {});
|
|
814
|
+
else
|
|
815
|
+
sendRefusal(req, res, status);
|
|
816
|
+
}
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
722
819
|
const body = await readJson(req);
|
|
723
820
|
// a list holds no ticket, and names no server.
|
|
724
821
|
const asked = isTable(body) ? body : {};
|
|
@@ -738,7 +835,7 @@ async function sendServer(req, res, route, { game, tickets, values, }) {
|
|
|
738
835
|
// `tickets` mints the game's, and publishes their key, and `playerOf(name)`
|
|
739
836
|
// is a local player by name (./ticket.js). `faviconFile` is the play page's
|
|
740
837
|
// 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, }) {
|
|
838
|
+
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, wires = null, }) {
|
|
742
839
|
// the play page's favicon.ico, read once, or null when it can't be read,
|
|
743
840
|
// which is tried again on the next request.
|
|
744
841
|
let favicon = null;
|
|
@@ -751,6 +848,8 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
|
|
|
751
848
|
};
|
|
752
849
|
// the players windows were opened as, by id, so a window's path names one
|
|
753
850
|
const named = new Map();
|
|
851
|
+
// the links made this run, by id
|
|
852
|
+
const links = new Map();
|
|
754
853
|
return function (req, res) {
|
|
755
854
|
// a target that can't be read as a URL (`//`) is no path of the page's.
|
|
756
855
|
const whole = pathOf(req) ?? "";
|
|
@@ -767,6 +866,7 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
|
|
|
767
866
|
game,
|
|
768
867
|
tickets,
|
|
769
868
|
values,
|
|
869
|
+
wires,
|
|
770
870
|
});
|
|
771
871
|
}
|
|
772
872
|
if (values && pathname.startsWith(`${VALUES}/`)) {
|
|
@@ -795,6 +895,13 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
|
|
|
795
895
|
}
|
|
796
896
|
return sendTicket(req, res, { playerOf, playing, tickets });
|
|
797
897
|
}
|
|
898
|
+
if (pathname === LINKS) {
|
|
899
|
+
if (req.method !== "POST") {
|
|
900
|
+
res.writeHead(405, { ...HEADERS, allow: "POST" }).end();
|
|
901
|
+
return Promise.resolve();
|
|
902
|
+
}
|
|
903
|
+
return sendLink(req, res, { links, playing });
|
|
904
|
+
}
|
|
798
905
|
if (opened) {
|
|
799
906
|
// only the page's own API is under a window's path
|
|
800
907
|
res.writeHead(404, HEADERS).end();
|
|
@@ -831,7 +938,7 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
|
|
|
831
938
|
"content-security-policy": policy(game.src),
|
|
832
939
|
"content-type": "text/html; charset=utf-8",
|
|
833
940
|
});
|
|
834
|
-
endWith(req, res, html(game, { art: Boolean(splash), icon: Boolean(mark) }, asked === undefined ? undefined : { player: asked }));
|
|
941
|
+
endWith(req, res, html(game, { art: Boolean(splash), icon: Boolean(mark) }, asked === undefined ? undefined : { player: asked }, linkAsked(req, links)));
|
|
835
942
|
});
|
|
836
943
|
}
|
|
837
944
|
if (pathname === ICON) {
|
package/dist/serve/runner.js
CHANGED
|
@@ -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
|
|
@@ -336,10 +339,12 @@ export async function runner({ dir, handler, hosts = [], main, origin, secrets =
|
|
|
336
339
|
return;
|
|
337
340
|
}
|
|
338
341
|
const player = checked.data.player;
|
|
342
|
+
const guest = checked.data.guest;
|
|
339
343
|
const dropped = [...DROPPED, "host"];
|
|
340
344
|
const headers = {
|
|
341
345
|
...Object.fromEntries(Object.entries(req.headers).filter(([name]) => !dropped.includes(name))),
|
|
342
346
|
[PLAYER]: typeof player === "string" ? player : "",
|
|
347
|
+
[GUEST]: typeof guest === "string" ? guest : "",
|
|
343
348
|
};
|
|
344
349
|
if (body !== true) {
|
|
345
350
|
delete headers["transfer-encoding"];
|
package/dist/serve/server.js
CHANGED
|
@@ -11,6 +11,7 @@ import { reloader } from "./reload.js";
|
|
|
11
11
|
import { 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, 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: {
|
|
@@ -93,6 +104,7 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
|
|
|
93
104
|
remote,
|
|
94
105
|
tickets,
|
|
95
106
|
values,
|
|
107
|
+
wires,
|
|
96
108
|
});
|
|
97
109
|
// a Map, so a Host named for one of an object's own members (`toString`)
|
|
98
110
|
// is an unknown host like any other.
|
|
@@ -112,7 +124,12 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
|
|
|
112
124
|
const forRunner = runner && onGame && pathname !== null && pathname.startsWith(`${RUNNER}/`)
|
|
113
125
|
? runner.handle
|
|
114
126
|
: null;
|
|
115
|
-
|
|
127
|
+
// a game opens a wire at Arcadible's path on its own origin, whether
|
|
128
|
+
// its files are served here or framed from another server (--url)
|
|
129
|
+
const forWires = wires && onGame && (pathname === WIRES || pathname === `${WIRES}/`)
|
|
130
|
+
? wires.handle
|
|
131
|
+
: null;
|
|
132
|
+
const pick = forRunner ?? forWires ?? (host === undefined ? null : hosts.get(host));
|
|
116
133
|
if (!pick) {
|
|
117
134
|
res.writeHead(421, { "content-type": "text/plain; charset=utf-8" });
|
|
118
135
|
res.end("Misdirected Request\n");
|
|
@@ -136,7 +153,21 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
|
|
|
136
153
|
failed();
|
|
137
154
|
}
|
|
138
155
|
};
|
|
156
|
+
// a connection to a wire: a WebSocket to its id under Arcadible's path,
|
|
157
|
+
// on the game's origin. Nothing else here is upgraded.
|
|
158
|
+
const upgrade = function (req, socket, head) {
|
|
159
|
+
const pathname = pathOf(req);
|
|
160
|
+
if (wires &&
|
|
161
|
+
req.headers.host === `127.0.0.1:${port}` &&
|
|
162
|
+
pathname !== null &&
|
|
163
|
+
pathname.startsWith(`${WIRES}/`)) {
|
|
164
|
+
wires.upgrade(req, socket, head);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
socket.end("HTTP/1.1 404 Not Found\r\nconnection: close\r\n\r\n");
|
|
168
|
+
};
|
|
139
169
|
const ipv4 = await listen(handler, port, LOOPBACK[0]);
|
|
170
|
+
ipv4.on("upgrade", upgrade);
|
|
140
171
|
// the IPv6 loopback is a bonus: a system without it still has 127.0.0.1.
|
|
141
172
|
let ipv6 = null;
|
|
142
173
|
try {
|
|
@@ -148,8 +179,10 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
|
|
|
148
179
|
throw ex;
|
|
149
180
|
}
|
|
150
181
|
}
|
|
182
|
+
ipv6?.on("upgrade", upgrade);
|
|
151
183
|
return {
|
|
152
184
|
close() {
|
|
185
|
+
wires?.close();
|
|
153
186
|
if (runner) {
|
|
154
187
|
runner.close();
|
|
155
188
|
}
|
package/dist/serve/ticket.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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 })),
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// arc serve's wires: the local stand-in for a game's wires on Arcadible
|
|
2
|
+
// (plan/SDKWIRES.md), in this process. A game opens one and connects to it
|
|
3
|
+
// on its own origin, at Arcadible's path, with its ticket, and its function
|
|
4
|
+
// opens and sends through the local server API. Each wire runs the rules
|
|
5
|
+
// Arcadible's run (../wires/room.ts), so a game meets the same wire in
|
|
6
|
+
// both: who's on, the one order, who a message is from, and the limits.
|
|
7
|
+
// Nothing reaches Cloudflare, and nothing is kept.
|
|
8
|
+
// [import]
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
// [import]
|
|
11
|
+
import { WebSocketServer } from "ws";
|
|
12
|
+
// [import]
|
|
13
|
+
import { CLOSED, createRoom, LIMITS, PING, PONG, PROTOCOL, } from "../wires/room.js";
|
|
14
|
+
import { CHANNEL } from "./ticket.js";
|
|
15
|
+
// [declare]
|
|
16
|
+
// where wires answer on a build's own origin, as on Arcadible
|
|
17
|
+
// (io-arcadible-wires' src/wires.js).
|
|
18
|
+
export const PREFIX = "/arcadible/wires";
|
|
19
|
+
// what marks an answer as Arcadible's own refusal, with its code.
|
|
20
|
+
export const REFUSAL = "x-arcadible-refusal";
|
|
21
|
+
// a wire's id, as Arcadible's: 16 random bytes, then 16 of their mark, each
|
|
22
|
+
// as base64url.
|
|
23
|
+
const ID = /^[\w-]{44}$/u;
|
|
24
|
+
const PART = 22;
|
|
25
|
+
// any origin may ask, as a game's does: the ticket is the proof, never the
|
|
26
|
+
// origin, and a dev server framed with --url is another origin.
|
|
27
|
+
const CORS = {
|
|
28
|
+
"access-control-allow-headers": "authorization, content-type",
|
|
29
|
+
"access-control-allow-methods": "POST, OPTIONS",
|
|
30
|
+
"access-control-allow-origin": "*",
|
|
31
|
+
"access-control-expose-headers": REFUSAL,
|
|
32
|
+
"access-control-max-age": "600",
|
|
33
|
+
};
|
|
34
|
+
// the largest frame a connection may send: a message, with room around it.
|
|
35
|
+
const FRAME_MAX = LIMITS.message * 4 + 64;
|
|
36
|
+
// [function]
|
|
37
|
+
// arc serve's wires for `game`, on its own `origin`, where a ticket for a
|
|
38
|
+
// wire is for. `tickets` are arc serve's own (./ticket.ts), which say who's
|
|
39
|
+
// connecting. `drop`, in seconds, drops each connection that long after it
|
|
40
|
+
// comes on, so a game's rejoin is tried without a network to break.
|
|
41
|
+
export function wires({ drop = null, game, origin, tickets, }) {
|
|
42
|
+
// an id's mark, over the game, the local channel, and its random part.
|
|
43
|
+
// Arcadible's is made with a secret; here the game's own id stands in,
|
|
44
|
+
// since no one on this machine is kept out: an id is still this game's
|
|
45
|
+
// alone, and one made in an earlier run still opens its wire, as a
|
|
46
|
+
// match kept in the project's values expects.
|
|
47
|
+
const mark = function (random) {
|
|
48
|
+
return crypto
|
|
49
|
+
.createHmac("sha256", `arc serve wires:${String(game)}`)
|
|
50
|
+
.update(`${String(game)}:${CHANNEL}:${random}`)
|
|
51
|
+
.digest()
|
|
52
|
+
.subarray(0, 16)
|
|
53
|
+
.toString("base64url");
|
|
54
|
+
};
|
|
55
|
+
const make = function () {
|
|
56
|
+
const random = crypto.randomBytes(16).toString("base64url");
|
|
57
|
+
return `${random}${mark(random)}`;
|
|
58
|
+
};
|
|
59
|
+
const isOurs = function (id) {
|
|
60
|
+
return (typeof id === "string" &&
|
|
61
|
+
ID.test(id) &&
|
|
62
|
+
mark(id.slice(0, PART)) === id.slice(PART));
|
|
63
|
+
};
|
|
64
|
+
// the wires with anyone on them, by id: one with no one isn't anywhere
|
|
65
|
+
const running = new Map();
|
|
66
|
+
const wire = function (id) {
|
|
67
|
+
let found = running.get(id);
|
|
68
|
+
if (!found) {
|
|
69
|
+
const on = new Map();
|
|
70
|
+
found = {
|
|
71
|
+
on,
|
|
72
|
+
room: createRoom({
|
|
73
|
+
deliver(key, text) {
|
|
74
|
+
on.get(key)?.socket.send(text);
|
|
75
|
+
},
|
|
76
|
+
drop(key, code, reason) {
|
|
77
|
+
on.get(key)?.socket.close(code, reason);
|
|
78
|
+
},
|
|
79
|
+
list: () => [...on.values()],
|
|
80
|
+
}),
|
|
81
|
+
};
|
|
82
|
+
running.set(id, found);
|
|
83
|
+
}
|
|
84
|
+
return found;
|
|
85
|
+
};
|
|
86
|
+
// what hasn't been heard from in too long is dropped, as Arcadible's
|
|
87
|
+
// alarm drops it
|
|
88
|
+
const sweeper = setInterval(() => {
|
|
89
|
+
for (const each of running.values())
|
|
90
|
+
each.room.sweep();
|
|
91
|
+
}, LIMITS.idle);
|
|
92
|
+
sweeper.unref();
|
|
93
|
+
const server = new WebSocketServer({
|
|
94
|
+
// the protocol's name is answered alone: the ticket beside it isn't one
|
|
95
|
+
handleProtocols: (offered) => (offered.has(PROTOCOL) ? PROTOCOL : false),
|
|
96
|
+
maxPayload: FRAME_MAX,
|
|
97
|
+
noServer: true,
|
|
98
|
+
});
|
|
99
|
+
// a game's ticket, checked for the game's origin: who it names, or the
|
|
100
|
+
// code it's refused with
|
|
101
|
+
const memberOf = async function (ticket) {
|
|
102
|
+
const checked = typeof ticket === "string"
|
|
103
|
+
? await tickets.check(ticket, origin)
|
|
104
|
+
: { data: { code: "invalid" }, status: 422 };
|
|
105
|
+
if (checked.status !== 200)
|
|
106
|
+
return { code: checked.data.code };
|
|
107
|
+
const { guest, player } = checked.data;
|
|
108
|
+
if (typeof player === "string") {
|
|
109
|
+
return {
|
|
110
|
+
member: {
|
|
111
|
+
guest: false,
|
|
112
|
+
id: player,
|
|
113
|
+
name: tickets.player(player)?.name ?? null,
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
// a guest whose page named no id is no one, and may not come on
|
|
118
|
+
return typeof guest === "string"
|
|
119
|
+
? { member: { guest: true, id: guest, name: null } }
|
|
120
|
+
: { code: "denied" };
|
|
121
|
+
};
|
|
122
|
+
let keys = 0;
|
|
123
|
+
return {
|
|
124
|
+
close() {
|
|
125
|
+
clearInterval(sweeper);
|
|
126
|
+
for (const each of running.values()) {
|
|
127
|
+
for (const { socket } of each.on.values())
|
|
128
|
+
socket.terminate();
|
|
129
|
+
}
|
|
130
|
+
running.clear();
|
|
131
|
+
server.close();
|
|
132
|
+
},
|
|
133
|
+
async handle(req, res) {
|
|
134
|
+
if (req.method === "OPTIONS") {
|
|
135
|
+
res.writeHead(204, CORS).end();
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const refuse = function (status, code) {
|
|
139
|
+
res.writeHead(status, {
|
|
140
|
+
...CORS,
|
|
141
|
+
"content-type": "application/json",
|
|
142
|
+
[REFUSAL]: code,
|
|
143
|
+
});
|
|
144
|
+
res.end(JSON.stringify({ code }));
|
|
145
|
+
};
|
|
146
|
+
if (req.method !== "POST") {
|
|
147
|
+
refuse(405, "invalid");
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const [scheme, ticket] = (req.headers.authorization ?? "").split(" ");
|
|
151
|
+
const who = await memberOf(scheme?.toLowerCase() === "bearer" ? ticket : null);
|
|
152
|
+
if ("code" in who) {
|
|
153
|
+
refuse(who.code === "denied" ? 403 : 401, who.code);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
res.writeHead(200, { ...CORS, "content-type": "application/json" });
|
|
157
|
+
res.end(JSON.stringify({ id: make() }));
|
|
158
|
+
},
|
|
159
|
+
open: make,
|
|
160
|
+
send(id, data) {
|
|
161
|
+
if (!isOurs(id) || data === undefined)
|
|
162
|
+
return 400;
|
|
163
|
+
if (Buffer.byteLength(JSON.stringify(data)) > LIMITS.message)
|
|
164
|
+
return 413;
|
|
165
|
+
// with no one on, it's passed to no one
|
|
166
|
+
running.get(id)?.room.server(data);
|
|
167
|
+
return 200;
|
|
168
|
+
},
|
|
169
|
+
upgrade(req, socket, head) {
|
|
170
|
+
const id = (req.url ?? "").split("?")[0]?.slice(PREFIX.length + 1) ?? "";
|
|
171
|
+
const offered = (req.headers["sec-websocket-protocol"] ?? "")
|
|
172
|
+
.split(",")
|
|
173
|
+
.map((each) => each.trim());
|
|
174
|
+
const ticket = offered.find((each) => each !== PROTOCOL);
|
|
175
|
+
server.handleUpgrade(req, socket, head, (ws) => {
|
|
176
|
+
// a connection that's refused opens, and closes with why: a
|
|
177
|
+
// browser is told nothing of one that never opens
|
|
178
|
+
const refuse = (code) => ws.close(CLOSED[code], code);
|
|
179
|
+
ws.on("error", () => ws.terminate());
|
|
180
|
+
if (!offered.includes(PROTOCOL) || !isOurs(id)) {
|
|
181
|
+
refuse("invalid");
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
void memberOf(ticket).then((who) => {
|
|
185
|
+
if ("code" in who) {
|
|
186
|
+
refuse(who.code);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
const { on, room } = wire(id);
|
|
190
|
+
const refused = room.admit(who.member);
|
|
191
|
+
if (refused) {
|
|
192
|
+
if (on.size === 0)
|
|
193
|
+
running.delete(id);
|
|
194
|
+
refuse(refused);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
keys += 1;
|
|
198
|
+
const key = String(keys);
|
|
199
|
+
const mine = {
|
|
200
|
+
heard: Date.now(),
|
|
201
|
+
key,
|
|
202
|
+
member: who.member,
|
|
203
|
+
socket: ws,
|
|
204
|
+
};
|
|
205
|
+
on.set(key, mine);
|
|
206
|
+
ws.on("message", (data, isBinary) => {
|
|
207
|
+
mine.heard = Date.now();
|
|
208
|
+
if (isBinary)
|
|
209
|
+
return;
|
|
210
|
+
const text = data.toString();
|
|
211
|
+
if (text === PING)
|
|
212
|
+
ws.send(PONG);
|
|
213
|
+
else
|
|
214
|
+
room.said(key, text);
|
|
215
|
+
});
|
|
216
|
+
ws.on("close", () => {
|
|
217
|
+
on.delete(key);
|
|
218
|
+
room.left(who.member);
|
|
219
|
+
if (on.size === 0)
|
|
220
|
+
running.delete(id);
|
|
221
|
+
});
|
|
222
|
+
room.joined(key);
|
|
223
|
+
if (drop !== null) {
|
|
224
|
+
setTimeout(() => ws.terminate(), drop * 1000).unref();
|
|
225
|
+
}
|
|
226
|
+
// a ticket that couldn't be checked at all: no one comes on
|
|
227
|
+
}, () => refuse("unavailable"));
|
|
228
|
+
});
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// A wire's rules (plan/SDKWIRES.md): who's on it, the one order its messages
|
|
2
|
+
// go out in, who each is from, and its limits. On Arcadible it's what each
|
|
3
|
+
// wire's Durable Object runs (io-arcadible-wires); under arc serve it's this
|
|
4
|
+
// module itself, as it's built (serve/wires.ts), so a game meets the same
|
|
5
|
+
// wire in both. It holds no connection: whatever runs it says who's
|
|
6
|
+
// connected (`list`), and it says what to send to whom (`deliver`) and whom
|
|
7
|
+
// to drop (`drop`). It imports nothing, so a runtime runs it as it is.
|
|
8
|
+
// [declare]
|
|
9
|
+
/** The protocol a connection speaks, named as it opens. */
|
|
10
|
+
export const PROTOCOL = "arcadible-wire.v1";
|
|
11
|
+
/** What a connection sends to say it's there, and what it's answered. */
|
|
12
|
+
export const PING = "ping";
|
|
13
|
+
export const PONG = "pong";
|
|
14
|
+
/**
|
|
15
|
+
* A wire's limits (LIMITS.md): a message's size as JSON, in bytes; a
|
|
16
|
+
* member's sends a second, and at once; the wire's, every member's
|
|
17
|
+
* together; its members; one member's connections; and how long a
|
|
18
|
+
* connection may go unheard, in milliseconds.
|
|
19
|
+
*/
|
|
20
|
+
export const LIMITS = {
|
|
21
|
+
connections: 8,
|
|
22
|
+
idle: 120_000,
|
|
23
|
+
members: 100,
|
|
24
|
+
message: 1024,
|
|
25
|
+
rate: 20,
|
|
26
|
+
rateBurst: 40,
|
|
27
|
+
wireRate: 200,
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* The code a connection is closed with, for each reason: in the range a
|
|
31
|
+
* protocol keeps for itself, each the HTTP status that means the same.
|
|
32
|
+
*/
|
|
33
|
+
export const CLOSED = {
|
|
34
|
+
busy: 4429,
|
|
35
|
+
denied: 4403,
|
|
36
|
+
expired: 4401,
|
|
37
|
+
invalid: 4400,
|
|
38
|
+
too_large: 4413,
|
|
39
|
+
too_many: 4409,
|
|
40
|
+
unavailable: 4503,
|
|
41
|
+
};
|
|
42
|
+
/** A connection that went unheard: closed, and free to come back. */
|
|
43
|
+
export const IDLE = 4408;
|
|
44
|
+
// [function]
|
|
45
|
+
// tokens that refill at `rate` a second, up to `burst`: whether one is
|
|
46
|
+
// there to take, at `at`.
|
|
47
|
+
function bucket(rate, burst) {
|
|
48
|
+
let tokens = burst;
|
|
49
|
+
let last = 0;
|
|
50
|
+
return function take(at) {
|
|
51
|
+
tokens = Math.min(burst, tokens + ((at - last) / 1000) * rate);
|
|
52
|
+
last = at;
|
|
53
|
+
if (tokens < 1)
|
|
54
|
+
return false;
|
|
55
|
+
tokens -= 1;
|
|
56
|
+
return true;
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
// [function]
|
|
60
|
+
// a string's size in bytes, as UTF-8.
|
|
61
|
+
function size(text) {
|
|
62
|
+
let bytes = 0;
|
|
63
|
+
for (let at = 0; at < text.length; at += 1) {
|
|
64
|
+
const code = text.charCodeAt(at);
|
|
65
|
+
if (code < 0x80)
|
|
66
|
+
bytes += 1;
|
|
67
|
+
else if (code < 0x800)
|
|
68
|
+
bytes += 2;
|
|
69
|
+
else if (code >= 0xd800 && code <= 0xdbff) {
|
|
70
|
+
bytes += 4;
|
|
71
|
+
at += 1;
|
|
72
|
+
}
|
|
73
|
+
else
|
|
74
|
+
bytes += 3;
|
|
75
|
+
}
|
|
76
|
+
return bytes;
|
|
77
|
+
}
|
|
78
|
+
// [function]
|
|
79
|
+
/** A member as a frame carries one: only what a member is. */
|
|
80
|
+
export function memberOf(value) {
|
|
81
|
+
if (typeof value !== "object" || value === null)
|
|
82
|
+
return null;
|
|
83
|
+
const { guest, id, name } = value;
|
|
84
|
+
if (typeof id !== "string" || typeof guest !== "boolean")
|
|
85
|
+
return null;
|
|
86
|
+
return { guest, id, name: typeof name === "string" && !guest ? name : null };
|
|
87
|
+
}
|
|
88
|
+
// [function]
|
|
89
|
+
/**
|
|
90
|
+
* A wire. Frames are JSON text, one thing each: to a connection,
|
|
91
|
+
* `{ welcome: { you, members } }` as it comes on, then
|
|
92
|
+
* `{ message: { data, from, at } }`, `{ join: member }`, `{ leave: member }`,
|
|
93
|
+
* and `{ refused: code }` for a send that wasn't taken; from one,
|
|
94
|
+
* `{ send: data }`. A member is a player, however many connections they
|
|
95
|
+
* have: the rest hear `join` at their first and `leave` at their last.
|
|
96
|
+
*/
|
|
97
|
+
export function createRoom(options) {
|
|
98
|
+
const now = options.now ?? (() => Date.now());
|
|
99
|
+
// each member's sends, and the wire's, counted here: a wire that's put to
|
|
100
|
+
// sleep and woken starts them full again, which lets no one send faster
|
|
101
|
+
// for long
|
|
102
|
+
const sends = new Map();
|
|
103
|
+
const wire = bucket(LIMITS.wireRate, LIMITS.wireRate);
|
|
104
|
+
// who's on: each member once, in the order they came
|
|
105
|
+
const members = function () {
|
|
106
|
+
const seen = new Map();
|
|
107
|
+
for (const each of options.list()) {
|
|
108
|
+
if (!seen.has(each.member.id))
|
|
109
|
+
seen.set(each.member.id, each.member);
|
|
110
|
+
}
|
|
111
|
+
return [...seen.values()];
|
|
112
|
+
};
|
|
113
|
+
const all = function (frame, but) {
|
|
114
|
+
const text = JSON.stringify(frame);
|
|
115
|
+
for (const each of options.list()) {
|
|
116
|
+
if (each.key !== but)
|
|
117
|
+
options.deliver(each.key, text);
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
// one message, to everyone on the wire, the sender included, stamped
|
|
121
|
+
// here: the order they're sent in is the wire's order
|
|
122
|
+
const message = function (data, from) {
|
|
123
|
+
all({ message: { at: new Date(now()).toISOString(), data, from } });
|
|
124
|
+
options.passed?.();
|
|
125
|
+
};
|
|
126
|
+
return {
|
|
127
|
+
admit(member) {
|
|
128
|
+
const on = options.list();
|
|
129
|
+
const theirs = on.filter((each) => each.member.id === member.id).length;
|
|
130
|
+
if (theirs >= LIMITS.connections)
|
|
131
|
+
return "too_many";
|
|
132
|
+
if (theirs === 0 && members().length >= LIMITS.members)
|
|
133
|
+
return "too_many";
|
|
134
|
+
return null;
|
|
135
|
+
},
|
|
136
|
+
joined(key) {
|
|
137
|
+
const on = options.list();
|
|
138
|
+
const mine = on.find((each) => each.key === key);
|
|
139
|
+
if (!mine)
|
|
140
|
+
return;
|
|
141
|
+
options.deliver(key, JSON.stringify({ welcome: { members: members(), you: mine.member } }));
|
|
142
|
+
// their first connection: the rest hear they came
|
|
143
|
+
const first = !on.some((each) => each.key !== key && each.member.id === mine.member.id);
|
|
144
|
+
if (first)
|
|
145
|
+
all({ join: mine.member }, key);
|
|
146
|
+
},
|
|
147
|
+
left(member) {
|
|
148
|
+
// their last connection: the rest hear they went
|
|
149
|
+
const still = options.list().some((each) => each.member.id === member.id);
|
|
150
|
+
if (!still) {
|
|
151
|
+
sends.delete(member.id);
|
|
152
|
+
all({ leave: member });
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
said(key, text) {
|
|
156
|
+
const mine = options.list().find((each) => each.key === key);
|
|
157
|
+
if (!mine)
|
|
158
|
+
return;
|
|
159
|
+
const refuse = (code) => options.deliver(key, JSON.stringify({ refused: code }));
|
|
160
|
+
// a frame is `{"send":<data>}`: its data's size, as JSON, is the
|
|
161
|
+
// frame's less what's around it
|
|
162
|
+
if (size(text) - '{"send":}'.length > LIMITS.message) {
|
|
163
|
+
refuse("too_large");
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
let frame;
|
|
167
|
+
try {
|
|
168
|
+
frame = JSON.parse(text);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
frame = null;
|
|
172
|
+
}
|
|
173
|
+
if (typeof frame !== "object" ||
|
|
174
|
+
frame === null ||
|
|
175
|
+
!Object.hasOwn(frame, "send")) {
|
|
176
|
+
refuse("invalid");
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
const at = now();
|
|
180
|
+
let take = sends.get(mine.member.id);
|
|
181
|
+
if (!take) {
|
|
182
|
+
take = bucket(LIMITS.rate, LIMITS.rateBurst);
|
|
183
|
+
sends.set(mine.member.id, take);
|
|
184
|
+
}
|
|
185
|
+
// past a member's rate, or the wire's, a message is dropped, and its
|
|
186
|
+
// sender told
|
|
187
|
+
if (!take(at) || !wire(at)) {
|
|
188
|
+
refuse("busy");
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
message(frame.send, mine.member);
|
|
192
|
+
},
|
|
193
|
+
server(data) {
|
|
194
|
+
if (data === undefined)
|
|
195
|
+
return false;
|
|
196
|
+
// the server's word is never dropped for the wire's rate: what it
|
|
197
|
+
// sends is counted where it's sent from
|
|
198
|
+
message(data, null);
|
|
199
|
+
return true;
|
|
200
|
+
},
|
|
201
|
+
sweep() {
|
|
202
|
+
const at = now();
|
|
203
|
+
let stay = 0;
|
|
204
|
+
// as it stood: dropping one changes who's listed
|
|
205
|
+
for (const each of [...options.list()]) {
|
|
206
|
+
if (at - each.heard > LIMITS.idle)
|
|
207
|
+
options.drop(each.key, IDLE, "idle");
|
|
208
|
+
else
|
|
209
|
+
stay += 1;
|
|
210
|
+
}
|
|
211
|
+
return stay;
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
"qrcode-terminal": "0.12.0",
|
|
29
29
|
"range-parser": "1.3.0",
|
|
30
30
|
"semver": "7.8.6",
|
|
31
|
+
"ws": "8.23.0",
|
|
31
32
|
"yargs": "17.7.3",
|
|
32
33
|
"zod": "4.6.7"
|
|
33
34
|
},
|
|
@@ -43,7 +44,7 @@
|
|
|
43
44
|
},
|
|
44
45
|
"license": "Apache-2.0",
|
|
45
46
|
"name": "arcadible",
|
|
46
|
-
"version": "1.0.
|
|
47
|
+
"version": "1.0.34"
|
|
47
48
|
},
|
|
48
49
|
"node_modules/@asamuzakjp/css-color": {
|
|
49
50
|
"dependencies": {
|
|
@@ -3147,7 +3148,7 @@
|
|
|
3147
3148
|
"engines": {
|
|
3148
3149
|
"node": ">=10.0.0"
|
|
3149
3150
|
},
|
|
3150
|
-
"integrity": "sha512
|
|
3151
|
+
"integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
|
|
3151
3152
|
"license": "MIT",
|
|
3152
3153
|
"peerDependencies": {
|
|
3153
3154
|
"bufferutil": "^4.0.1",
|
|
@@ -3161,8 +3162,8 @@
|
|
|
3161
3162
|
"optional": true
|
|
3162
3163
|
}
|
|
3163
3164
|
},
|
|
3164
|
-
"resolved": "https://registry.npmjs.org/ws/-/ws-8.
|
|
3165
|
-
"version": "8.
|
|
3165
|
+
"resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
|
|
3166
|
+
"version": "8.23.0"
|
|
3166
3167
|
},
|
|
3167
3168
|
"node_modules/wsl-utils": {
|
|
3168
3169
|
"dependencies": {
|
|
@@ -3266,5 +3267,5 @@
|
|
|
3266
3267
|
}
|
|
3267
3268
|
},
|
|
3268
3269
|
"requires": true,
|
|
3269
|
-
"version": "1.0.
|
|
3270
|
+
"version": "1.0.34"
|
|
3270
3271
|
}
|
package/package.json
CHANGED
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
"qrcode-terminal": "0.12.0",
|
|
26
26
|
"range-parser": "1.3.0",
|
|
27
27
|
"semver": "7.8.6",
|
|
28
|
+
"ws": "8.23.0",
|
|
28
29
|
"yargs": "17.7.3",
|
|
29
30
|
"zod": "4.6.7"
|
|
30
31
|
},
|
|
@@ -67,5 +68,5 @@
|
|
|
67
68
|
"test": "tsc && npm run lint && node --test \"test/**/*.test.js\" \"test/**/*.test.mjs\""
|
|
68
69
|
},
|
|
69
70
|
"type": "module",
|
|
70
|
-
"version": "1.0.
|
|
71
|
+
"version": "1.0.34"
|
|
71
72
|
}
|