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.
@@ -0,0 +1,236 @@
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, ticketClose, } 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, Cloudflare's: a larger message
35
+ // than a wire takes is refused as `too_large`, the connection kept, as on
36
+ // Arcadible.
37
+ const FRAME_MAX = 1024 * 1024;
38
+ // [function]
39
+ // arc serve's wires for `game`, on its own `origin`, where a ticket for a
40
+ // wire is for. `tickets` are arc serve's own (./ticket.ts), which say who's
41
+ // connecting. `drop`, in seconds, drops each connection that long after it
42
+ // comes on, so a game's rejoin is tried without a network to break.
43
+ export function wires({ drop = null, game, origin, tickets, }) {
44
+ // an id's mark, over the game, the local channel, and its random part.
45
+ // Arcadible's is made with a secret; here the game's own id stands in,
46
+ // since no one on this machine is kept out: an id is still this game's
47
+ // alone, and one made in an earlier run still opens its wire, as a
48
+ // match kept in the project's values expects.
49
+ const mark = function (random) {
50
+ return crypto
51
+ .createHmac("sha256", `arc serve wires:${String(game)}`)
52
+ .update(`${String(game)}:${CHANNEL}:${random}`)
53
+ .digest()
54
+ .subarray(0, 16)
55
+ .toString("base64url");
56
+ };
57
+ const make = function () {
58
+ const random = crypto.randomBytes(16).toString("base64url");
59
+ return `${random}${mark(random)}`;
60
+ };
61
+ const isOurs = function (id) {
62
+ return (typeof id === "string" &&
63
+ ID.test(id) &&
64
+ mark(id.slice(0, PART)) === id.slice(PART));
65
+ };
66
+ // the wires with anyone on them, by id: one with no one isn't anywhere
67
+ const running = new Map();
68
+ const wire = function (id) {
69
+ let found = running.get(id);
70
+ if (!found) {
71
+ const on = new Map();
72
+ found = {
73
+ on,
74
+ room: createRoom({
75
+ deliver(key, text) {
76
+ on.get(key)?.socket.send(text);
77
+ },
78
+ drop(key, code, reason) {
79
+ on.get(key)?.socket.close(code, reason);
80
+ },
81
+ list: () => [...on.values()],
82
+ }),
83
+ };
84
+ running.set(id, found);
85
+ }
86
+ return found;
87
+ };
88
+ // what hasn't been heard from in too long is dropped, as Arcadible's
89
+ // alarm drops it
90
+ const sweeper = setInterval(() => {
91
+ for (const each of running.values())
92
+ each.room.sweep();
93
+ }, LIMITS.idle);
94
+ sweeper.unref();
95
+ const server = new WebSocketServer({
96
+ // the protocol's name is answered alone: the ticket beside it isn't one
97
+ handleProtocols: (offered) => (offered.has(PROTOCOL) ? PROTOCOL : false),
98
+ maxPayload: FRAME_MAX,
99
+ noServer: true,
100
+ });
101
+ // a game's ticket, checked for the game's origin: who it names, or the
102
+ // code it's refused with
103
+ const memberOf = async function (ticket) {
104
+ const checked = typeof ticket === "string"
105
+ ? await tickets.check(ticket, origin)
106
+ : { data: { code: "invalid" }, status: 422 };
107
+ if (checked.status !== 200)
108
+ return { code: checked.data.code };
109
+ const { guest, player } = checked.data;
110
+ if (typeof player === "string") {
111
+ return {
112
+ member: {
113
+ guest: false,
114
+ id: player,
115
+ name: tickets.player(player)?.name ?? null,
116
+ },
117
+ };
118
+ }
119
+ // a guest whose page named no id is no one, and may not come on
120
+ return typeof guest === "string"
121
+ ? { member: { guest: true, id: guest, name: null } }
122
+ : { code: "denied" };
123
+ };
124
+ let keys = 0;
125
+ return {
126
+ close() {
127
+ clearInterval(sweeper);
128
+ for (const each of running.values()) {
129
+ for (const { socket } of each.on.values())
130
+ socket.terminate();
131
+ }
132
+ running.clear();
133
+ server.close();
134
+ },
135
+ async handle(req, res) {
136
+ if (req.method === "OPTIONS") {
137
+ res.writeHead(204, CORS).end();
138
+ return;
139
+ }
140
+ const refuse = function (status, code) {
141
+ res.writeHead(status, {
142
+ ...CORS,
143
+ "content-type": "application/json",
144
+ [REFUSAL]: code,
145
+ });
146
+ res.end(JSON.stringify({ code }));
147
+ };
148
+ if (req.method !== "POST") {
149
+ refuse(405, "invalid");
150
+ return;
151
+ }
152
+ const [scheme, ticket] = (req.headers.authorization ?? "").split(" ");
153
+ const who = await memberOf(scheme?.toLowerCase() === "bearer" ? ticket : null);
154
+ if ("code" in who) {
155
+ refuse(who.code === "denied" ? 403 : 401, who.code);
156
+ return;
157
+ }
158
+ res.writeHead(200, { ...CORS, "content-type": "application/json" });
159
+ res.end(JSON.stringify({ id: make() }));
160
+ },
161
+ open: make,
162
+ send(id, data) {
163
+ if (!isOurs(id) || data === undefined)
164
+ return 400;
165
+ if (Buffer.byteLength(JSON.stringify(data)) > LIMITS.message)
166
+ return 413;
167
+ // with no one on, it's passed to no one
168
+ running.get(id)?.room.server(data);
169
+ return 200;
170
+ },
171
+ upgrade(req, socket, head) {
172
+ const id = (req.url ?? "").split("?")[0]?.slice(PREFIX.length + 1) ?? "";
173
+ const offered = (req.headers["sec-websocket-protocol"] ?? "")
174
+ .split(",")
175
+ .map((each) => each.trim());
176
+ const ticket = offered.find((each) => each !== PROTOCOL);
177
+ server.handleUpgrade(req, socket, head, (ws) => {
178
+ // a connection that's refused opens, and closes with why: a
179
+ // browser is told nothing of one that never opens
180
+ const refuse = (code) => ws.close(CLOSED[code], code);
181
+ ws.on("error", () => ws.terminate());
182
+ if (!offered.includes(PROTOCOL) || !isOurs(id)) {
183
+ refuse("invalid");
184
+ return;
185
+ }
186
+ void memberOf(ticket).then((who) => {
187
+ if ("code" in who) {
188
+ ws.close(ticketClose(who.code), who.code);
189
+ return;
190
+ }
191
+ const { on, room } = wire(id);
192
+ const refused = room.admit(who.member);
193
+ if (refused) {
194
+ if (on.size === 0)
195
+ running.delete(id);
196
+ refuse(refused);
197
+ return;
198
+ }
199
+ keys += 1;
200
+ const key = String(keys);
201
+ const mine = {
202
+ heard: Date.now(),
203
+ key,
204
+ member: who.member,
205
+ socket: ws,
206
+ };
207
+ on.set(key, mine);
208
+ ws.on("message", (data, isBinary) => {
209
+ mine.heard = Date.now();
210
+ // a wire carries text: JSON, a frame each
211
+ if (isBinary) {
212
+ room.said(key, "");
213
+ return;
214
+ }
215
+ const text = data.toString();
216
+ if (text === PING)
217
+ ws.send(PONG);
218
+ else
219
+ room.said(key, text);
220
+ });
221
+ ws.on("close", () => {
222
+ on.delete(key);
223
+ room.left(who.member);
224
+ if (on.size === 0)
225
+ running.delete(id);
226
+ });
227
+ room.joined(key);
228
+ if (drop !== null) {
229
+ setTimeout(() => ws.terminate(), drop * 1000).unref();
230
+ }
231
+ // a ticket that couldn't be checked at all: no one comes on
232
+ }, () => refuse("unavailable"));
233
+ });
234
+ },
235
+ };
236
+ }
@@ -1,5 +1,5 @@
1
1
  // [import]
