arcadible 1.0.32 → 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 +172 -16
- package/dist/serve/runner.js +53 -1
- package/dist/serve/server.js +35 -2
- package/dist/serve/ticket.js +33 -5
- package/dist/serve/values.js +17 -12
- 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
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
|
|
@@ -36,6 +39,10 @@ export const DROPPED = [
|
|
|
36
39
|
// the code a game is given when its function failed, as on Arcadible: it
|
|
37
40
|
// threw, or it isn't running.
|
|
38
41
|
export const FAILED = "function_failed";
|
|
42
|
+
// the largest body a request may bring a function, in bytes, as on
|
|
43
|
+
// Arcadible, where the dispatcher refuses one past it with TOO_LARGE.
|
|
44
|
+
export const BODY_MAX = 1024 * 1024;
|
|
45
|
+
export const TOO_LARGE = "too_large";
|
|
39
46
|
// what marks an answer as Arcadible's own, with its code, as the dispatcher
|
|
40
47
|
// marks its refusals: dropped from what a function's code answers, so a
|
|
41
48
|
// game can't be told a refusal that isn't one.
|
|
@@ -209,6 +216,30 @@ const outbound :Workerd.Worker = (
|
|
|
209
216
|
`;
|
|
210
217
|
}
|
|
211
218
|
// [function]
|
|
219
|
+
// a request's body, held to BODY_MAX: `true` when it fits as it came, with
|
|
220
|
+
// a length it says (Node holds the bytes to it), its bytes when it fits and
|
|
221
|
+
// came without one (streamed), or `null` when it's larger.
|
|
222
|
+
async function bodyOf(req) {
|
|
223
|
+
const said = req.headers["content-length"];
|
|
224
|
+
if (said !== undefined && /^\d+$/u.test(said.trim())) {
|
|
225
|
+
return Number(said) <= BODY_MAX ? true : null;
|
|
226
|
+
}
|
|
227
|
+
if (req.headers["transfer-encoding"] === undefined)
|
|
228
|
+
return true;
|
|
229
|
+
const parts = [];
|
|
230
|
+
let size = 0;
|
|
231
|
+
for await (const chunk of req) {
|
|
232
|
+
const part = chunk;
|
|
233
|
+
size += part.length;
|
|
234
|
+
if (size > BODY_MAX) {
|
|
235
|
+
req.resume();
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
parts.push(part);
|
|
239
|
+
}
|
|
240
|
+
return Buffer.concat(parts);
|
|
241
|
+
}
|
|
242
|
+
// [function]
|
|
212
243
|
// a game's runner, running. `main` is its code's path, `dir` where the
|
|
213
244
|
// runtime is kept, `origin` the game's own origin (a ticket for the runner
|
|
214
245
|
// is for it), `serve` arc serve's page (where Arcadible is, here), `hosts`
|
|
@@ -279,6 +310,18 @@ export async function runner({ dir, handler, hosts = [], main, origin, secrets =
|
|
|
279
310
|
res.end(JSON.stringify({ code: checked.data.code }));
|
|
280
311
|
return;
|
|
281
312
|
}
|
|
313
|
+
// a body past what a function may be sent, said or streamed, as the
|
|
314
|
+
// dispatcher refuses it: a streamed one is read here, to hold it
|
|
315
|
+
const body = await bodyOf(req);
|
|
316
|
+
if (body === null) {
|
|
317
|
+
res.writeHead(413, {
|
|
318
|
+
...CORS,
|
|
319
|
+
"content-type": "application/json",
|
|
320
|
+
[REFUSAL]: TOO_LARGE,
|
|
321
|
+
});
|
|
322
|
+
res.end(JSON.stringify({ code: TOO_LARGE }));
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
282
325
|
// the game's answer when its function failed, as the dispatcher's: why
|
|
283
326
|
// is the terminal's, said as it happened
|
|
284
327
|
const fail = function () {
|
|
@@ -296,11 +339,17 @@ export async function runner({ dir, handler, hosts = [], main, origin, secrets =
|
|
|
296
339
|
return;
|
|
297
340
|
}
|
|
298
341
|
const player = checked.data.player;
|
|
342
|
+
const guest = checked.data.guest;
|
|
299
343
|
const dropped = [...DROPPED, "host"];
|
|
300
344
|
const headers = {
|
|
301
345
|
...Object.fromEntries(Object.entries(req.headers).filter(([name]) => !dropped.includes(name))),
|
|
302
346
|
[PLAYER]: typeof player === "string" ? player : "",
|
|
347
|
+
[GUEST]: typeof guest === "string" ? guest : "",
|
|
303
348
|
};
|
|
349
|
+
if (body !== true) {
|
|
350
|
+
delete headers["transfer-encoding"];
|
|
351
|
+
headers["content-length"] = String(body.length);
|
|
352
|
+
}
|
|
304
353
|
// `request` is called through the module, as the tests fake Node's own.
|
|
305
354
|
const forward = http.request({
|
|
306
355
|
headers,
|
|
@@ -313,7 +362,10 @@ export async function runner({ dir, handler, hosts = [], main, origin, secrets =
|
|
|
313
362
|
answer.pipe(res);
|
|
314
363
|
});
|
|
315
364
|
forward.on("error", fail);
|
|
316
|
-
|
|
365
|
+
if (body === true)
|
|
366
|
+
req.pipe(forward);
|
|
367
|
+
else
|
|
368
|
+
forward.end(body);
|
|
317
369
|
};
|
|
318
370
|
await start();
|
|
319
371
|
return {
|
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
|
@@ -18,12 +18,17 @@ const generateKeyPair = promisify(crypto.generateKeyPair);
|
|
|
18
18
|
export const CHANNEL = "local";
|
|
19
19
|
// how long a ticket is good for, as Arcadible's.
|
|
20
20
|
export const LIFETIME = 600;
|
|
21
|
+
// how far a clock may be from the signer's, in seconds, either way, as the
|
|
22
|
+
// Server SDK's and the API's checks allow.
|
|
23
|
+
export const LEEWAY = 30;
|
|
21
24
|
// the ticket's own type, as Arcadible's.
|
|
22
25
|
export const TYPE = "arcadible-ticket+jwt";
|
|
23
26
|
// the hosts that are this machine: a server on one needs no declaring.
|
|
24
27
|
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
25
28
|
// the longest name a player is given.
|
|
26
29
|
const NAME_MAX = 200;
|
|
30
|
+
// A player's id in a game, a ticket's `sub`: a UUID, in lowercase.
|
|
31
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
|
|
27
32
|
// [function]
|
|
28
33
|
function b64(data) {
|
|
29
34
|
return Buffer.from(data).toString("base64url");
|
|
@@ -160,17 +165,34 @@ export function tickets({ file, game, issuer, now = () => Date.now(), servers =
|
|
|
160
165
|
claims["game"] !== game) {
|
|
161
166
|
return refused("invalid");
|
|
162
167
|
}
|
|
168
|
+
// a player is named by their id in the game, a UUID, as the API and
|
|
169
|
+
// the Server SDK ask; no `sub` is a guest
|
|
170
|
+
const sub = claims["sub"];
|
|
171
|
+
if (sub !== undefined && (typeof sub !== "string" || !UUID.test(sub))) {
|
|
172
|
+
return refused("invalid");
|
|
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
|
+
}
|
|
163
181
|
const exp = claims["exp"];
|
|
164
|
-
|
|
182
|
+
// good until its time and the leeway a clock is allowed, as the
|
|
183
|
+
// Server SDK's `tickets.check` and the API's check give it
|
|
184
|
+
if (typeof exp === "number" && exp <= now() / 1000 - LEEWAY) {
|
|
165
185
|
return refused("expired");
|
|
166
186
|
}
|
|
167
187
|
return {
|
|
168
188
|
data: {
|
|
169
189
|
channel: claims["channel"],
|
|
170
|
-
|
|
190
|
+
// an ISO time, as the API answers one, never the ticket's seconds
|
|
191
|
+
expires_at: typeof exp === "number" ? new Date(exp * 1000).toISOString() : null,
|
|
171
192
|
game: claims["game"],
|
|
193
|
+
guest: sub === undefined ? (guest ?? null) : null,
|
|
172
194
|
id: claims["jti"],
|
|
173
|
-
player:
|
|
195
|
+
player: sub ?? null,
|
|
174
196
|
site: claims["site"],
|
|
175
197
|
version: claims["version"],
|
|
176
198
|
},
|
|
@@ -185,7 +207,9 @@ export function tickets({ file, game, issuer, now = () => Date.now(), servers =
|
|
|
185
207
|
],
|
|
186
208
|
};
|
|
187
209
|
},
|
|
188
|
-
|
|
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) {
|
|
189
213
|
const origin = originOf(server);
|
|
190
214
|
if (!origin) {
|
|
191
215
|
return { status: 400, ticket: null };
|
|
@@ -208,7 +232,11 @@ export function tickets({ file, game, issuer, now = () => Date.now(), servers =
|
|
|
208
232
|
jti: crypto.randomUUID(),
|
|
209
233
|
site: uuidOf(`site:${String(game)}`),
|
|
210
234
|
version: version ?? "0.0.0",
|
|
211
|
-
...(player
|
|
235
|
+
...(player
|
|
236
|
+
? { sub: player.id }
|
|
237
|
+
: typeof guest === "string" && UUID.test(guest)
|
|
238
|
+
? { guest }
|
|
239
|
+
: {}),
|
|
212
240
|
};
|
|
213
241
|
const signing = [
|
|
214
242
|
b64(JSON.stringify({ alg: "EdDSA", kid, typ: TYPE })),
|
package/dist/serve/values.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// same ones. It answers as Arcadible's database functions do
|
|
5
5
|
// (app/src/web/arcadible-api/db/function/game_value.sql): the same keys,
|
|
6
6
|
// the same limits, a write of several all or none, a named revision
|
|
7
|
-
// replaced or a conflict, with the API's statuses. The developer's values
|
|
7
|
+
// replaced or a conflict, which names the items, with the API's statuses. The developer's values
|
|
8
8
|
// are the project's own files, read as they change, and never written here;
|
|
9
9
|
// the rest are kept in arc's folder in the project, so a match survives a
|
|
10
10
|
// restart.
|
|
@@ -192,6 +192,12 @@ export function values({ isPlayer, now = () => Date.now(), root, }) {
|
|
|
192
192
|
const rowOf = function (item) {
|
|
193
193
|
return held(item.scope, item.owner).get(item.key);
|
|
194
194
|
};
|
|
195
|
+
// the items whose named revision isn't their value's now, or 0 for a key
|
|
196
|
+
// with none, as the database's value_conflicts
|
|
197
|
+
const conflictsOf = function (items) {
|
|
198
|
+
return items.filter((item) => item.revision !== undefined &&
|
|
199
|
+
item.revision !== (rowOf(item)?.revision ?? 0));
|
|
200
|
+
};
|
|
195
201
|
const readItems = function (given) {
|
|
196
202
|
const items = itemsOf(given, ["since"], false);
|
|
197
203
|
if (!items) {
|
|
@@ -241,11 +247,9 @@ export function values({ isPlayer, now = () => Date.now(), root, }) {
|
|
|
241
247
|
return { data: null, status: 413 };
|
|
242
248
|
}
|
|
243
249
|
// every named revision first, so a call writes all or none
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
return { data: null, status: 409 };
|
|
248
|
-
}
|
|
250
|
+
const conflicts = conflictsOf(items);
|
|
251
|
+
if (conflicts.length > 0) {
|
|
252
|
+
return { conflicts, data: null, status: 409 };
|
|
249
253
|
}
|
|
250
254
|
const next = { ...kept.rows };
|
|
251
255
|
let revision = kept.revision;
|
|
@@ -284,7 +288,7 @@ export function values({ isPlayer, now = () => Date.now(), root, }) {
|
|
|
284
288
|
save();
|
|
285
289
|
return { data: written, status: 200 };
|
|
286
290
|
};
|
|
287
|
-
const removeItems = function (given) {
|
|
291
|
+
const removeItems = function (given, skips = false) {
|
|
288
292
|
const items = itemsOf(given, ["revision"], false);
|
|
289
293
|
if (!items) {
|
|
290
294
|
return { data: null, status: 400 };
|
|
@@ -293,14 +297,15 @@ export function values({ isPlayer, now = () => Date.now(), root, }) {
|
|
|
293
297
|
if (refused) {
|
|
294
298
|
return { data: null, status: refused };
|
|
295
299
|
}
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
return { data: null, status: 409 };
|
|
300
|
-
}
|
|
300
|
+
const conflicts = conflictsOf(items);
|
|
301
|
+
if (conflicts.length > 0 && !skips) {
|
|
302
|
+
return { conflicts, data: null, status: 409 };
|
|
301
303
|
}
|
|
302
304
|
let removed = 0;
|
|
303
305
|
for (const item of items) {
|
|
306
|
+
if (conflicts.includes(item)) {
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
304
309
|
const rows = kept.rows[`${item.scope}:${item.owner}`] ?? {};
|
|
305
310
|
if (Object.hasOwn(rows, item.key)) {
|
|
306
311
|
Reflect.deleteProperty(rows, item.key);
|
|
@@ -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
|
+
}
|