arcadible 1.0.34 → 1.0.36

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.
@@ -25,14 +25,58 @@ export const FUNCTION_MODULE = "function.js";
25
25
  // address in a `process.env` of the entry's making. A function's secrets
26
26
  // arrive as a header too (x-arcadible-secrets, opened by the dispatcher),
27
27
  // and are added to what the code is given, `env`. Neither header reaches
28
- // the developer's code.
28
+ // the developer's code. Under arc serve they're the script's own bindings,
29
+ // named by ARCADIBLE_SECRETS. Whatever the code logs has the secrets' values
30
+ // it was given hidden, `[secret NAME]`, and an error it throws that holds
31
+ // one is logged hidden and thrown as one that doesn't, so a function's logs
32
+ // never keep a secret (plan/FUNCTION-LOGS.md, What's redacted).
29
33
  export const ENTRY = `import handler from "./${FUNCTION_MODULE}";
30
34
  const CLAIM = "x-arcadible-claim";
31
35
  const SECRETS = "x-arcadible-secrets";
32
36
  const API = "https://api.arcadible.com/v1/server";
37
+ // a secret shorter than this isn't hidden in what's logged: it would be
38
+ // found in ordinary words
39
+ const SHORTEST = 8;
33
40
  // the newest claim, and arc serve's address under it
34
41
  let claimed = null;
35
42
  let serve = null;
43
+ // the secrets' values the code has been given, each with its name, longest
44
+ // first, so one inside another is hidden as the longer
45
+ const hidden = [];
46
+ const remember = (values) => {
47
+ let added = false;
48
+ for (const [name, value] of Object.entries(values)) {
49
+ if (typeof value !== "string" || value.length < SHORTEST) continue;
50
+ if (hidden.some(([known]) => known === value)) continue;
51
+ hidden.push([value, name]);
52
+ added = true;
53
+ }
54
+ if (added) hidden.sort((a, b) => b[0].length - a[0].length);
55
+ };
56
+ const hide = (text) => {
57
+ for (const [value, name] of hidden) text = text.split(value).join("[secret " + name + "]");
58
+ return text;
59
+ };
60
+ // one of console's arguments with any secret in it hidden: a string as it
61
+ // is, an error as its stack, anything else as JSON, and as the console
62
+ // would show it when no secret's in it
63
+ const shown = (value) => {
64
+ if (typeof value === "string") return hide(value);
65
+ let text;
66
+ try {
67
+ text = value instanceof Error ? String(value.stack ?? value) : JSON.stringify(value);
68
+ } catch {
69
+ return value;
70
+ }
71
+ if (typeof text !== "string") return value;
72
+ const safe = hide(text);
73
+ return safe === text ? value : safe;
74
+ };
75
+ for (const level of ["debug", "error", "info", "log", "trace", "warn"]) {
76
+ const original = console[level];
77
+ if (typeof original !== "function") continue;
78
+ console[level] = (...args) => original.apply(console, hidden.length > 0 ? args.map(shown) : args);
79
+ }
36
80
  globalThis[Symbol.for("arcadible.function.api")] = {
37
81
  version: 1,
38
82
  async fetch(path, init = {}) {
@@ -68,7 +112,12 @@ export default {
68
112
  if (secrets) {
69
113
  const text = atob(secrets.replace(/-/g, "+").replace(/_/g, "/"));
70
114
  const bytes = Uint8Array.from(text, (char) => char.charCodeAt(0));
71
- given = { ...env, ...JSON.parse(new TextDecoder().decode(bytes)) };
115
+ const opened = JSON.parse(new TextDecoder().decode(bytes));
116
+ remember(opened);
117
+ given = { ...env, ...opened };
118
+ }
119
+ if (typeof env.ARCADIBLE_SECRETS === "string") {
120
+ remember(Object.fromEntries(env.ARCADIBLE_SECRETS.split(",").map((name) => [name, env[name]])));
72
121
  }
73
122
  if (claim || secrets) {
74
123
  const headers = new Headers(request.headers);
@@ -79,7 +128,14 @@ export default {
79
128
  if (typeof handler?.fetch !== "function") {
80
129
  return new Response("The function's default export has no fetch(request).\\n", { status: 500 });
81
130
  }
82
- return handler.fetch(request, given, ctx);
131
+ try {
132
+ return await handler.fetch(request, given, ctx);
133
+ } catch (err) {
134
+ const text = String(err?.stack ?? err);
135
+ if (hidden.length === 0 || hide(text) === text) throw err;
136
+ console.error(err);
137
+ throw new Error("The function threw an error holding a secret: it's logged with the secret hidden.");
138
+ }
83
139
  },
84
140
  };
85
141
  `;