2
- import { ALL, API_REFUSED, INTERNAL } from "../config/code.js";
2
+ import { ALL, API_REFUSED, INTERNAL, UNEXPECTED } from "../config/code.js";
3
3
  import { HttpError } from "./http.js";
4
4
  // [class]
5
5
  // a failure with its code (config/code.js), which scripts match on while the
@@ -21,15 +21,18 @@ export class ArcError extends Error {
21
21
  }
22
22
  }
23
23
  // [function]
24
- // the code a failure reports: its own, api_refused for a request the API
25
- // refused, or internal for a failure on Arcadible's side (a 5xx) and for
26
- // anything else, which is a bug in the CLI.
24
+ // the code a failure reports: its own; the API's, when it names one of the
25
+ // CLI's (ERRORS.md); api_refused for any other request the API refused;
26
+ // internal for a failure on Arcadible's side (a 5xx), worth trying again;
27
+ // and unexpected for anything else, a bug in the CLI, which isn't.
27
28
  export function codeOf(ex) {
28
29
  if (ex instanceof ArcError) {
29
30
  return ex.code;
30
31
  }
31
- if (ex instanceof HttpError && !(ex.status >= 500)) {
32
- return API_REFUSED;
32
+ if (ex instanceof HttpError) {
33
+ if (ex.status >= 500)
34
+ return INTERNAL;
35
+ return ex.code !== undefined && ALL.has(ex.code) ? ex.code : API_REFUSED;
33
36
  }
34
- return INTERNAL;
37
+ return UNEXPECTED;
35
38
  }
package/dist/util/http.js CHANGED
@@ -2,10 +2,15 @@
2
2
  import { httpError } from "../phrase/index.js";
3
3
  // [class]
4
4
  export class HttpError extends Error {
5
+ // the API's code for the refusal, which a client reads before its status:
6
+ // the database's own (`game_unavailable`), or the status's word
7
+ // (`denied`); undefined when the answer has none.
8
+ code;
5
9
  status;
6
10
  // [constructor]
7
- constructor(status, { message, title } = {}) {
11
+ constructor(status, { code, message, title } = {}) {
8
12
  super(message);
13
+ this.code = code;
9
14
  this.status = status;
10
15
  this.name = title || "HTTP Error";
11
16
  this.message = httpError(this.name, this.status, message);
@@ -28,15 +28,17 @@ function dataOf(body) {
28
28
  return (isTable(body) ? body["data"] : null) ?? null;
29
29
  }
30
30
  // [function]
31
- // an error's title and message, from the response's status text and the
32
- // API's own `{ title, message }`, which takes precedence when it's there.
31
+ // an error's code, title, and message, from the response's status text and
32
+ // the API's own `{ code, title, message }`, which takes precedence when it's
33
+ // there. A code is a string; an API from before its codes said the status.
33
34
  function errorOf(statusText, data) {
34
35
  const all = {
35
36
  title: statusText,
36
37
  ...(isTable(data) ? data : {}),
37
38
  };
38
- const { message, title } = all;
39
+ const { code, message, title } = all;
39
40
  return {
41
+ code: typeof code === "string" ? code : undefined,
40
42
  message: typeof message === "string" ? message : undefined,
41
43
  title: typeof title === "string" ? title : undefined,
42
44
  };
@@ -0,0 +1,224 @@
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
+ /**
46
+ * The close for a ticket a wire didn't take, by why: `4401` for one that ran
47
+ * out or was refused, as HTTP's `401` is for both, so the game asks for a
48
+ * new one and tries once more; a guest with no id `4403`; one that couldn't
49
+ * be checked `4503`. The close's reason says which.
50
+ */
51
+ export function ticketClose(code) {
52
+ return code === "invalid" ? CLOSED.expired : CLOSED[code];
53
+ }
54
+ // [function]
55
+ // tokens that refill at `rate` a second, up to `burst`: whether one is
56
+ // there to take, at `at`.
57
+ function bucket(rate, burst) {
58
+ let tokens = burst;
59
+ let last = 0;
60
+ return function take(at) {
61
+ tokens = Math.min(burst, tokens + ((at - last) / 1000) * rate);
62
+ last = at;
63
+ if (tokens < 1)
64
+ return false;
65
+ tokens -= 1;
66
+ return true;
67
+ };
68
+ }
69
+ // [function]
70
+ // a string's size in bytes, as UTF-8.
71
+ function size(text) {
72
+ let bytes = 0;
73
+ for (let at = 0; at < text.length; at += 1) {
74
+ const code = text.charCodeAt(at);
75
+ if (code < 0x80)
76
+ bytes += 1;
77
+ else if (code < 0x800)
78
+ bytes += 2;
79
+ else if (code >= 0xd800 && code <= 0xdbff) {
80
+ bytes += 4;
81
+ at += 1;
82
+ }
83
+ else
84
+ bytes += 3;
85
+ }
86
+ return bytes;
87
+ }
88
+ // [function]
89
+ /** A member as a frame carries one: only what a member is. */
90
+ export function memberOf(value) {
91
+ if (typeof value !== "object" || value === null)
92
+ return null;
93
+ const { guest, id, name } = value;
94
+ if (typeof id !== "string" || typeof guest !== "boolean")
95
+ return null;
96
+ return { guest, id, name: typeof name === "string" && !guest ? name : null };
97
+ }
98
+ // [function]
99
+ /**
100
+ * A wire. Frames are JSON text, one thing each: to a connection,
101
+ * `{ welcome: { you, members } }` as it comes on, then
102
+ * `{ message: { data, from, at } }`, `{ join: member }`, `{ leave: member }`,
103
+ * and `{ refused: code }` for a send that wasn't taken; from one,
104
+ * `{ send: data }`. A member is a player, however many connections they
105
+ * have: the rest hear `join` at their first and `leave` at their last.
106
+ */
107
+ export function createRoom(options) {
108
+ const now = options.now ?? (() => Date.now());
109
+ // each member's sends, and the wire's, counted here: a wire that's put to
110
+ // sleep and woken starts them full again, which lets no one send faster
111
+ // for long
112
+ const sends = new Map();
113
+ const wire = bucket(LIMITS.wireRate, LIMITS.wireRate);
114
+ // who's on: each member once, in the order they came
115
+ const members = function () {
116
+ const seen = new Map();
117
+ for (const each of options.list()) {
118
+ if (!seen.has(each.member.id))
119
+ seen.set(each.member.id, each.member);
120
+ }
121
+ return [...seen.values()];
122
+ };
123
+ const all = function (frame, but) {
124
+ const text = JSON.stringify(frame);
125
+ for (const each of options.list()) {
126
+ if (each.key !== but)
127
+ options.deliver(each.key, text);
128
+ }
129
+ };
130
+ // one message, to everyone on the wire, the sender included, stamped
131
+ // here: the order they're sent in is the wire's order
132
+ const message = function (data, from) {
133
+ all({ message: { at: new Date(now()).toISOString(), data, from } });
134
+ options.passed?.();
135
+ };
136
+ return {
137
+ admit(member) {
138
+ const on = options.list();
139
+ const theirs = on.filter((each) => each.member.id === member.id).length;
140
+ if (theirs >= LIMITS.connections)
141
+ return "too_many";
142
+ if (theirs === 0 && members().length >= LIMITS.members)
143
+ return "too_many";
144
+ return null;
145
+ },
146
+ joined(key) {
147
+ const on = options.list();
148
+ const mine = on.find((each) => each.key === key);
149
+ if (!mine)
150
+ return;
151
+ options.deliver(key, JSON.stringify({ welcome: { members: members(), you: mine.member } }));
152
+ // their first connection: the rest hear they came
153
+ const first = !on.some((each) => each.key !== key && each.member.id === mine.member.id);
154
+ if (first)
155
+ all({ join: mine.member }, key);
156
+ },
157
+ left(member) {
158
+ // their last connection: the rest hear they went
159
+ const still = options.list().some((each) => each.member.id === member.id);
160
+ if (!still) {
161
+ sends.delete(member.id);
162
+ all({ leave: member });
163
+ }
164
+ },
165
+ said(key, text) {
166
+ const mine = options.list().find((each) => each.key === key);
167
+ if (!mine)
168
+ return;
169
+ const refuse = (code) => options.deliver(key, JSON.stringify({ refused: code }));
170
+ // a frame is `{"send":<data>}`: its data's size, as JSON, is the
171
+ // frame's less what's around it
172
+ if (size(text) - '{"send":}'.length > LIMITS.message) {
173
+ refuse("too_large");
174
+ return;
175
+ }
176
+ let frame;
177
+ try {
178
+ frame = JSON.parse(text);
179
+ }
180
+ catch {
181
+ frame = null;
182
+ }
183
+ if (typeof frame !== "object" ||
184
+ frame === null ||
185
+ !Object.hasOwn(frame, "send")) {
186
+ refuse("invalid");
187
+ return;
188
+ }
189
+ const at = now();
190
+ let take = sends.get(mine.member.id);
191
+ if (!take) {
192
+ take = bucket(LIMITS.rate, LIMITS.rateBurst);
193
+ sends.set(mine.member.id, take);
194
+ }
195
+ // past a member's rate, or the wire's, a message is dropped, and its
196
+ // sender told
197
+ if (!take(at) || !wire(at)) {
198
+ refuse("busy");
199
+ return;
200
+ }
201
+ message(frame.send, mine.member);
202
+ },
203
+ server(data) {
204
+ if (data === undefined)
205
+ return false;
206
+ // the server's word is never dropped for the wire's rate: what it
207
+ // sends is counted where it's sent from
208
+ message(data, null);
209
+ return true;
210
+ },
211
+ sweep() {
212
+ const at = now();
213
+ let stay = 0;
214
+ // as it stood: dropping one changes who's listed
215
+ for (const each of [...options.list()]) {
216
+ if (at - each.heard > LIMITS.idle)
217
+ options.drop(each.key, IDLE, "idle");
218
+ else
219
+ stay += 1;
220
+ }
221
+ return stay;
222
+ },
223
+ };
224
+ }
@@ -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.33"
47
+ "version": "1.0.35"
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-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==",
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.22.2.tgz",
3165
- "version": "8.22.2"
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.33"
3270
+ "version": "1.0.35"
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.33"
71
+ "version": "1.0.35"
71
72
  }