@zaisma/game-server 1.43.0 → 1.45.0

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/bin/local-play.js CHANGED
@@ -325,6 +325,8 @@ export async function startLocalPlay(givenOptions) {
325
325
  }
326
326
  }
327
327
  const glass = await loadGlass(localFolder);
328
+ // A mode a player's band no longer has (13–15's solo-focused, since chat left the presets): their band's own start.
329
+ for (const account of state.accounts) if (!glass.isSocialModeAllowed(account.ageBand, account.socialMode)) account.socialMode = glass.startingSocialMode(account.ageBand);
328
330
  const accountOf = (id) => state.accounts.find((account) => account.id === id) ?? null;
329
331
  const accountOfPlayer = (playerId) => state.accounts.find((account) => account.playerId === playerId) ?? null;
330
332
  const asOf = (playerNumber) => state.tabs[playerNumber] ?? "guest";
@@ -370,12 +372,15 @@ export async function startLocalPlay(givenOptions) {
370
372
  const nowSec = Math.floor(now() / 1000);
371
373
  const account = as === "guest" ? null : accountOf(as);
372
374
  const player = account ? { id: account.playerId, name: account.username, kind: "account" } : { ...guestOf(playerNumber), kind: "guest" };
373
- // Who they chat with, by Zaisma's own rules for their age and social mode, and an opaque chat group for their band, never the age.
374
- const chat = account ? glass.chatOf(account.ageBand, account.socialMode) : null;
375
+ // How their chat reaches, by Zaisma's own rules for their age, and an opaque chat group for their band, never the age.
376
+ // who_can_chat is v1's stricter stand-in, for servers that don't read who_reads_my_chat. The bench seals no network:
377
+ // its own chat check lets every message through.
378
+ const chat = account ? glass.chatOf(account.ageBand) : null;
375
379
  const claims = account
376
380
  ? {
377
381
  sub: account.playerId, aud: gameSlug, iss: issuerUrl, pass_version_number: PASS_VERSION_NUMBER, kind: "account",
378
- who_can_chat: chat.whoCanChat, ...(chat.bandGroup ? { chat_group_id: `chat_group_${createHash("sha256").update(`local:${gameSlug}:${chat.bandGroup}`).digest("hex").slice(0, 24)}` } : {}),
382
+ who_can_chat: chat.whoReadsMyChat === "friends" ? "friends" : "anyone", who_reads_my_chat: chat.whoReadsMyChat, chat_reading_enabled: true,
383
+ chat_group_id: `chat_group_${createHash("sha256").update(`local:${gameSlug}:${chat.bandGroup}`).digest("hex").slice(0, 24)}`,
379
384
  player_tag_id: account.playerTagId, friend_player_tag_ids: tagsOf(friendIdsOf(account.id)), block_player_tag_ids: tagsOf(blockIdsOf(account.id)),
380
385
  owned_item_names: ownedNamesOf(account.id), iat: nowSec, exp: nowSec + PASS_DURATION_SEC,
381
386
  }
@@ -568,7 +573,7 @@ export async function startLocalPlay(givenOptions) {
568
573
  // --- The bench's API: everything the Players panel and the dev bar do, as JSON, for the developer's AI as much as for the panel ---
569
574
  // Players are named by their player_id, the ID games see. Answers and errors are shaped as Zaisma's developer API's.
570
575
  const apiPlayer = (account) => ({
571
- player_id: account.playerId, name: account.username, age_band: account.ageBand, social_mode: account.socialMode, who_can_chat: glass.chatOf(account.ageBand, account.socialMode).whoCanChat,
576
+ player_id: account.playerId, name: account.username, age_band: account.ageBand, social_mode: account.socialMode, who_reads_my_chat: glass.chatOf(account.ageBand).whoReadsMyChat,
572
577
  open_player_numbers: openNumbersOf(account), friend_player_ids: playerIdsOf(friendIdsOf(account.id)), block_player_ids: playerIdsOf(blockedIdsOf(account)),
573
578
  blocked_by_player_ids: playerIdsOf(blockerIdsOf(account)), owned_item_names: ownedNamesOf(account.id),
574
579
  });
@@ -1328,10 +1333,31 @@ export async function startLocalPlay(givenOptions) {
1328
1333
  }
1329
1334
  return notLocal();
1330
1335
  }
1331
- // Zaisma's chat check, as the runner's rooms ask it for room.chat (checkChat): the bench lets every message through,
1332
- // nothing flagged, the way /v1/filter stands in below. Zaisma's own filter runs once the game is on Zaisma.
1336
+ // Zaisma's chat check, as the runner's rooms ask it for room.chat (checkChat). The bench keeps Zaisma's witness rule, so
1337
+ // a game sees here what it will there: a message an under-18 sends or reads goes only where two other players read it
1338
+ // (every bench player counts as established, each on a network of its own), and a stranger from outside Zaisma never
1339
+ // chats with an under-18. Its words aren't checked, nothing is flagged, the way /v1/filter stands in below.
1333
1340
  if (request.method === "POST" && path === "/v1/chat/check") {
1334
- await readBody();
1341
+ const body = await readBody();
1342
+ const subOf = (pass) => {
1343
+ if (typeof pass !== "string") return null;
1344
+ try {
1345
+ return JSON.parse(Buffer.from(pass.split(".")[1] ?? "", "base64url").toString("utf8")).sub ?? null;
1346
+ } catch {
1347
+ return null;
1348
+ }
1349
+ };
1350
+ const senderId = subOf(body.senderPass);
1351
+ const passes = Array.isArray(body.receiverPasses) ? body.receiverPasses : [];
1352
+ const readerIds = [...new Set(passes.map(subOf).filter((id) => id !== null && id !== senderId))];
1353
+ const isMinor = (playerId) => {
1354
+ const account = playerId === null ? null : accountOfPlayer(playerId);
1355
+ return account !== null && account.ageBand !== "18+";
1356
+ };
1357
+ const hasMinor = isMinor(senderId) || readerIds.some(isMinor);
1358
+ const hasOutsider = body.senderPass === null || passes.some((pass) => pass === null);
1359
+ const isWitnessed = readerIds.filter((id) => accountOfPlayer(id) !== null).length >= 2;
1360
+ if (hasMinor && (hasOutsider || !isWitnessed)) return reply(200, { isAllowed: false, reason: "not_allowed_to_chat", message: "Chat isn't open for this message.", hasSwearing: false, hasSlur: false });
1335
1361
  return reply(200, { isAllowed: true, reason: null, message: null, hasSwearing: false, hasSlur: false });
1336
1362
  }
1337
1363
  if (request.method === "POST" && ["/v1/pass", "/v1/rooms", "/v1/report", "/v1/filter", "/v1/friends", "/v1/friends/room", "/v1/items/unhandled", "/v1/items/handled"].includes(path)) {
package/bin/node.js CHANGED
@@ -26,7 +26,7 @@ import { createServer } from "node:http";
26
26
  import { fileURLToPath, pathToFileURL } from "node:url";
27
27
  import { basename, dirname, join, resolve } from "node:path";
28
28
  import { readFileSync, realpathSync } from "node:fs";
29
- import { roomMessageProblem, BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, ERROR_TEXT, NO_ANSWER_CLOSE_CODE, PASS_ISSUER_URL, OUTSIDE_ZAISMA_CHAT_SETTINGS, PassError, ReceiptError, REMOVED_CLOSE_CODE, REQUEST_ERROR_HTTP_STATUS, REQUEST_LIMITS, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_TUNING, WEBHOOK_LIMITS, GameServerError, RoomCore, chatSettingsOf, checkChat, readChatMessage, restoreInfoOf, passesAreFriends, passesHaveBlockBetween, answerRequest, startSchedules, checkRoomData, checkedOutsidePlayer, clientIdle, defineGameServer, errorMessage, guestPlayer, newServer, isPlayerToken, isRoomCode, readRequestBody, relay, requestError, runWebhook, tidyRoomInfo, verifyPass, verifyReceipt, verifyWebhook } from "../src/internal.js";
29
+ import { CHAT_CHECK_LIMITS, roomMessageProblem, BUSY_CLOSE_CODE, ENDED_CLOSE_CODE, ERROR_TEXT, NO_ANSWER_CLOSE_CODE, PASS_ISSUER_URL, OUTSIDE_ZAISMA_CHAT_SETTINGS, PassError, ReceiptError, REMOVED_CLOSE_CODE, REQUEST_ERROR_HTTP_STATUS, REQUEST_LIMITS, ROOM_LIMITS, ROOM_MESSAGE_LIMITS, ROOM_TUNING, WEBHOOK_LIMITS, GameServerError, RoomCore, chatSettingsOf, checkChat, readChatMessage, restoreInfoOf, passesAreFriends, passesHaveBlockBetween, answerRequest, startSchedules, checkRoomData, checkedOutsidePlayer, clientIdle, defineGameServer, errorMessage, guestPlayer, newServer, isPlayerToken, isRoomCode, readRequestBody, relay, requestError, runWebhook, tidyRoomInfo, verifyPass, verifyReceipt, verifyWebhook } from "../src/internal.js";
30
30
  import { OutsideCallError } from "../src/outside-calls.js";
31
31
  import { startFastLane } from "./fast-lane.js";
32
32
  import { checkedStartServerOptions, dataFilesFrom, loadWasmAsModules, localDatabase, localRoomStates, passKeysFrom, profilesFrom, receiptKeysFrom, secretsFromEnvironment } from "./node-parts.js";
@@ -565,8 +565,10 @@ export function startServer(options) {
565
565
  /**
566
566
  * A player's chat message (room.chat): the room checks it and asks the game server's onChat (startChat),
567
567
  * Zaisma's filter looks (checkChat, with the passes of those who may read it), and it goes to them
568
- * (deliverChat) or the sender hears why not (stopChat). Everyone it may reach is in the sender's chat
569
- * group, so the first CHAT_CHECK_LIMITS.maximumReceiverCount of them stand for the rest.
568
+ * (deliverChat) or the sender hears why not (stopChat). More readers than one check takes go in checks of
569
+ * CHAT_CHECK_LIMITS.maximumReceiverCount, each a full one (the last overlaps the one before), so each sees
570
+ * witnesses as the whole room has them, and every one must allow it. Zaisma may have let it through only for
571
+ * the witnesses it counted, so it goes to every reader or, when one can't read it by then, is stopped.
570
572
  */
571
573
  async function chatIn(room, playerId, chat) {
572
574
  const started = await room.core.startChat(playerId, chat);
@@ -576,10 +578,17 @@ export function startServer(options) {
576
578
  // A player from outside Zaisma goes as null: Zaisma stops their chat with under-18 accounts, and doesn't hear chat among them alone.
577
579
  const passOf = (id) => (room.core.players.get(id)?.kind === "outside_zaisma" ? null : (room.passTexts.get(id) ?? ""));
578
580
  const receiverPasses = started.receiverPlayerIds.map(passOf);
579
- check = await checkChat({ text: started.text, senderPass: passOf(playerId), receiverPasses, isAdultFilterEnabled: definition.adultChatFilterEnabled === true });
581
+ const batchReceiverCount = CHAT_CHECK_LIMITS.maximumReceiverCount;
582
+ for (let endIndex = Math.min(batchReceiverCount, receiverPasses.length); ; endIndex = Math.min(endIndex + batchReceiverCount, receiverPasses.length)) {
583
+ const batch = receiverPasses.slice(Math.max(0, endIndex - batchReceiverCount), endIndex);
584
+ const batchCheck = await checkChat({ text: started.text, senderPass: passOf(playerId), receiverPasses: batch, isAdultFilterEnabled: definition.adultChatFilterEnabled === true });
585
+ check = { ...batchCheck, hasSwearing: check.hasSwearing || batchCheck.hasSwearing, hasSlur: check.hasSlur || batchCheck.hasSlur };
586
+ if (!batchCheck.isAllowed || endIndex === receiverPasses.length) break;
587
+ }
580
588
  }
581
- if (check.isAllowed) room.core.deliverChat(playerId, chat.chatNumber, started.receiverPlayerIds, { text: started.text, hasSwearing: check.hasSwearing, hasSlur: check.hasSlur });
582
- else room.core.stopChat(playerId, chat.chatNumber, check.reason ?? "unchecked", check.message ?? "");
589
+ if (!check.isAllowed) return room.core.stopChat(playerId, chat.chatNumber, check.reason ?? "unchecked", check.message ?? "");
590
+ const isDelivered = room.core.deliverChat(playerId, chat.chatNumber, started.receiverPlayerIds, { text: started.text, hasSwearing: check.hasSwearing, hasSlur: check.hasSlur }, { isEveryReaderNeeded: true });
591
+ if (!isDelivered) room.core.stopChat(playerId, chat.chatNumber, "not_allowed_to_chat", "Chat isn't open for this message.");
583
592
  }
584
593
 
585
594
  /** Keep a room for players on their way, even if it empties meanwhile. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/game-server",
3
- "version": "1.43.0",
3
+ "version": "1.45.0",
4
4
  "description": "Run your Zaisma game server: the same rooms on Zaisma or on your own server.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://zaisma.com",
package/sdk/zaisma.d.ts CHANGED
@@ -1268,8 +1268,11 @@ declare namespace Zaisma {
1268
1268
  block(playerId: string): Promise<boolean>;
1269
1269
  /**
1270
1270
  * Report a player to Zaisma, with what happened in the player's own words if they gave any (details).
1271
- * The last chat lines (up to 20) they sent this player, or this player sent them, go with it from this
1272
- * screen; nothing else about the reporting player is sent.
1271
+ * On Zaisma it opens Zaisma's report sheet beside the game, filled in with the player, reason and words,
1272
+ * where the player picks the messages to send and sends it: only reports a player sends there count
1273
+ * toward muting someone. Resolves once they send it; rejects with error.code "report_not_sent" when they
1274
+ * close it without sending. Off Zaisma (a game's own site) the last chat lines (up to 20) they sent this
1275
+ * player, or this player sent them, go with it; nothing else about the reporting player is sent.
1273
1276
  */
1274
1277
  report(playerId: string, reason: ReportReason, details?: string): Promise<ReportAnswer>;
1275
1278
  /**
@@ -1593,10 +1596,11 @@ declare namespace Zaisma {
1593
1596
  * game's own keys at https://rooms.zaisma.com/v1/pass-keys/<gameSlug>. It proves only who the player is: its sub
1594
1597
  * is the player's ID, kind says guest or account, aud is the game, pass_version_number is 1. A
1595
1598
  * guest's pass also carries their name; an account's name comes from its profile
1596
- * (https://rooms.zaisma.com/v1/players/<id>). An account's pass says who it can chat with:
1597
- * who_can_chat (nobody, friends or anyone, the player's own setting) and, when anyone, an opaque
1598
- * chat_group_id (chat_group_…) that differs in every game. Zaisma never tells a game anyone's age; a
1599
- * game could guess which chat group is the younger one from its size. It carries its friends and
1599
+ * (https://rooms.zaisma.com/v1/players/<id>). An account's pass says how its chat reaches:
1600
+ * who_reads_my_chat (friends, my_age_band or everyone; nobody while its chat is stopped), chat_reading_enabled,
1601
+ * an opaque chat_group_id (chat_group_…) that differs in every game, network_seal (its network, sealed for
1602
+ * Zaisma's witness rule alone), and v1's who_can_chat as a stricter stand-in. Zaisma never tells a game anyone's
1603
+ * age; a game could guess which chat group is the younger one from its size. It carries its friends and
1600
1604
  * blocks, never as a list of players anyone can read: player_tag_id, its own opaque tag in this game
1601
1605
  * (player_tag_…), friend_player_tag_ids, its friends' tags (up to 200), and block_player_tag_ids, the
1602
1606
  * tags of the accounts it has a block with, either way (up to 100). Your own server checks it with
@@ -1782,6 +1786,7 @@ declare namespace Zaisma {
1782
1786
  * - slow_down: too many calls; try again in a minute.
1783
1787
  * - zaisma_rooms_not_used: the game doesn't use Zaisma rooms.
1784
1788
  * - bad_report: a report whose reason isn't a {@link ReportReason}, or whose player ID isn't one.
1789
+ * - report_not_sent: the player closed Zaisma's report sheet, which {@link Room.report} opened, without sending it.
1785
1790
  * - bad_origin: the call didn't come from the game's own page.
1786
1791
  * - not_on_zaisma: the game is played off Zaisma, so it has no player passes, sign-in or room lists; joinRoom and server.request need {@link setUpOffZaisma} and a serverUrl.
1787
1792
  * - bad_game_slug: {@link setUpOffZaisma}'s gameSlug isn't a game slug: 1 to 40 lowercase letters, digits or hyphens.
@@ -1811,6 +1816,7 @@ declare namespace Zaisma {
1811
1816
  type ErrorCode =
1812
1817
  | RoomErrorCode
1813
1818
  | RequestErrorCode
1819
+ | "report_not_sent"
1814
1820
  | "chat_stopped"
1815
1821
  | "chat_not_allowed"
1816
1822
  | "chat_empty"
@@ -1916,7 +1922,7 @@ declare namespace Zaisma {
1916
1922
  type ChatCheckReason = "contact_details" | "personal_details" | "slur" | "sexual" | "unchecked" | "too_long";
1917
1923
 
1918
1924
  /** What happened, in a player report. Zaisma looks at real_life_threat (a threat that reaches past the game: their real details, finding them, a plan), personal_details (sharing someone's), following_after_block and sexual (behavior); harassment, cheating and other go to the game's developer. */
1919
- type ReportReason = "real_life_threat" | "personal_details" | "following_after_block" | "sexual" | "harassment" | "cheating" | "other";
1925
+ type ReportReason = "real_life_threat" | "personal_details" | "following_after_block" | "sexual" | "harassment" | "cheating" | "wrong_age" | "under_13" | "other";
1920
1926
 
1921
1927
  /** Zaisma's answer to a report. */
1922
1928
  interface ReportAnswer {
package/sdk/zaisma.js CHANGED
@@ -1751,10 +1751,20 @@
1751
1751
  return blockAsk;
1752
1752
  }
1753
1753
  /**
1754
- * Report a player to Zaisma. reason: real_life_threat, personal_details, following_after_block or sexual (Zaisma looks), or harassment, cheating or other (passed to the game's developer).
1755
- * The last chat lines they sent you, or you sent them, go with it (up to 20); nothing else about you is sent.
1754
+ * Report a player to Zaisma. reason: real_life_threat, personal_details, following_after_block, sexual, wrong_age or under_13 (Zaisma looks), or harassment, cheating or other (passed to the game's developer).
1755
+ * On a Zaisma page it opens Zaisma's report sheet beside the game, filled in, and the player sends it there: only a report the
1756
+ * player sends from Zaisma counts toward muting someone. Anywhere else the last chat lines they sent you, or you sent them,
1757
+ * go with it (up to 20); nothing else about you is sent.
1756
1758
  */
1757
1759
  Room.prototype.report = function (playerId, reason, details) {
1760
+ var reported = this.players.filter(function (each) { return each.id === playerId; })[0];
1761
+ var room = this;
1762
+ var sendDirectly = function () { return room._sendReport(playerId, reason, details); };
1763
+ if (onZaismaPage() && this.roomCode) return askPageToReport(this.roomCode, { id: playerId, name: reported ? reported.name : "" }, reason, details || "", sendDirectly);
1764
+ return sendDirectly();
1765
+ };
1766
+ /** A report straight to Zaisma's rooms, with the last chat lines: off Zaisma, or when the page has no report sheet. */
1767
+ Room.prototype._sendReport = function (playerId, reason, details) {
1758
1768
  var reported = this.players.filter(function (each) { return each.id === playerId; })[0];
1759
1769
  var me = this.me ? this.me.id : null;
1760
1770
  var chatMessages = this._chatLines.filter(function (line) {
@@ -2845,6 +2855,49 @@
2845
2855
  });
2846
2856
  });
2847
2857
 
2858
+ /**
2859
+ * Zaisma's report sheet, opened beside the game for room.report: resolves { isReported: true } once the player sends it, and rejects
2860
+ * (report_not_sent) when they close it. A page that doesn't say it opened the sheet within REPORT_SHEET_WAIT_MS gets the report the
2861
+ * way it goes off Zaisma instead (fallback), so room.report never hangs.
2862
+ */
2863
+ var REPORT_SHEET_WAIT_MS = 3000;
2864
+ var reportAsks = {};
2865
+ function askPageToReport(roomCode, player, reason, details, fallback) {
2866
+ if (reportAsks[player.id]) return reportAsks[player.id];
2867
+ reportAsks[player.id] = new Promise(function (resolve, reject) {
2868
+ var isOpened = false;
2869
+ var timer = setTimeout(function () { if (!isOpened) settle(function () { fallback().then(resolve, reject); }); }, REPORT_SHEET_WAIT_MS);
2870
+ function settle(then) {
2871
+ removeEventListener("message", onMessage);
2872
+ clearTimeout(timer);
2873
+ delete reportAsks[player.id];
2874
+ then();
2875
+ }
2876
+ function onMessage(event) {
2877
+ if (event.origin !== config.site || event.source !== window.parent || !event.data || event.data.playerId !== player.id) return;
2878
+ if (event.data.type === "zaisma:report-opened") { isOpened = true; return; }
2879
+ if (event.data.type !== "zaisma:report-done") return;
2880
+ settle(function () {
2881
+ if (event.data.isReported === true) resolve({ isReported: true });
2882
+ else reject(codedError("report_not_sent", "The player closed Zaisma's report sheet without sending it."));
2883
+ });
2884
+ }
2885
+ addEventListener("message", onMessage);
2886
+ window.parent.postMessage({ type: "zaisma:report-player", code: roomCode, player: player, reason: typeof reason === "string" ? reason : "", details: String(details).slice(0, 2000) }, config.site);
2887
+ });
2888
+ return reportAsks[player.id];
2889
+ }
2890
+
2891
+ // Zaisma's report sheet asks for a player's last chat lines on this screen, for the player to tick the ones to send.
2892
+ window.addEventListener("message", function (event) {
2893
+ if (!config.site || event.origin !== config.site || event.source !== window.parent || !event.data || event.data.type !== "zaisma:chat-lines-request") return;
2894
+ var playerId = event.data.playerId, lines = [];
2895
+ joined.forEach(function (room) {
2896
+ room._chatLines.forEach(function (line) { if (line.fromPlayerId === playerId) lines.push({ fromPlayerId: line.fromPlayerId, text: line.text, sentAt: line.sentAt }); });
2897
+ });
2898
+ window.parent.postMessage({ type: "zaisma:chat-lines", id: event.data.id, playerId: playerId, lines: lines.slice(-REPORTED_CHAT_LINE_COUNT) }, config.site);
2899
+ });
2900
+
2848
2901
  // The Zaisma page says when a player report was sent from its plate: mute them, as the panel's own form does.
2849
2902
  window.addEventListener("message", function (event) {
2850
2903
  if (!config.site || event.origin !== config.site || event.source !== window.parent || !event.data || event.data.type !== "zaisma:reported") return;
package/src/chat.d.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  /**
2
- * Zaisma's chat filter for your own server (docs/DECISIONS.md, "The text filter catches what matters and
3
- * leaves the rest alone"). Every chat message to or from an under-18 account is checked on Zaisma's side:
4
- * contact details in any disguise, moving to another app or meeting up, personal details and sexual
5
- * content are stopped. Swearing and slurs are only flagged (hasSwearing, hasSlur): blocking them is your
6
- * call. Between adults it only flags, unless you turn the filter on for them too (isAdultFilterEnabled).
7
- * The answer is one verdict for the whole message, never per receiver, so it never says who's under 18.
2
+ * Zaisma's chat check for your own server ("Chat with witnesses"). Every chat message an under-18 account sends or
3
+ * reads is checked on Zaisma's side, by two rules: it goes only where at least two independent players read it
4
+ * (established accounts on networks unlike the sender's and each other's, whispers and two-player rooms included),
5
+ * and it can't carry contact details, moving to another app or meeting up, in any disguise. Swearing and slurs are
6
+ * only flagged (hasSwearing, hasSlur): blocking them is your call. Between adults it only flags, unless you turn
7
+ * the filter on for them too (isAdultFilterEnabled). The answer is one verdict for the whole message, never per
8
+ * receiver; a message stopped between two players does show that one of them is under 18. Send the passes of the
9
+ * players who really read it: your server is trusted to, as it's trusted to call this at all.
8
10
  *
9
11
  * checkChat sends the players' passes (as your server received them) and the sender's last few messages to
10
12
  * Zaisma (POST <issuer>/v1/chat/check), so a phone number sent a few digits at a time is caught too.
@@ -18,8 +20,9 @@
18
20
  * server running there never sees passes, and checkChat throws a ChatCheckError (own_server_only).
19
21
  */
20
22
  /**
21
- * Why a message was stopped. The same reasons as Zaisma.checkChat, plus chat_paused, not_allowed_to_chat and
22
- * unchecked (Zaisma couldn't be reached). slur is v1's and no longer given: slurs are flagged (hasSlur), never stopped.
23
+ * Why a message was stopped: contact_details, chat_paused, too_long, not_allowed_to_chat (canChat says no for a
24
+ * receiver, or too few independent players read a message an under-18 is in) and unchecked (Zaisma couldn't be
25
+ * reached). personal_details, sexual and slur are v1's and no longer given.
23
26
  */
24
27
  export type ChatCheckReason = "contact_details" | "personal_details" | "slur" | "sexual" | "chat_paused" | "unchecked" | "too_long" | "not_allowed_to_chat";
25
28
  export interface ChatCheck {
@@ -28,7 +31,8 @@ export interface ChatCheck {
28
31
  /**
29
32
  * Why not; null when it's allowed. chat_paused: the sender's chat is paused or removed. unchecked: your
30
33
  * server couldn't reach Zaisma, so don't deliver it (try again in a moment). too_long: over 2000 characters.
31
- * not_allowed_to_chat: canChat says the sender and a receiver may not chat (Zaisma checks it too).
34
+ * not_allowed_to_chat: canChat says a receiver may not read the sender (Zaisma checks it too), or the message has
35
+ * an under-18 in it and fewer than two independent players read it.
32
36
  */
33
37
  reason: ChatCheckReason | null;
34
38
  /** The words to show the sender when it's stopped (never mentions age or the other player); null when it's allowed. */
@@ -45,7 +49,7 @@ export interface ChatCheckOptions {
45
49
  senderPass: string | null;
46
50
  /** The passes of everyone it would reach, up to 50; null for each player from outside Zaisma. */
47
51
  receiverPasses: (string | null)[];
48
- /** Check chat between adults too, as for under-18s; each message Zaisma's AI looks at counts on your hosting meter. False by default. */
52
+ /** Check chat between adults for contact details too, as for under-18s. Free. False by default. */
49
53
  isAdultFilterEnabled?: boolean;
50
54
  }
51
55
  /** Chat in rooms (room.chat), for both Zaisma's rooms and your own server's runner: past any human's typing, so it only stops floods. */
@@ -73,10 +77,10 @@ export declare class ChatCheckError extends Error {
73
77
  constructor(message: string, fix: string);
74
78
  }
75
79
  /**
76
- * Check one chat message with Zaisma's filter. Call it on every chat message your server delivers, after
77
- * canChat says the players may chat, and deliver it only when isAllowed (Zaisma applies canChat's rule
78
- * too, so a message to anyone who may not chat is stopped). It's free, except the checks of chat between
79
- * adults when isAdultFilterEnabled. When Zaisma can't be reached it answers unchecked: don't deliver the message.
80
+ * Check one chat message with Zaisma's filter. Call it on every chat message your server delivers, with the passes
81
+ * of everyone who'd read it, after canChat(sender, reader) says each may, and deliver it only when isAllowed, to all
82
+ * of them (Zaisma applies canChat's rule too, and may allow it only for the witnesses among them). It's free. When
83
+ * Zaisma can't be reached it answers unchecked: don't deliver the message.
80
84
  * The runner (zaisma-game-server) does all this for room.chat in its rooms.
81
85
  *
82
86
  * const check = await checkChat({ text, senderPass, receiverPasses: [receiverPass] });
package/src/chat.js CHANGED
@@ -1,10 +1,12 @@
1
1
  /**
2
- * Zaisma's chat filter for your own server (docs/DECISIONS.md, "The text filter catches what matters and
3
- * leaves the rest alone"). Every chat message to or from an under-18 account is checked on Zaisma's side:
4
- * contact details in any disguise, moving to another app or meeting up, personal details and sexual
5
- * content are stopped. Swearing and slurs are only flagged (hasSwearing, hasSlur): blocking them is your
6
- * call. Between adults it only flags, unless you turn the filter on for them too (isAdultFilterEnabled).
7
- * The answer is one verdict for the whole message, never per receiver, so it never says who's under 18.
2
+ * Zaisma's chat check for your own server ("Chat with witnesses"). Every chat message an under-18 account sends or
3
+ * reads is checked on Zaisma's side, by two rules: it goes only where at least two independent players read it
4
+ * (established accounts on networks unlike the sender's and each other's, whispers and two-player rooms included),
5
+ * and it can't carry contact details, moving to another app or meeting up, in any disguise. Swearing and slurs are
6
+ * only flagged (hasSwearing, hasSlur): blocking them is your call. Between adults it only flags, unless you turn
7
+ * the filter on for them too (isAdultFilterEnabled). The answer is one verdict for the whole message, never per
8
+ * receiver; a message stopped between two players does show that one of them is under 18. Send the passes of the
9
+ * players who really read it: your server is trusted to, as it's trusted to call this at all.
8
10
  *
9
11
  * checkChat sends the players' passes (as your server received them) and the sender's last few messages to
10
12
  * Zaisma (POST <issuer>/v1/chat/check), so a phone number sent a few digits at a time is caught too.
@@ -77,10 +79,10 @@ function rememberText(senderPlayerId, text, nowMs) {
77
79
  recentBySender.set(senderPlayerId, recent.slice(-CHAT_CHECK_LIMITS.recentTextCount));
78
80
  }
79
81
  /**
80
- * Check one chat message with Zaisma's filter. Call it on every chat message your server delivers, after
81
- * canChat says the players may chat, and deliver it only when isAllowed (Zaisma applies canChat's rule
82
- * too, so a message to anyone who may not chat is stopped). It's free, except the checks of chat between
83
- * adults when isAdultFilterEnabled. When Zaisma can't be reached it answers unchecked: don't deliver the message.
82
+ * Check one chat message with Zaisma's filter. Call it on every chat message your server delivers, with the passes
83
+ * of everyone who'd read it, after canChat(sender, reader) says each may, and deliver it only when isAllowed, to all
84
+ * of them (Zaisma applies canChat's rule too, and may allow it only for the witnesses among them). It's free. When
85
+ * Zaisma can't be reached it answers unchecked: don't deliver the message.
84
86
  * The runner (zaisma-game-server) does all this for room.chat in its rooms.
85
87
  *
86
88
  * const check = await checkChat({ text, senderPass, receiverPasses: [receiverPass] });
package/src/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export { SCHEDULE_LIMITS, type Schedule, type ScheduledRun } from "./schedules.t
4
4
  export { WEBHOOK_LIMITS, verifyWebhook, type WebhookError, type WebhookErrorCode, type WebhookEvent, type WebhookEventKind, type WebhookHeaders } from "./webhooks.ts";
5
5
  export { DATABASE_LIMITS, DatabaseError, type DatabaseErrorCode, type DatabaseRow, type DatabaseStatement, type DatabaseValue, type GameDatabase } from "./database.ts";
6
6
  export { OUTSIDE_CALL_LIMITS, OutsideCallError, type OutsideCallErrorCode } from "./outside-calls.ts";
7
- export { PASS_ISSUER_URL, PASS_TOKEN_TYPE, PASS_VERSION_NUMBER, PassError, RECEIPT_ISSUER_URL, RECEIPT_TOKEN_TYPE, RECEIPT_VERSION_NUMBER, ReceiptError, canChat, passesAreFriends, passesHaveBlockBetween, verifyPass, verifyReceipt, type PassClaims, type PassErrorCode, type PassExpectations, type PlayerKind, type PublicKey, type ReceiptClaims, type ReceiptErrorCode, type ReceiptExpectations, type WhoCanChat } from "./pass.ts";
7
+ export { PASS_ISSUER_URL, PASS_TOKEN_TYPE, PASS_VERSION_NUMBER, PassError, RECEIPT_ISSUER_URL, RECEIPT_TOKEN_TYPE, RECEIPT_VERSION_NUMBER, ReceiptError, canChat, passesAreFriends, passesHaveBlockBetween, verifyPass, verifyReceipt, type PassClaims, type PassErrorCode, type PassExpectations, type PlayerKind, type PublicKey, type ReceiptClaims, type ReceiptErrorCode, type ReceiptExpectations, type WhoCanChat, type WhoReadsMyChat, type ChatReach } from "./pass.ts";
8
8
  export { CHAT_CHECK_LIMITS, CHAT_ROOM_LIMITS, ChatCheckError, checkChat, type ChatCheck, type ChatCheckOptions, type ChatCheckReason } from "./chat.ts";
9
9
  export { guestName, isRoomCode } from "./names.ts";
10
10
  export { guestPlayer, signInWithZaismaPlayers, type IdentifyPlayer, type OutsidePlayer, type SignInWithZaismaPlayersOptions } from "./outside-players.ts";
package/src/pass.d.ts CHANGED
@@ -22,15 +22,28 @@ export interface PassClaims {
22
22
  /** guest or account, or a kind added later: treat one your server doesn't know as a guest. */
23
23
  kind: PlayerKind | (string & {});
24
24
  /**
25
- * Who an account lets chat with it: nobody, its friends, or anyone in its chat group, or a choice
26
- * added later (canChat matches only the ones it knows, so an unknown one chats with nobody).
27
- * Guests' passes have none: guests don't chat.
25
+ * v1's chat setting, still sent for servers that don't read who_reads_my_chat: a stricter stand-in for it
26
+ * (nobody when the account's chat is stopped or it reads no chat, friends for Friends, anyone otherwise),
27
+ * read by canChat only on a pass without who_reads_my_chat. Guests' passes have none: guests don't chat.
28
28
  */
29
29
  who_can_chat?: WhoCanChat | (string & {});
30
30
  /**
31
- * For accounts that chat at all (friends or anyone), the group they can chat in (chat_group_…): two
32
- * players chat only when their groups match (canChat), friends included. Opaque and different in every
33
- * game, so it never says an age; a game could guess which group is the younger one from its size.
31
+ * Who reads what this account types: its friends in its chat group, anyone in its chat group, everyone, or
32
+ * nobody while its chat is stopped; a choice added later reaches nobody. Guests' passes have none.
33
+ */
34
+ who_reads_my_chat?: WhoReadsMyChat | "nobody" | (string & {});
35
+ /** Whether this account reads others' chat at all: false when the player turned it off. Guests' passes have none. */
36
+ chat_reading_enabled?: boolean;
37
+ /**
38
+ * The player's network, sealed for Zaisma alone with a fresh nonce on every pass: it says nothing to your
39
+ * server, and two seals of one network look nothing alike. Zaisma's chat check opens it for the witness rule
40
+ * (anyone under 18 types only where two independent players read it). Pass it on as it is, in the pass.
41
+ */
42
+ network_seal?: string;
43
+ /**
44
+ * An account's chat group (chat_group_…): Friends and My age band reach only the same group, and only a
45
+ * sender who chose Everyone crosses it. Opaque and different in every game, so it never says an age; a game
46
+ * could guess which group is the younger one from its size.
34
47
  */
35
48
  chat_group_id?: string;
36
49
  /**
@@ -68,8 +81,26 @@ export interface PassClaims {
68
81
  * guest from elsewhere (outsideGuestsEnabled). Zaisma's rooms and passes never give outside_zaisma.
69
82
  */
70
83
  export type PlayerKind = "guest" | "account" | "outside_zaisma";
71
- /** No chat, friends only, or anyone in the same chat group: the player's "Who can chat with you" setting (docs/DECISIONS.md, "Social settings, with the social modes as presets"). */
84
+ /** v1's chat setting: no chat, friends only, or anyone in the same chat group, both ways. who_reads_my_chat replaces it. */
72
85
  export type WhoCanChat = "nobody" | "friends" | "anyone";
86
+ /** Who reads what a player types: friends in their chat group, anyone in it, or everyone (the only choice that crosses chat groups). */
87
+ export type WhoReadsMyChat = "friends" | "my_age_band" | "everyone";
88
+ /** How far one side of chat reaches: a sender's who_reads_my_chat, or whose chat a reader reads. */
89
+ export type ChatReach = "nobody" | "friends" | "my_age_band" | "everyone";
90
+ /**
91
+ * How far a pass's chat reaches, sending and reading. A pass with who_reads_my_chat says so directly (and reads
92
+ * everyone's chat unless chat_reading_enabled is false); a v1 pass's who_can_chat counts for both sides, as v1's
93
+ * two-way rule did (friends: friends; anyone: the chat group). Guests and unknown choices reach nobody.
94
+ */
95
+ export declare function chatReachOf(claims: Pick<PassClaims, "kind" | "who_can_chat" | "who_reads_my_chat" | "chat_reading_enabled">): {
96
+ sending: ChatReach;
97
+ reading: ChatReach;
98
+ };
99
+ /** Whether one side's reach takes in the other player: everyone; the same chat group; or a friend in it. */
100
+ export declare function isWithinChatReach(reach: ChatReach, other: {
101
+ isSameChatGroup: boolean;
102
+ isFriend: boolean;
103
+ }): boolean;
73
104
  /** A pass's JWS header typ (RFC 8725 explicit typing): verifyPass refuses any other token (wrong_kind). */
74
105
  export declare const PASS_TOKEN_TYPE = "pass+jwt";
75
106
  /** The pass contract this copy reads: verifyPass refuses any other pass_version_number (wrong_version). */
@@ -92,12 +123,12 @@ export declare function passesHaveBlockBetween(first: PassClaims, second: PassCl
92
123
  */
93
124
  export declare function passesAreFriends(first: PassClaims, second: PassClaims): boolean;
94
125
  /**
95
- * Whether two players may chat, by the passes your server checked (verifyPass): both accounts in the same
96
- * chat group, no block between them, neither letting nobody chat, and either friends or both letting
97
- * anyone chat. Guests and accounts set to nobody never chat; accounts set to friends chat only with
98
- * friends (passesAreFriends); friends in different chat groups don't chat. Use it on every message your
99
- * own server delivers, text or voice; Zaisma's chat check (checkChat) applies the same rule, and so do
100
- * rooms (room.chat), on Zaisma and in the runner.
126
+ * Whether the first player's chat may reach the second: first is the sender, second the reader, and the order
127
+ * matters (ask both ways for a two-way check, like voice between two players). Both accounts, no block between
128
+ * them, the reader reads chat, and the sender's choice takes the reader in: everyone; anyone in the same chat
129
+ * group (My age band); or a friend in it (passesAreFriends). Guests never chat. Use it on every message your own
130
+ * server delivers, text or voice; Zaisma's chat check (checkChat) applies the same rule, and the witness rule on
131
+ * top (anyone under 18 types only where two independent players read it), and so do rooms (room.chat).
101
132
  */
102
133
  export declare function canChat(first: PassClaims, second: PassClaims): boolean;
103
134
  export type PublicKey = JsonWebKey & {
package/src/pass.js CHANGED
@@ -3,6 +3,29 @@
3
3
  * and so can any developer's own server, using its game's keys, published at
4
4
  * /v1/pass-keys/<gameSlug>. Any JWT library that supports EdDSA works.
5
5
  */
6
+ /**
7
+ * How far a pass's chat reaches, sending and reading. A pass with who_reads_my_chat says so directly (and reads
8
+ * everyone's chat unless chat_reading_enabled is false); a v1 pass's who_can_chat counts for both sides, as v1's
9
+ * two-way rule did (friends: friends; anyone: the chat group). Guests and unknown choices reach nobody.
10
+ */
11
+ export function chatReachOf(claims) {
12
+ if (claims.kind !== "account")
13
+ return { sending: "nobody", reading: "nobody" };
14
+ if (claims.who_reads_my_chat !== undefined) {
15
+ const sending = ["friends", "my_age_band", "everyone"].find((reach) => reach === claims.who_reads_my_chat) ?? "nobody";
16
+ return { sending, reading: claims.chat_reading_enabled === false ? "nobody" : "everyone" };
17
+ }
18
+ const reach = claims.who_can_chat === "friends" ? "friends" : claims.who_can_chat === "anyone" ? "my_age_band" : "nobody";
19
+ return { sending: reach, reading: reach };
20
+ }
21
+ /** Whether one side's reach takes in the other player: everyone; the same chat group; or a friend in it. */
22
+ export function isWithinChatReach(reach, other) {
23
+ if (reach === "everyone")
24
+ return true;
25
+ if (reach === "my_age_band")
26
+ return other.isSameChatGroup;
27
+ return reach === "friends" && other.isSameChatGroup && other.isFriend;
28
+ }
6
29
  /** A pass's JWS header typ (RFC 8725 explicit typing): verifyPass refuses any other token (wrong_kind). */
7
30
  export const PASS_TOKEN_TYPE = "pass+jwt";
8
31
  /** The pass contract this copy reads: verifyPass refuses any other pass_version_number (wrong_version). */
@@ -44,12 +67,12 @@ export function passesAreFriends(first, second) {
44
67
  return lists(first, second) && lists(second, first);
45
68
  }
46
69
  /**
47
- * Whether two players may chat, by the passes your server checked (verifyPass): both accounts in the same
48
- * chat group, no block between them, neither letting nobody chat, and either friends or both letting
49
- * anyone chat. Guests and accounts set to nobody never chat; accounts set to friends chat only with
50
- * friends (passesAreFriends); friends in different chat groups don't chat. Use it on every message your
51
- * own server delivers, text or voice; Zaisma's chat check (checkChat) applies the same rule, and so do
52
- * rooms (room.chat), on Zaisma and in the runner.
70
+ * Whether the first player's chat may reach the second: first is the sender, second the reader, and the order
71
+ * matters (ask both ways for a two-way check, like voice between two players). Both accounts, no block between
72
+ * them, the reader reads chat, and the sender's choice takes the reader in: everyone; anyone in the same chat
73
+ * group (My age band); or a friend in it (passesAreFriends). Guests never chat. Use it on every message your own
74
+ * server delivers, text or voice; Zaisma's chat check (checkChat) applies the same rule, and the witness rule on
75
+ * top (anyone under 18 types only where two independent players read it), and so do rooms (room.chat).
53
76
  */
54
77
  export function canChat(first, second) {
55
78
  mustBePasses(first, second, "canChat");
@@ -57,13 +80,10 @@ export function canChat(first, second) {
57
80
  return false;
58
81
  if (passesHaveBlockBetween(first, second))
59
82
  return false;
60
- const isOpenTo = (whoCanChat) => whoCanChat === "friends" || whoCanChat === "anyone";
61
- if (!isOpenTo(first.who_can_chat) || !isOpenTo(second.who_can_chat))
83
+ if (typeof first.chat_group_id !== "string" || typeof second.chat_group_id !== "string")
62
84
  return false;
63
- // Chat never leaves a chat group, friends included.
64
- if (typeof first.chat_group_id !== "string" || first.chat_group_id !== second.chat_group_id)
65
- return false;
66
- return passesAreFriends(first, second) || (first.who_can_chat === "anyone" && second.who_can_chat === "anyone");
85
+ const other = { isSameChatGroup: first.chat_group_id === second.chat_group_id, isFriend: passesAreFriends(first, second) };
86
+ return isWithinChatReach(chatReachOf(first).sending, other) && isWithinChatReach(chatReachOf(second).reading, other);
67
87
  }
68
88
  // Plain class fields (no TypeScript-only syntax) so Node can run this file directly.
69
89
  export class PassError extends Error {
@@ -188,6 +208,12 @@ export async function verifyPass(token, keys, expect) {
188
208
  throw new PassError("malformed");
189
209
  if (claims.chat_group_id !== undefined && typeof claims.chat_group_id !== "string")
190
210
  throw new PassError("malformed");
211
+ if (claims.who_reads_my_chat !== undefined && typeof claims.who_reads_my_chat !== "string")
212
+ throw new PassError("malformed");
213
+ if (claims.chat_reading_enabled !== undefined && typeof claims.chat_reading_enabled !== "boolean")
214
+ throw new PassError("malformed");
215
+ if (claims.network_seal !== undefined && typeof claims.network_seal !== "string")
216
+ throw new PassError("malformed");
191
217
  if (claims.player_tag_id !== undefined && typeof claims.player_tag_id !== "string")
192
218
  throw new PassError("malformed");
193
219
  if (claims.friend_player_tag_ids !== undefined && !isStringList(claims.friend_player_tag_ids))