@@ -78,6 +78,17 @@ const VALUES_BODY_MAX = 512 * 1024;
78
78
  const VALUE_WRITES = ["game", "player", "server"];
79
79
  // what the API says of a request it refuses (app/lib/python/offst/error.py),
80
80
  // in an error's `data`, with its status as `code`.
81
+ // each refusal's code, the status's word, as the API's own (its
82
+ // app/result.py's CODES; ERRORS.md).
83
+ const REFUSAL_CODES = {
84
+ 400: "invalid",
85
+ 403: "denied",
86
+ 404: "not_found",
87
+ 405: "method_not_allowed",
88
+ 409: "conflict",
89
+ 413: "too_large",
90
+ 507: "full",
91
+ };
81
92
  const REFUSALS = {
82
93
  400: [
83
94
  "Bad Request",
@@ -262,7 +273,11 @@ export function html(game, pictures = { art: false, icon: false }, opened, link)
262
273
  `;
263
274
  }
264
275
  // [function]
265
- // a request's body as JSON, or null: larger than `max`, or not JSON.
276
+ // what `readJson` resolves with for a body larger than it takes, which a
277
+ // values call answers `413`, as the API does.
278
+ const OVERSIZE = Symbol("oversize");
279
+ // [function]
280
+ // a request's body as JSON; OVERSIZE, larger than `max`; or null, not JSON.
266
281
  function readJson(req, max = BODY_MAX) {
267
282
  return new Promise((resolve) => {
268
283
  const chunks = [];
@@ -276,7 +291,7 @@ function readJson(req, max = BODY_MAX) {
276
291
  req.on("error", () => resolve(null));
277
292
  req.on("end", () => {
278
293
  try {
279
- resolve(size > max ? null : JSON.parse(Buffer.concat(chunks).toString()));
294
+ resolve(size > max ? OVERSIZE : JSON.parse(Buffer.concat(chunks).toString()));
280
295
  }
281
296
  catch {
282
297
  resolve(null);
@@ -292,7 +307,7 @@ function readJson(req, max = BODY_MAX) {
292
307
  // ticket. 400 a body that isn't an object; 403 no one to make it; 413 data
293
308
  // past 1 KB as JSON. None of Arcadible's rate is kept, nor its 30 days: a
294
309
  // link lasts until arc serve stops.
295
- async function sendLink(req, res, { links, playing }) {
310
+ async function sendLink(req, res, { links, onLink, origin, playing, }) {
296
311
  const type = ((req.headers["content-type"] ?? "").split(";")[0] ?? "").trim();
297
312
  const asked = type.toLowerCase() === "application/json" ? await readJson(req) : null;
298
313
  if (!isTable(asked)) {
@@ -319,6 +334,7 @@ async function sendLink(req, res, { links, playing }) {
319
334
  id += LINK_ALPHABET.charAt(crypto.randomInt(LINK_ALPHABET.length));
320
335
  }
321
336
  links.set(id, { by, data, id });
337
+ onLink(`${origin}/?l=${id}`);
322
338
  res.writeHead(200, {
323
339
  ...HEADERS,
324
340
  "content-type": "application/json; charset=utf-8",
@@ -534,7 +550,7 @@ async function sendGameValues(req, res, verb, { player, values }) {
534
550
  ? await readJson(req, VALUES_BODY_MAX)
535
551
  : null;
536
552
  if (!isTable(body)) {
537
- refuse(400);
553
+ refuse(body === OVERSIZE ? 413 : 400);
538
554
  return;
539
555
  }
540
556
  const write = verb === "write" || verb === "remove";
@@ -667,8 +683,9 @@ function windowOf(pathname, named) {
667
683
  function sendRefusal(req, res, status, conflicts) {
668
684
  const [title, message] = REFUSALS[status] ?? ["", ""];
669
685
  sendData(req, res, status, {
670
- code: status,
686
+ code: REFUSAL_CODES[status] ?? "invalid",
671
687
  message,
688
+ status,
672
689
  title,
673
690
  type: "HttpError",
674
691
  ...(conflicts ? { conflicts } : {}),
@@ -684,7 +701,7 @@ function sendRefusal(req, res, status, conflicts) {
684
701
  async function sendValues(req, res, verb, values) {
685
702
  const body = await readJson(req, VALUES_BODY_MAX);
686
703
  if (!values || !isTable(body)) {
687
- sendRefusal(req, res, values ? 400 : 404);
704
+ sendRefusal(req, res, !values ? 404 : body === OVERSIZE ? 413 : 400);
688
705
  return;
689
706
  }
690
707
  // whether the call names one scope for all its keys; a list's does
@@ -835,7 +852,7 @@ async function sendServer(req, res, route, { game, tickets, values, wires, }) {
835
852
  // `tickets` mints the game's, and publishes their key, and `playerOf(name)`
836
853
  // is a local player by name (./ticket.js). `faviconFile` is the play page's
837
854
  // favicon.ico, the package's own unless a test names another.
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, }) {
855
+ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = FAVICON, game, hostFile = null, icon = () => Promise.resolve(null), onLink = () => undefined, onRemote = () => null, origin = "http://localhost", playerOf = () => null, reloads, remote, tickets = null, values = null, wires = null, }) {
839
856
  // the play page's favicon.ico, read once, or null when it can't be read,
840
857
  // which is tried again on the next request.
841
858
  let favicon = null;
@@ -900,7 +917,7 @@ export function pageHandler({ art = () => Promise.resolve(null), faviconFile = F
900
917
  res.writeHead(405, { ...HEADERS, allow: "POST" }).end();
901
918
  return Promise.resolve();
902
919
  }
903
- return sendLink(req, res, { links, playing });
920
+ return sendLink(req, res, { links, onLink, origin, playing });
904
921
  }
905
922
  if (opened) {
906
923
  // only the page's own API is under a window's path
@@ -93,6 +93,28 @@ const CORS = {
93
93
  "access-control-max-age": "600",
94
94
  };
95
95
  // [function]
96
+ // Arcadible's own answer, marked as the dispatcher marks it: a status, and
97
+ // a code the SDK's `functions.fetch` rejects with.
98
+ function refuse(res, status, code) {
99
+ res.writeHead(status, {
100
+ ...CORS,
101
+ "content-type": "application/json",
102
+ [REFUSAL]: code,
103
+ });
104
+ res.end(JSON.stringify({ code }));
105
+ }
106
+ // [function]
107
+ /**
108
+ * The answer under PREFIX for a project with no function, as the
109
+ * dispatcher's for a build with none: `404`, `no_function`.
110
+ */
111
+ export const noFunction = function (req, res) {
112
+ if (req.method === "OPTIONS")
113
+ res.writeHead(204, CORS).end();
114
+ else
115
+ refuse(res, 404, "no_function");
116
+ return Promise.resolve();
117
+ };
96
118
  // a port nothing listens on, on this machine.
97
119
  function freePort() {
98
120
  return new Promise((resolve, reject) => {
@@ -174,12 +196,19 @@ async function runtime(dir, onInstall) {
174
196
  // the manifest's, and to arc serve; only that worker reaches the network,
175
197
  // this machine included, which arc serve is on, and HTTPS hosts, checked
176
198
  // against the certificate authorities browsers trust. `secrets` are the
177
- // values the code is given, each by its name.
199
+ // values the code is given, each by its name, and named to the entry in
200
+ // ARCADIBLE_SECRETS.
178
201
  function config({ hosts, port, secrets, serve, }) {
179
202
  // each secret that has a value here, as the code's own binding
180
203
  const given = Object.entries(secrets)
181
204
  .map(([name, value]) => `, (name = ${JSON.stringify(name)}, text = ${JSON.stringify(value)})`)
182
205
  .join("");
206
+ // which bindings are secrets, so the entry hides their values in what the
207
+ // code logs, as it does on Arcadible
208
+ const names = Object.keys(secrets);
209
+ const named = names.length > 0
210
+ ? `, (name = "ARCADIBLE_SECRETS", text = ${JSON.stringify(names.join(","))})`
211
+ : "";
183
212
  return `using Workerd = import "/workerd/workerd.capnp";
184
213
  const config :Workerd.Config = (
185
214
  services = [
@@ -201,7 +230,7 @@ const runner :Workerd.Worker = (
201
230
  (name = "${FUNCTION_MODULE}", esModule = embed "${FUNCTION_MODULE}"),
202
231
  ],
203
232
  compatibilityDate = "${COMPATIBILITY_DATE}",
204
- bindings = [(name = "ARCADIBLE_SERVE", text = ${JSON.stringify(serve)})${given}],
233
+ bindings = [(name = "ARCADIBLE_SERVE", text = ${JSON.stringify(serve)})${given}${named}],
205
234
  globalOutbound = "outbound",
206
235
  );
207
236
  const outbound :Workerd.Worker = (
@@ -302,24 +331,22 @@ export async function runner({ dir, handler, hosts = [], main, origin, secrets =
302
331
  ? await tickets.check(ticket, origin)
303
332
  : { data: { code: "invalid" }, status: 422 };
304
333
  if (checked.status !== 200) {
305
- res.writeHead(401, {
306
- ...CORS,
307
- "content-type": "application/json",
308
- [REFUSAL]: checked.data.code,
309
- });
310
- res.end(JSON.stringify({ code: checked.data.code }));
334
+ refuse(res, 401, checked.data.code);
311
335
  return;
312
336
  }
313
337
  // 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);
338
+ // dispatcher refuses it: a streamed one is read here, to hold it. One
339
+ // that couldn't be read is `invalid`, as there.
340
+ let body;
341
+ try {
342
+ body = await bodyOf(req);
343
+ }
344
+ catch {
345
+ refuse(res, 400, "invalid");
346
+ return;
347
+ }
316
348
  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 }));
349
+ refuse(res, 413, TOO_LARGE);
323
350
  return;
324
351
  }
325
352
  // the game's answer when its function failed, as the dispatcher's: why
@@ -8,7 +8,7 @@ import http, {} from "node:http";
8
8
  import { gameHandler, pathOf } from "./game.js";
9
9
  import { pageHandler } from "./page.js";
10
10
  import { reloader } from "./reload.js";
11
- import { PREFIX as RUNNER, runner as startRunner, } from "./runner.js";
11
+ import { noFunction, PREFIX as RUNNER, runner as startRunner, } from "./runner.js";
12
12
  import { playerOf, tickets as ticketsFor } from "./ticket.js";
13
13
  import { values as valuesFor } from "./values.js";
14
14
  import { PREFIX as WIRES, wires as wiresFor } from "./wires.js";
@@ -40,7 +40,7 @@ function listen(handler, port, address) {
40
40
  // or a guest. Resolves with
41
41
  // `{ page, game, reload(), close() }`: the page's origin, the game's URL,
42
42
  // and the controls.
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
+ export async function serve({ art, files, hostFile = null, icon, info, keyFile, onLink, onRemote, player = null, port, remote, root, runner: runs = null, servers = [], connect = [], src, wiresDrop = null, }) {
44
44
  const origins = {
45
45
  game: `http://127.0.0.1:${port}`,
46
46
  page: `http://localhost:${port}`,
@@ -98,7 +98,9 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
98
98
  },
99
99
  hostFile,
100
100
  icon,
101
+ onLink,
101
102
  onRemote,
103
+ origin: origins.page,
102
104
  playerOf: (name) => playerOf(info.id, name),
103
105
  reloads,
104
106
  remote,
@@ -121,8 +123,10 @@ export async function serve({ art, files, hostFile = null, icon, info, keyFile,
121
123
  // what's under the runner's folder, as Arcadible's edge sends it on:
122
124
  // /arcadible/runner itself, like /arcadible/runnerx, is a file of
123
125
  // Arcadible's, like any other there, and isn't found.
124
- const forRunner = runner && onGame && pathname !== null && pathname.startsWith(`${RUNNER}/`)
125
- ? runner.handle
126
+ // A project with no function is answered as Arcadible answers a build
127
+ // with none.
128
+ const forRunner = onGame && pathname !== null && pathname.startsWith(`${RUNNER}/`)
129
+ ? (runner?.handle ?? noFunction)
126
130
  : null;
127
131
  // a game opens a wire at Arcadible's path on its own origin, whether
128
132
  // its files are served here or framed from another server (--url)
@@ -10,7 +10,7 @@ import crypto from "node:crypto";
10
10
  // [import]
11
11
  import { WebSocketServer } from "ws";
12
12
  // [import]
13
- import { CLOSED, createRoom, LIMITS, PING, PONG, PROTOCOL, } from "../wires/room.js";
13
+ import { CLOSED, createRoom, LIMITS, PING, PONG, PROTOCOL, ticketClose, } from "../wires/room.js";
14
14
  import { CHANNEL } from "./ticket.js";
15
15
  // [declare]
16
16
  // where wires answer on a build's own origin, as on Arcadible
@@ -31,8 +31,10 @@ const CORS = {
31
31
  "access-control-expose-headers": REFUSAL,
32
32
  "access-control-max-age": "600",
33
33
  };
34
- // the largest frame a connection may send: a message, with room around it.
35
- const FRAME_MAX = LIMITS.message * 4 + 64;
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;
36
38
  // [function]
37
39
  // arc serve's wires for `game`, on its own `origin`, where a ticket for a
38
40
  // wire is for. `tickets` are arc serve's own (./ticket.ts), which say who's
@@ -183,7 +185,7 @@ export function wires({ drop = null, game, origin, tickets, }) {
183
185
  }
184
186
  void memberOf(ticket).then((who) => {
185
187
  if ("code" in who) {
186
- refuse(who.code);
188
+ ws.close(ticketClose(who.code), who.code);
187
189
  return;
188
190
  }
189
191
  const { on, room } = wire(id);
@@ -205,8 +207,11 @@ export function wires({ drop = null, game, origin, tickets, }) {
205
207
  on.set(key, mine);
206
208
  ws.on("message", (data, isBinary) => {
207
209
  mine.heard = Date.now();
208
- if (isBinary)
210
+ // a wire carries text: JSON, a frame each
211
+ if (isBinary) {
212
+ room.said(key, "");
209
213
  return;
214
+ }
210
215
  const text = data.toString();
211
216
  if (text === PING)
212
217
  ws.send(PONG);
@@ -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
  };
@@ -42,6 +42,16 @@ export const CLOSED = {
42
42
  /** A connection that went unheard: closed, and free to come back. */
43
43
  export const IDLE = 4408;
44
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]
45
55
  // tokens that refill at `rate` a second, up to `burst`: whether one is
46
56
  // there to take, at `at`.
47
57
  function bucket(rate, burst) {
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "license": "Apache-2.0",
46
46
  "name": "arcadible",
47
- "version": "1.0.34"
47
+ "version": "1.0.36"
48
48
  },
49
49
  "node_modules/@asamuzakjp/css-color": {
50
50
  "dependencies": {
@@ -3267,5 +3267,5 @@
3267
3267
  }
3268
3268
  },
3269
3269
  "requires": true,
3270
- "version": "1.0.34"
3270
+ "version": "1.0.36"
3271
3271
  }
package/package.json CHANGED
@@ -68,5 +68,5 @@
68
68
  "test": "tsc && npm run lint && node --test \"test/**/*.test.js\" \"test/**/*.test.mjs\""
69
69
  },
70
70
  "type": "module",
71
- "version": "1.0.34"
71
+ "version": "1.0.36"
72
72
  }