@zaisma/game-server 1.47.0 → 1.48.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/src/internal.d.ts CHANGED
@@ -12,5 +12,6 @@ export * from "./webhooks.ts";
12
12
  export * from "./pass.ts";
13
13
  export * from "./names.ts";
14
14
  export * from "./chat.ts";
15
+ export * from "./voice-ticket.ts";
15
16
  export * from "./relay.ts";
16
17
  export * from "./doors.ts";
package/src/internal.js CHANGED
@@ -14,5 +14,6 @@ export * from "./webhooks.js";
14
14
  export * from "./pass.js";
15
15
  export * from "./names.js";
16
16
  export * from "./chat.js";
17
+ export * from "./voice-ticket.js";
17
18
  export * from "./relay.js";
18
19
  export * from "./doors.js";
package/src/pass.d.ts CHANGED
@@ -34,6 +34,13 @@ export interface PassClaims {
34
34
  who_reads_my_chat?: WhoReadsMyChat | "nobody" | (string & {});
35
35
  /** Whether this account reads others' chat at all: false when the player turned it off. Guests' passes have none. */
36
36
  chat_reading_enabled?: boolean;
37
+ /**
38
+ * Who hears this account talk, in games with voice: the same choices and the same narrowing as who_reads_my_chat
39
+ * (nobody while its chat is stopped). A pass without it is heard as far as it's read (canVoiceChat). Guests' passes have none.
40
+ */
41
+ who_hears_my_voice?: WhoReadsMyChat | "nobody" | (string & {});
42
+ /** Whether this account hears others talk at all: false when the player turned it off. Guests' passes have none. */
43
+ voice_hearing_enabled?: boolean;
37
44
  /**
38
45
  * The player's network, sealed for Zaisma alone with a fresh nonce on every pass: it says nothing to your
39
46
  * server, and two seals of one network look nothing alike. Zaisma's chat check opens it for the witness rule
@@ -131,6 +138,14 @@ export declare function passesAreFriends(first: PassClaims, second: PassClaims):
131
138
  * top (anyone under 18 types only where two independent players read it), and so do rooms (room.chat).
132
139
  */
133
140
  export declare function canChat(first: PassClaims, second: PassClaims): boolean;
141
+ /**
142
+ * Whether the first player's voice may reach the second: first is the speaker, second the listener, and the order
143
+ * matters. canChat's rule over the voice choices: both accounts, no block between them, the listener hears voice, and
144
+ * the speaker's who_hears_my_voice takes the listener in (everyone; the same chat group; or a friend in it). A pass
145
+ * from before voice is heard as far as it's read. Zaisma's rooms apply it, and the witness rule on top (anyone under
146
+ * 18 is heard only where two independent players hear them too); use it on any voice your own server passes on.
147
+ */
148
+ export declare function canVoiceChat(first: PassClaims, second: PassClaims): boolean;
134
149
  export type PublicKey = JsonWebKey & {
135
150
  kid: string;
136
151
  };
package/src/pass.js CHANGED
@@ -85,6 +85,22 @@ export function canChat(first, second) {
85
85
  const other = { isSameChatGroup: first.chat_group_id === second.chat_group_id, isFriend: passesAreFriends(first, second) };
86
86
  return isWithinChatReach(chatReachOf(first).sending, other) && isWithinChatReach(chatReachOf(second).reading, other);
87
87
  }
88
+ /**
89
+ * Whether the first player's voice may reach the second: first is the speaker, second the listener, and the order
90
+ * matters. canChat's rule over the voice choices: both accounts, no block between them, the listener hears voice, and
91
+ * the speaker's who_hears_my_voice takes the listener in (everyone; the same chat group; or a friend in it). A pass
92
+ * from before voice is heard as far as it's read. Zaisma's rooms apply it, and the witness rule on top (anyone under
93
+ * 18 is heard only where two independent players hear them too); use it on any voice your own server passes on.
94
+ */
95
+ export function canVoiceChat(first, second) {
96
+ mustBePasses(first, second, "canVoiceChat");
97
+ const voiceSide = (claims) => ({
98
+ ...claims,
99
+ who_reads_my_chat: claims.who_hears_my_voice ?? claims.who_reads_my_chat,
100
+ chat_reading_enabled: claims.voice_hearing_enabled ?? claims.chat_reading_enabled,
101
+ });
102
+ return canChat(voiceSide(first), voiceSide(second));
103
+ }
88
104
  // Plain class fields (no TypeScript-only syntax) so Node can run this file directly.
89
105
  export class PassError extends Error {
90
106
  code;
@@ -10,6 +10,11 @@ export interface RoomCallLimits {
10
10
  maximumLabelCount: number;
11
11
  /** A room message (room.sendToRoom, room.sendToEveryRoom) as JSON: ROOM_MESSAGE_LIMITS has it. */
12
12
  maximumRoomMessageSizeBytes: number;
13
+ /** Players in one room: ROOM_LIMITS has it. And voice's (room.setVoiceGroup, setHeardSpeakers, setHeardSpeakerCount): VOICE_ROOM_LIMITS has them. */
14
+ maximumPlayerCount: number;
15
+ defaultHeardSpeakerCount: number;
16
+ maximumHeardSpeakerCount: number;
17
+ maximumVoiceGroupNameCharacterCount: number;
13
18
  }
14
19
  /** The error a mistake in a room call throws: GameServerError, or the sandbox's copy of it. */
15
20
  export type RoomCallErrorClass = new (code: "bad_room_call" | "room_call_unavailable" | "room_call_limit", field: string, message: string, fix: string) => Error;
@@ -86,6 +91,10 @@ export interface RoomCallChecks {
86
91
  message: string;
87
92
  isKeptOut: boolean;
88
93
  };
94
+ checkPlayerId(playerId: unknown, call: string): string;
95
+ checkPlayerIds(playerIds: unknown, call: string): string[] | null;
96
+ checkVoiceGroupName(groupName: unknown, call: string): string | null;
97
+ checkHeardSpeakerCount(heardSpeakerCount: unknown, call: string): number;
89
98
  checkReserve(reserveOptions: unknown, playerIdsInRoom: readonly string[]): CheckedReserve;
90
99
  checkMoveTo(toRoomCode: unknown, moveOptions: unknown, playerIdsInRoom: readonly string[]): CheckedMove & {
91
100
  toRoomCode: string;
package/src/room-calls.js CHANGED
@@ -138,6 +138,26 @@ function roomCallChecksParts() {
138
138
  const given = closed(kickOptions, ["message", "keepOut"], "room.kick");
139
139
  return { playerId: readText(playerId, "playerId", "room.kick"), message: tidy(given.message, limits.maximumKickMessageCharacterCount), isKeptOut: given.keepOut === true };
140
140
  };
141
+ const checkPlayerId = (playerId, call) => readText(playerId, "playerId", call);
142
+ const checkPlayerIds = (playerIds, call) => {
143
+ if (playerIds === null)
144
+ return null;
145
+ if (!Array.isArray(playerIds) || playerIds.length > limits.maximumPlayerCount || playerIds.some((playerId) => typeof playerId !== "string" || !playerId))
146
+ throw mistake(call, `${call} needs a list of player IDs, up to ${limits.maximumPlayerCount}, or null.`, "Give player IDs from room.players, or null for everyone.");
147
+ return [...new Set(playerIds)];
148
+ };
149
+ const checkVoiceGroupName = (groupName, call) => {
150
+ if (groupName === null)
151
+ return null;
152
+ if (typeof groupName !== "string" || !groupName.length || groupName.length > limits.maximumVoiceGroupNameCharacterCount)
153
+ throw mistake(call, `${call} needs a group name of 1 to ${limits.maximumVoiceGroupNameCharacterCount} characters, or null.`, 'Give a name like "red", or null for no group.');
154
+ return groupName;
155
+ };
156
+ const checkHeardSpeakerCount = (heardSpeakerCount, call) => {
157
+ if (typeof heardSpeakerCount !== "number" || !Number.isInteger(heardSpeakerCount) || heardSpeakerCount < 1 || heardSpeakerCount > limits.maximumHeardSpeakerCount)
158
+ throw mistake(call, `${call} needs a whole number from 1 to ${limits.maximumHeardSpeakerCount}.`, `Give how many voices each player hears at once; ${limits.defaultHeardSpeakerCount} is the default.`);
159
+ return heardSpeakerCount;
160
+ };
141
161
  const checkReserve = (reserveOptions, playerIdsInRoom) => {
142
162
  const given = closed(reserveOptions, ["playerIds", "setupData", "isListed", "friendJoinsEnabled", "isKept", "name", "labels"], "room.reserve");
143
163
  const playerIds = [...new Set(Array.isArray(given.playerIds) ? given.playerIds : [])].filter((id) => typeof id === "string" && playerIdsInRoom.includes(id));
@@ -252,7 +272,7 @@ function roomCallChecksParts() {
252
272
  throw mistake(call, `${call} found no data file at ${JSON.stringify(path.slice(0, 200))}.`, `Put the file in the upload's zaisma-server/ folder. ${example} .js, .json and .wasm files there are code: import them instead.`);
253
273
  return found;
254
274
  };
255
- return { checkBroadcast, checkSend, checkBroadcastBytes, checkSendBytes, checkKick, checkReserve, checkMoveTo, checkSetInfo, checkEnd, checkRestoreToAt, checkKeptRoomRestoreId, keptRoomRestoreOf, keptRoomRestoreListOf, checkSendToRoom, checkSendToEveryRoom, checkRoomSelection, tidy, tidyRoomInfo, checkRoomData, readDataFile };
275
+ return { checkBroadcast, checkSend, checkBroadcastBytes, checkSendBytes, checkKick, checkPlayerId, checkPlayerIds, checkVoiceGroupName, checkHeardSpeakerCount, checkReserve, checkMoveTo, checkSetInfo, checkEnd, checkRestoreToAt, checkKeptRoomRestoreId, keptRoomRestoreOf, keptRoomRestoreListOf, checkSendToRoom, checkSendToEveryRoom, checkRoomSelection, tidy, tidyRoomInfo, checkRoomData, readDataFile };
256
276
  }
257
277
  return { checksFor };
258
278
  }
package/src/room.d.ts CHANGED
@@ -147,6 +147,20 @@ export interface Room {
147
147
  * of the match, and out of any room it reserves after. onLeave runs once the current handler is done.
148
148
  */
149
149
  kick(playerId: string, kickOptions?: KickOptions): void;
150
+ /**
151
+ * Put a player in a voice group, like a team or a squad's radio, or null for none: a player in a group hears and is
152
+ * heard only within it, and one in none hears and is heard by everyone voice allows. Names are 1 to 40 characters.
153
+ * It's the server's word on fairness: a changed game can't hear the other team. (Voice: room.voice in the game.)
154
+ */
155
+ setVoiceGroup(playerId: string, groupName: string | null): void;
156
+ /**
157
+ * Whom a player hears, for proximity voice or radios: only these speakers among those voice allows, or null for
158
+ * all of them. Smooth fading by distance is the game's own (room.voice.setSpeakerVolume); this is the server's
159
+ * backstop, so a changed game can't hear what's too far away.
160
+ */
161
+ setHeardSpeakers(listenerPlayerId: string, speakerPlayerIds: readonly string[] | null): void;
162
+ /** How many voices each player hears at once, 1 to 32 (16 unless you set it); past it, the loudest. */
163
+ setHeardSpeakerCount(heardSpeakerCount: number): void;
150
164
  /**
151
165
  * Send some of this room's players to another room of this game that already exists, like back to
152
166
  * their party's match or into the next area of an open world. The other room's canJoin decides with
@@ -1039,6 +1053,8 @@ export type ServerMessage = {
1039
1053
  probeIntervalSec: number | null;
1040
1054
  protocolVersionNumber: number;
1041
1055
  canChat: boolean;
1056
+ /** Whether this player can talk in voice (room.voice): an account whose voice reaches someone. Absent from an older runner: as canChat. */
1057
+ canTalk?: boolean;
1042
1058
  /** The room takes { type: "messages", data: [...] }: the SDK combines what a game sends at once only where this says so. */
1043
1059
  canCombineMessages: boolean;
1044
1060
  } | {
@@ -1188,7 +1204,7 @@ export type ClientMessage = {
1188
1204
  * the game became unavailable, its kept room was deleted, or no players were left for its spectators.
1189
1205
  */
1190
1206
  export type EndReason = "game" | "hosting_paused" | "game_server_stopped" | "game_unavailable" | "kept_room_deleted" | "no_players";
1191
- export type RoomErrorCode = "room_full" | "room_closed" | "ended" | "too_big" | "too_fast" | "bad_message" | "bad_pass" | "bad_player_token" | "no_hello" | "not_allowed" | "game_unavailable" | "busy" | "kept_out" | "refused" | "room_not_running" | "hosting_paused" | "rented_share_used" | "account_needed" | "game_not_open_to_player" | "blocked_player_here" | "other_version" | "spectators_full" | "spectator_cannot_send" | "already_playing" | "bad_origin" | "send_queue_full" | "chat_not_here" | "chat_not_allowed" | "chat_empty" | "chat_too_long" | "chat_too_fast";
1207
+ export type RoomErrorCode = "room_full" | "room_closed" | "ended" | "too_big" | "too_fast" | "bad_message" | "bad_pass" | "bad_player_token" | "no_hello" | "not_allowed" | "game_unavailable" | "busy" | "kept_out" | "refused" | "room_not_running" | "hosting_paused" | "rented_share_used" | "account_needed" | "game_not_open_to_player" | "blocked_player_here" | "other_version" | "spectators_full" | "spectator_cannot_send" | "already_playing" | "bad_origin" | "send_queue_full" | "chat_not_here" | "voice_not_here" | "chat_not_allowed" | "chat_empty" | "chat_too_long" | "chat_too_fast";
1192
1208
  export declare const ERROR_TEXT: Record<RoomErrorCode, string>;
1193
1209
  /** What players are told when Zaisma ends a match at room.endsAt. */
1194
1210
  export declare const HOSTING_PAUSED_END_MESSAGE = "This game's hosting is paused, so this match has ended. New rooms open again when the month resets or its developer adds credit.";
@@ -1216,6 +1232,10 @@ export interface SavedRoom extends RoomSettings {
1216
1232
  friendships?: [string, string][];
1217
1233
  /** Who each account player the room remembers may chat with, by player ID. */
1218
1234
  chatSettings?: Record<string, PlayerChatSettings>;
1235
+ /** The game server's voice rules (room.setVoiceGroup, setHeardSpeakers, setHeardSpeakerCount), by player ID. */
1236
+ voiceGroups?: Record<string, string>;
1237
+ heardSpeakers?: Record<string, string[]>;
1238
+ heardSpeakerCount?: number;
1219
1239
  /** When Zaisma will end the match (room.endsAt), once it's set. */
1220
1240
  endsAt?: string;
1221
1241
  /** Kept (room.setKept): it sleeps with its state when everyone leaves, instead of going a day later. */
@@ -1280,6 +1300,8 @@ export interface Transport {
1280
1300
  verifyReceipt?(receipt: string): Promise<ReceiptClaims>;
1281
1301
  /** room.applyVersionUpdate(): switch to the version coming now. Without it (your own server), it does nothing. */
1282
1302
  applyVersionUpdate?(): void;
1303
+ /** Who may hear whom may have changed (room.setVoiceGroup and the like, a block, a player's chat settings): Zaisma's rooms recompute it. Without it, nothing listens. */
1304
+ voiceRulesChanged?(): void;
1283
1305
  /** Whether a player's connection holds ROOM_TUNING.backedUpSizeBytes or more not yet sent. Without it, the room judges by its probes. */
1284
1306
  isBackedUp?(playerId: string): boolean;
1285
1307
  /** Where the room hands purchases over (onPurchase, onRefund). Without it, purchases never reach the room. */
@@ -1327,6 +1349,9 @@ export interface PlayerChatSettings {
1327
1349
  reading: ChatReach;
1328
1350
  chatGroupId: string | null;
1329
1351
  networkSeal: string | null;
1352
+ /** Who hears the player talk, and whose voices they hear (who_hears_my_voice, voice_hearing_enabled); a pass from before voice: as far as chat. */
1353
+ voiceSending?: ChatReach;
1354
+ voiceHearing?: ChatReach;
1330
1355
  }
1331
1356
  /**
1332
1357
  * The chat settings of a player your own server let in from outside Zaisma (outside_zaisma): they send to and read
@@ -1486,6 +1511,58 @@ export declare const ROOM_MESSAGE_DOORS: {
1486
1511
  };
1487
1512
  readonly chat: DoorContract;
1488
1513
  readonly block: DoorContract;
1514
+ readonly voice: {
1515
+ readonly takes: {
1516
+ readonly query: {};
1517
+ readonly body: {
1518
+ readonly kind: "json";
1519
+ readonly fields: {
1520
+ readonly type: DoorShape;
1521
+ readonly action: DoorShape;
1522
+ readonly offerSdp: DoorShape;
1523
+ readonly mid: DoorShape;
1524
+ readonly isSpeaking: DoorShape;
1525
+ readonly levelPct: DoorShape;
1526
+ readonly playerId: DoorShape;
1527
+ readonly isMuted: DoorShape;
1528
+ readonly answerSdp: DoorShape;
1529
+ };
1530
+ readonly required: readonly ["type", "action"];
1531
+ readonly maximumSizeBytes: 200000;
1532
+ };
1533
+ };
1534
+ readonly reaches: import("./doors.ts").DoorReach;
1535
+ readonly trusts: readonly import("./doors.ts").DoorTrust[];
1536
+ readonly answers: import("./doors.ts").DoorAnswer;
1537
+ readonly limit: import("./doors.ts").DoorLimit;
1538
+ readonly whoMayCall: import("./doors.ts").DoorCallerProvenByGuard;
1539
+ } | {
1540
+ readonly takes: {
1541
+ readonly query: {};
1542
+ readonly body: {
1543
+ readonly kind: "json";
1544
+ readonly fields: {
1545
+ readonly type: DoorShape;
1546
+ readonly action: DoorShape;
1547
+ readonly offerSdp: DoorShape;
1548
+ readonly mid: DoorShape;
1549
+ readonly isSpeaking: DoorShape;
1550
+ readonly levelPct: DoorShape;
1551
+ readonly playerId: DoorShape;
1552
+ readonly isMuted: DoorShape;
1553
+ readonly answerSdp: DoorShape;
1554
+ };
1555
+ readonly required: readonly ["type", "action"];
1556
+ readonly maximumSizeBytes: 200000;
1557
+ };
1558
+ };
1559
+ readonly reaches: import("./doors.ts").DoorReach;
1560
+ readonly trusts: readonly import("./doors.ts").DoorTrust[];
1561
+ readonly answers: import("./doors.ts").DoorAnswer;
1562
+ readonly limit: import("./doors.ts").DoorLimit;
1563
+ readonly whoMayCall: import("./doors.ts").DoorCallerProvenByFunction;
1564
+ readonly provenBy: import("./doors.ts").DoorProof;
1565
+ };
1489
1566
  readonly unblock: DoorContract;
1490
1567
  readonly friend_request: DoorContract;
1491
1568
  readonly "zaisma:purchase": {
@@ -1603,6 +1680,10 @@ export declare class RoomCore<S = any> {
1603
1680
  private readonly friendships;
1604
1681
  /** Who each account player may chat with, from their pass: never in Player, so games never see it. */
1605
1682
  private readonly chatSettings;
1683
+ /** The game server's voice rules (room.setVoiceGroup, setHeardSpeakers, setHeardSpeakerCount). */
1684
+ private readonly voiceGroups;
1685
+ private readonly heardSpeakers;
1686
+ private heardSpeakerCount;
1606
1687
  /** When each player sent their chat messages in the last CHAT_ROOM_LIMITS.chatWindowDurationMs. */
1607
1688
  private readonly chatSentAtMs;
1608
1689
  /** Each player's last chat messages, for Zaisma's filter to read pieces together: in memory only. */
@@ -1722,6 +1803,23 @@ export declare class RoomCore<S = any> {
1722
1803
  * a friend in it). Zaisma's chat check stops what would reach an under-18 account without witnesses.
1723
1804
  */
1724
1805
  private mayChat;
1806
+ /**
1807
+ * Whether one player's voice may reach another, mayChat's rule over the voice choices, speaker to listener: both in
1808
+ * the match, no block either way, the listener hears voice, and the speaker's choice takes the listener in. The voice
1809
+ * rules (groups, heard speakers) and Zaisma's witness rule apply on top (voicePulls).
1810
+ */
1811
+ mayVoice(speakerPlayerId: string, listenerPlayerId: string): boolean;
1812
+ /** Whether a player can talk at all: an account whose voice reaches someone. */
1813
+ canTalk(playerId: string): boolean;
1814
+ /** The game server's voice rules: groups, heard speakers and how many voices each player hears at once. */
1815
+ voiceRules(): {
1816
+ voiceGroupOf: Map<string, string | null>;
1817
+ heardSpeakerIdsOf: Map<string, readonly string[] | null>;
1818
+ heardSpeakerCount: number;
1819
+ };
1820
+ private setVoiceGroup;
1821
+ private setHeardSpeakers;
1822
+ private setHeardSpeakerCount;
1725
1823
  /** Who a player's chat may reach: the players in the match (or those of toPlayerIds in it), never spectators, kept only where they may chat. */
1726
1824
  chatReceivers(senderPlayerId: string, toPlayerIds?: readonly string[]): string[];
1727
1825
  /**
package/src/room.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * developer's code that holds the official game state. A *room* is one live match,
7
7
  * running one copy of the game server. Names follow docs/NAMING.md.
8
8
  */
9
- import { CHAT_CHECK_LIMITS, CHAT_ROOM_LIMITS } from "./chat.js";
9
+ import { CHAT_CHECK_LIMITS, CHAT_ROOM_LIMITS, VOICE_ROOM_LIMITS } from "./chat.js";
10
10
  import { DatabaseError } from "./database.js";
11
11
  import { answersJson, checkDoor, fieldsOf, gameData, listOf, orNothing, realNumber, schemaProblems, text as textUpTo, yesOrNo } from "./doors.js";
12
12
  import { isRoomCode, roomCode } from "./names.js";
@@ -276,7 +276,7 @@ export class GameServerError extends Error {
276
276
  }
277
277
  }
278
278
  /** The checks every room call goes through, here and in a game's sandbox (room-calls.ts). */
279
- const checks = roomCallChecks(GameServerError, { ...ROOM_LIMITS, ...ROOM_MESSAGE_LIMITS });
279
+ const checks = roomCallChecks(GameServerError, { ...ROOM_LIMITS, ...ROOM_MESSAGE_LIMITS, ...VOICE_ROOM_LIMITS });
280
280
  /** The error for an option a game server doesn't take, naming the ones it does. */
281
281
  export function unknownOptionError(field) {
282
282
  return new GameServerError("unknown_option", field, `${field} isn't a game server option.`, `A game server takes: ${GAME_SERVER_OPTIONS.join(", ")}.`);
@@ -377,6 +377,7 @@ export const ERROR_TEXT = {
377
377
  // The SDK's own: sends waiting while it reconnects ran past its queue.
378
378
  send_queue_full: "Up to 60 sends wait while reconnecting; older ones were dropped.",
379
379
  chat_not_here: "This room's server doesn't take chat.",
380
+ voice_not_here: "This room's server doesn't take voice.",
380
381
  chat_not_allowed: "You can't chat here.",
381
382
  chat_empty: "Type a message first.",
382
383
  chat_too_long: "That message is too long to send.",
@@ -485,14 +486,15 @@ export const OUTSIDE_ZAISMA_CHAT_SETTINGS = { sending: "everyone", reading: "eve
485
486
  export function chatSettingsOf(claims) {
486
487
  if (claims.kind !== "account")
487
488
  return null;
488
- return { ...chatReachOf(claims), chatGroupId: typeof claims.chat_group_id === "string" ? claims.chat_group_id : null, networkSeal: typeof claims.network_seal === "string" ? claims.network_seal : null };
489
+ const voice = chatReachOf({ ...claims, who_reads_my_chat: claims.who_hears_my_voice ?? claims.who_reads_my_chat, chat_reading_enabled: claims.voice_hearing_enabled ?? claims.chat_reading_enabled });
490
+ return { ...chatReachOf(claims), chatGroupId: typeof claims.chat_group_id === "string" ? claims.chat_group_id : null, networkSeal: typeof claims.network_seal === "string" ? claims.network_seal : null, voiceSending: voice.sending, voiceHearing: voice.reading };
489
491
  }
490
492
  /** Chat settings a room saved, in today's shape: one saved before who_reads_my_chat reads as v1's two-way setting did. */
491
493
  function savedChatSettings(saved) {
492
494
  const chatGroupId = typeof saved.chatGroupId === "string" ? saved.chatGroupId : null;
493
495
  const networkSeal = typeof saved.networkSeal === "string" ? saved.networkSeal : null;
494
496
  if (saved.sending !== undefined && saved.reading !== undefined)
495
- return { sending: saved.sending, reading: saved.reading, chatGroupId, networkSeal };
497
+ return { sending: saved.sending, reading: saved.reading, chatGroupId, networkSeal, ...(saved.voiceSending && saved.voiceHearing ? { voiceSending: saved.voiceSending, voiceHearing: saved.voiceHearing } : {}) };
496
498
  const reach = chatGroupId === OUTSIDE_ZAISMA_CHAT_SETTINGS.chatGroupId ? "everyone" : saved.whoCanChat === "friends" ? "friends" : saved.whoCanChat === "anyone" ? "my_age_band" : "nobody";
497
499
  return { sending: reach, reading: reach, chatGroupId, networkSeal };
498
500
  }
@@ -595,7 +597,7 @@ const wirePlayers = { type: "array", items: looseObject };
595
597
  const WIRE_DATA = {};
596
598
  export const ROOM_FRAME = {
597
599
  anyOf: [
598
- frameOf("welcome", { me: looseObject, isSpectator: wireYesOrNo, players: wirePlayers, room: looseObject, spectatorCount: wireNumber, hostPlayerId: wireNullable("string"), awayChecks: looseObject, endsAt: wireNullable("string"), probeIntervalSec: wireNullable("number"), protocolVersionNumber: wireNumber, canChat: wireYesOrNo, canCombineMessages: wireYesOrNo }),
600
+ frameOf("welcome", { me: looseObject, isSpectator: wireYesOrNo, players: wirePlayers, room: looseObject, spectatorCount: wireNumber, hostPlayerId: wireNullable("string"), awayChecks: looseObject, endsAt: wireNullable("string"), probeIntervalSec: wireNullable("number"), protocolVersionNumber: wireNumber, canChat: wireYesOrNo, canCombineMessages: wireYesOrNo }, { canTalk: wireYesOrNo }),
599
601
  frameOf("probe", { probeNumber: wireNumber, serverTimeMs: wireNumber, pingDurationMs: wireNullable("number") }),
600
602
  frameOf("ending", { endsAt: wireText }),
601
603
  frameOf("ending_cancelled"),
@@ -612,6 +614,8 @@ export const ROOM_FRAME = {
612
614
  frameOf("friend_request"),
613
615
  frameOf("chat", { fromPlayerId: wireText, text: wireText, hasSwearing: wireYesOrNo, hasSlur: wireYesOrNo, sentAt: wireText }),
614
616
  frameOf("chat_sent", { chatNumber: wireNumber, sentAt: wireText }),
617
+ // Voice, from Zaisma's rooms (apps/rooms/src/voice.ts): joined, offer, tracks or error.
618
+ frameOf("voice", { action: wireText }, { answerSdp: wireNullable("string"), offerSdp: wireText, tracks: { type: "array", items: looseObject }, code: wireText }),
615
619
  frameOf("chat_stopped", { chatNumber: wireNumber, reason: wireText, message: wireText }),
616
620
  frameOf("error", { code: wireText, message: wireText }, { versionId: wireText, chatNumber: wireNumber }),
617
621
  frameOf("ended", { message: wireText, endReason: wireText }),
@@ -626,6 +630,8 @@ const ASKED_ROOM = fieldsOf({
626
630
  labels: gameData(4 * 1024),
627
631
  });
628
632
  const PLAYER_ID_SHAPE = textUpTo(80);
633
+ /** A voice message's most: an offer or answer for a session pulling many voices. */
634
+ const VOICE_MESSAGE_MAXIMUM_SIZE_BYTES = 200_000;
629
635
  const IDLE_FIELDS = { idleTimeoutSec: realNumber(0, Number.MAX_SAFE_INTEGER), idleCheckEnabled: yesOrNo };
630
636
  /** A connection's limit is a room's message bucket, which takes a token per player before any of these runs. */
631
637
  const roomMessage = (whoMayCall, fields = {}, required = []) => ({
@@ -694,6 +700,12 @@ export const ROOM_MESSAGE_DOORS = {
694
700
  },
695
701
  chat: roomMessage("room_player", { chatNumber: realNumber(0, Number.MAX_SAFE_INTEGER), text: textUpTo(ROOM_LIMITS.maximumGameMessageSizeBytes), toPlayerIds: listOf(PLAYER_ID_SHAPE, 200) }, ["text"]),
696
702
  block: roomMessage("room_player", { playerId: PLAYER_ID_SHAPE }, ["playerId"]),
703
+ // Voice (room.voice): the host's to take before receive, like chat, in Zaisma's rooms (apps/rooms/src/voice.ts). A session's
704
+ // descriptions grow with each voice pulled, so its door takes more than a game's message.
705
+ voice: {
706
+ ...roomMessage("room_player", { action: textUpTo(20), offerSdp: textUpTo(VOICE_MESSAGE_MAXIMUM_SIZE_BYTES), mid: textUpTo(8), isSpeaking: yesOrNo, levelPct: realNumber(0, 100), playerId: PLAYER_ID_SHAPE, isMuted: yesOrNo, answerSdp: textUpTo(VOICE_MESSAGE_MAXIMUM_SIZE_BYTES) }, ["action"]),
707
+ takes: { query: {}, body: { kind: "json", fields: { type: textUpTo(40), action: textUpTo(20), offerSdp: textUpTo(VOICE_MESSAGE_MAXIMUM_SIZE_BYTES), mid: textUpTo(8), isSpeaking: yesOrNo, levelPct: realNumber(0, 100), playerId: PLAYER_ID_SHAPE, isMuted: yesOrNo, answerSdp: textUpTo(VOICE_MESSAGE_MAXIMUM_SIZE_BYTES) }, required: ["type", "action"], maximumSizeBytes: VOICE_MESSAGE_MAXIMUM_SIZE_BYTES } },
708
+ },
697
709
  unblock: roomMessage("room_player", { playerId: PLAYER_ID_SHAPE }, ["playerId"]),
698
710
  friend_request: roomMessage("room_player", { playerId: PLAYER_ID_SHAPE }, ["playerId"]),
699
711
  "zaisma:purchase": {
@@ -830,6 +842,10 @@ export class RoomCore {
830
842
  friendships = new Set();
831
843
  /** Who each account player may chat with, from their pass: never in Player, so games never see it. */
832
844
  chatSettings = new Map();
845
+ /** The game server's voice rules (room.setVoiceGroup, setHeardSpeakers, setHeardSpeakerCount). */
846
+ voiceGroups = new Map();
847
+ heardSpeakers = new Map();
848
+ heardSpeakerCount = VOICE_ROOM_LIMITS.defaultHeardSpeakerCount;
833
849
  /** When each player sent their chat messages in the last CHAT_ROOM_LIMITS.chatWindowDurationMs. */
834
850
  chatSentAtMs = new Map();
835
851
  /** Each player's last chat messages, for Zaisma's filter to read pieces together: in memory only. */
@@ -965,6 +981,14 @@ export class RoomCore {
965
981
  this.friendships.add(pairKey(first, second));
966
982
  for (const [id, settings] of Object.entries(saved.chatSettings ?? {}))
967
983
  this.chatSettings.set(id, savedChatSettings(settings));
984
+ for (const [id, groupName] of Object.entries(saved.voiceGroups ?? {}))
985
+ if (typeof groupName === "string")
986
+ this.voiceGroups.set(id, groupName);
987
+ for (const [id, speakerIds] of Object.entries(saved.heardSpeakers ?? {}))
988
+ if (Array.isArray(speakerIds))
989
+ this.heardSpeakers.set(id, speakerIds.filter((speakerId) => typeof speakerId === "string"));
990
+ if (typeof saved.heardSpeakerCount === "number")
991
+ this.heardSpeakerCount = saved.heardSpeakerCount;
968
992
  }
969
993
  else if (startOptions.start) {
970
994
  const start = startOptions.start;
@@ -1069,6 +1093,9 @@ export class RoomCore {
1069
1093
  const checked = checks.checkKick(playerId, kickOptions);
1070
1094
  this.kick(checked.playerId, { message: checked.message, keepOut: checked.isKeptOut });
1071
1095
  },
1096
+ setVoiceGroup: (playerId, groupName) => this.setVoiceGroup(checks.checkPlayerId(playerId, "room.setVoiceGroup"), checks.checkVoiceGroupName(groupName, "room.setVoiceGroup")),
1097
+ setHeardSpeakers: (listenerPlayerId, speakerPlayerIds) => this.setHeardSpeakers(checks.checkPlayerId(listenerPlayerId, "room.setHeardSpeakers"), checks.checkPlayerIds(speakerPlayerIds, "room.setHeardSpeakers")),
1098
+ setHeardSpeakerCount: (heardSpeakerCount) => this.setHeardSpeakerCount(checks.checkHeardSpeakerCount(heardSpeakerCount, "room.setHeardSpeakerCount")),
1072
1099
  moveTo: (toRoomCode, moveOptions) => this.moveTo(toRoomCode, moveOptions),
1073
1100
  sendToRoom: (toRoomCode, message) => {
1074
1101
  const reach = this.roomReachFor("room.sendToRoom");
@@ -1149,6 +1176,9 @@ export class RoomCore {
1149
1176
  ...(this.isKept ? { isKept: true } : {}),
1150
1177
  ...this.savedBlocks(),
1151
1178
  ...(this.chatSettings.size ? { chatSettings: Object.fromEntries([...this.chatSettings].filter(([id]) => this.known.has(id))) } : {}),
1179
+ ...(this.voiceGroups.size ? { voiceGroups: Object.fromEntries([...this.voiceGroups].filter(([id]) => this.known.has(id))) } : {}),
1180
+ ...(this.heardSpeakers.size ? { heardSpeakers: Object.fromEntries([...this.heardSpeakers].filter(([id]) => this.known.has(id)).map(([id, speakerIds]) => [id, [...speakerIds]])) } : {}),
1181
+ ...(this.heardSpeakerCount !== VOICE_ROOM_LIMITS.defaultHeardSpeakerCount ? { heardSpeakerCount: this.heardSpeakerCount } : {}),
1152
1182
  };
1153
1183
  }
1154
1184
  /** The blocks worth keeping while the room sleeps: those between players it still remembers. */
@@ -1190,10 +1220,11 @@ export class RoomCore {
1190
1220
  /** A player's chat settings from their pass, before join: null for a guest, who chats with nobody. */
1191
1221
  setChatSettings(playerId, settings) {
1192
1222
  if (settings)
1193
- this.chatSettings.set(playerId, { sending: settings.sending, reading: settings.reading, chatGroupId: settings.chatGroupId, networkSeal: settings.networkSeal });
1223
+ this.chatSettings.set(playerId, { sending: settings.sending, reading: settings.reading, chatGroupId: settings.chatGroupId, networkSeal: settings.networkSeal, ...(settings.voiceSending && settings.voiceHearing ? { voiceSending: settings.voiceSending, voiceHearing: settings.voiceHearing } : {}) });
1194
1224
  else if (!this.chatSettings.delete(playerId))
1195
1225
  return;
1196
1226
  this.dirty = true;
1227
+ this.transport.voiceRulesChanged?.();
1197
1228
  }
1198
1229
  /** Whether a player can send chat at all: an account whose chat isn't stopped, with a chat group. */
1199
1230
  canChat(playerId) {
@@ -1219,6 +1250,55 @@ export class RoomCore {
1219
1250
  const other = { isSameChatGroup: sender.chatGroupId === receiver.chatGroupId, isFriend: this.areFriends(senderPlayerId, receiverPlayerId) };
1220
1251
  return isWithinChatReach(sender.sending, other) && isWithinChatReach(receiver.reading, other);
1221
1252
  }
1253
+ /**
1254
+ * Whether one player's voice may reach another, mayChat's rule over the voice choices, speaker to listener: both in
1255
+ * the match, no block either way, the listener hears voice, and the speaker's choice takes the listener in. The voice
1256
+ * rules (groups, heard speakers) and Zaisma's witness rule apply on top (voicePulls).
1257
+ */
1258
+ mayVoice(speakerPlayerId, listenerPlayerId) {
1259
+ if (speakerPlayerId === listenerPlayerId || !this.players.has(speakerPlayerId) || !this.players.has(listenerPlayerId) || this.hasBlockBetween(speakerPlayerId, listenerPlayerId))
1260
+ return false;
1261
+ const speaker = this.chatSettings.get(speakerPlayerId);
1262
+ const listener = this.chatSettings.get(listenerPlayerId);
1263
+ if (!speaker || !listener || speaker.chatGroupId === null || listener.chatGroupId === null)
1264
+ return false;
1265
+ const other = { isSameChatGroup: speaker.chatGroupId === listener.chatGroupId, isFriend: this.areFriends(speakerPlayerId, listenerPlayerId) };
1266
+ return isWithinChatReach(speaker.voiceSending ?? speaker.sending, other) && isWithinChatReach(listener.voiceHearing ?? listener.reading, other);
1267
+ }
1268
+ /** Whether a player can talk at all: an account whose voice reaches someone. */
1269
+ canTalk(playerId) {
1270
+ const settings = this.chatSettings.get(playerId);
1271
+ return settings !== undefined && (settings.voiceSending ?? settings.sending) !== "nobody" && settings.chatGroupId !== null;
1272
+ }
1273
+ /** The game server's voice rules: groups, heard speakers and how many voices each player hears at once. */
1274
+ voiceRules() {
1275
+ return { voiceGroupOf: new Map(this.voiceGroups), heardSpeakerIdsOf: new Map(this.heardSpeakers), heardSpeakerCount: this.heardSpeakerCount };
1276
+ }
1277
+ setVoiceGroup(playerId, groupName) {
1278
+ if (groupName === null ? !this.voiceGroups.delete(playerId) : this.voiceGroups.get(playerId) === groupName)
1279
+ return;
1280
+ if (groupName !== null)
1281
+ this.voiceGroups.set(playerId, groupName);
1282
+ this.dirty = true;
1283
+ this.transport.voiceRulesChanged?.();
1284
+ }
1285
+ setHeardSpeakers(listenerPlayerId, speakerPlayerIds) {
1286
+ if (speakerPlayerIds === null) {
1287
+ if (!this.heardSpeakers.delete(listenerPlayerId))
1288
+ return;
1289
+ }
1290
+ else
1291
+ this.heardSpeakers.set(listenerPlayerId, [...new Set(speakerPlayerIds)]);
1292
+ this.dirty = true;
1293
+ this.transport.voiceRulesChanged?.();
1294
+ }
1295
+ setHeardSpeakerCount(heardSpeakerCount) {
1296
+ if (this.heardSpeakerCount === heardSpeakerCount)
1297
+ return;
1298
+ this.heardSpeakerCount = heardSpeakerCount;
1299
+ this.dirty = true;
1300
+ this.transport.voiceRulesChanged?.();
1301
+ }
1222
1302
  /** Who a player's chat may reach: the players in the match (or those of toPlayerIds in it), never spectators, kept only where they may chat. */
1223
1303
  chatReceivers(senderPlayerId, toPlayerIds) {
1224
1304
  const asked = toPlayerIds ? [...new Set(toPlayerIds)].filter((id) => this.players.has(id)) : [...this.players.keys()];
@@ -1359,6 +1439,7 @@ export class RoomCore {
1359
1439
  this.dirty = true;
1360
1440
  this.listingChanged = true;
1361
1441
  this.pairChangeCount++;
1442
+ this.transport.voiceRulesChanged?.();
1362
1443
  }
1363
1444
  /** The players in the room this one has a block with, either way. */
1364
1445
  blockedWith(playerId) {
@@ -1391,6 +1472,7 @@ export class RoomCore {
1391
1472
  this.dirty = true;
1392
1473
  this.listingChanged = true;
1393
1474
  this.tellBlocks();
1475
+ this.transport.voiceRulesChanged?.();
1394
1476
  return null;
1395
1477
  }
1396
1478
  /**
@@ -1666,7 +1748,7 @@ export class RoomCore {
1666
1748
  this.remember(player.id);
1667
1749
  this.presence.set(player.id, newPresence(this.now(), joinOptions.clientIdle === undefined ? (this.presence.get(player.id)?.clientIdle ?? {}) : clientIdle(joinOptions.clientIdle)));
1668
1750
  const probeIntervalSec = this.ticking ? ROOM_TUNING.probeIntervalSec : null;
1669
- this.sendText(player.id, JSON.stringify({ type: "welcome", me: shownPlayer(player), isSpectator: false, players: this.list(), room: this.settings(), spectatorCount: this.spectators.size, hostPlayerId: this.hostPlayerId, awayChecks: this.checks(player.id), endsAt: this.endsAt, probeIntervalSec, protocolVersionNumber: PROTOCOL_VERSION_NUMBER, canChat: this.canChat(player.id), canCombineMessages: true }));
1751
+ this.sendText(player.id, JSON.stringify({ type: "welcome", me: shownPlayer(player), isSpectator: false, players: this.list(), room: this.settings(), spectatorCount: this.spectators.size, hostPlayerId: this.hostPlayerId, awayChecks: this.checks(player.id), endsAt: this.endsAt, probeIntervalSec, protocolVersionNumber: PROTOCOL_VERSION_NUMBER, canChat: this.canChat(player.id), canTalk: this.canTalk(player.id), canCombineMessages: true }));
1670
1752
  // Every room gets a first ping and clock sample right away, ticking or not.
1671
1753
  this.probe(player.id);
1672
1754
  // A new connection starts with nothing of the state: a full copy comes with the next round.
@@ -1705,7 +1787,7 @@ export class RoomCore {
1705
1787
  this.spectators.set(spectator.id, spectator);
1706
1788
  this.presence.set(spectator.id, newPresence(this.now(), {}));
1707
1789
  const probeIntervalSec = this.ticking ? ROOM_TUNING.probeIntervalSec : null;
1708
- this.sendText(spectator.id, JSON.stringify({ type: "welcome", me: shownPlayer(spectator), isSpectator: true, players: this.list(), room: this.settings(), spectatorCount: this.spectators.size, hostPlayerId: this.hostPlayerId, awayChecks: { idleTimeoutSec: null, hiddenTimeoutSec: null }, endsAt: this.endsAt, probeIntervalSec, protocolVersionNumber: PROTOCOL_VERSION_NUMBER, canChat: false, canCombineMessages: true }));
1790
+ this.sendText(spectator.id, JSON.stringify({ type: "welcome", me: shownPlayer(spectator), isSpectator: true, players: this.list(), room: this.settings(), spectatorCount: this.spectators.size, hostPlayerId: this.hostPlayerId, awayChecks: { idleTimeoutSec: null, hiddenTimeoutSec: null }, endsAt: this.endsAt, probeIntervalSec, protocolVersionNumber: PROTOCOL_VERSION_NUMBER, canChat: false, canTalk: false, canCombineMessages: true }));
1709
1791
  this.probe(spectator.id);
1710
1792
  // A new connection starts with nothing of the state: a full copy comes with the next round.
1711
1793
  if (this.server.stateSyncEnabled) {
@@ -2073,6 +2155,9 @@ export class RoomCore {
2073
2155
  case "chat":
2074
2156
  // The room's host takes chat before it gets here (readChatMessage); a host that doesn't, doesn't take chat.
2075
2157
  return "chat_not_here";
2158
+ case "voice":
2159
+ // Zaisma's rooms take voice before it gets here (readVoiceMessage); elsewhere there's no voice in the room itself.
2160
+ return "voice_not_here";
2076
2161
  case "zaisma:purchase":
2077
2162
  this.purchaseTold(playerId, message);
2078
2163
  return null;
@@ -0,0 +1,56 @@
1
+ import { type PassClaims } from "./pass.ts";
2
+ /**
3
+ * Voice for a game's own server (PL39). Zaisma's rooms decide who hears whom in their voice themselves; a game on its own
4
+ * server joins its players to a voice channel on Zaisma with a ticket its server signs with the game's ticket secret
5
+ * (create_ticket_secret): which player, which channel, and the server's rules for them (their voice group, whom they
6
+ * hear, how many at once). The channel applies Zaisma's rules on top: who each player lets hear them, blocks, and anyone
7
+ * under 18 only where two independent players hear them too. A new ticket, sent on the open channel, updates the rules,
8
+ * so a team switch needs no reconnect.
9
+ */
10
+ /** What a voice ticket says, signed: kept short, so it rides in any message. */
11
+ export interface VoiceTicketClaims {
12
+ /** voice: a ticket for something else signed with the same secret (a channel's, later) is never a voice ticket. */
13
+ ticket_kind: "voice";
14
+ /** The game's slug, as the player's pass names it. */
15
+ aud: string;
16
+ /** The player, as their pass names them. */
17
+ sub: string;
18
+ channel_name: string;
19
+ /** The player's voice group (a team), or null for none: a player in a group hears and is heard only within it. */
20
+ voice_group_name: string | null;
21
+ /** Whom the player hears, or null for everyone voice allows (proximity: only those near). */
22
+ heard_speaker_ids: string[] | null;
23
+ /** Voices the player hears at once, 1 to 32. */
24
+ heard_speaker_count: number;
25
+ /** When the ticket stops working, in seconds since 1970: it's for joining or updating, not for staying. */
26
+ exp: number;
27
+ }
28
+ /** What voiceTicket takes beside the player and channel: the server's rules for this player now. */
29
+ export interface VoiceTicketOptions {
30
+ voiceGroupName?: string | null;
31
+ heardSpeakerPlayerIds?: readonly string[] | null;
32
+ heardSpeakerCount?: number;
33
+ }
34
+ /** A channel's name: 1 to 40 of a-z, 0-9, -, _ and :. */
35
+ export declare const VOICE_CHANNEL_NAME_PATTERN: RegExp;
36
+ /** Why a voice ticket was refused. */
37
+ export type VoiceTicketErrorCode = "malformed" | "bad_signature" | "expired" | "wrong_game" | "wrong_player" | "wrong_channel" | "wrong_kind";
38
+ export declare class VoiceTicketError extends Error {
39
+ readonly code: VoiceTicketErrorCode;
40
+ constructor(code: VoiceTicketErrorCode);
41
+ }
42
+ /**
43
+ * Sign a voice ticket for a player whose pass your server checked (verifyPass), for a channel your server names, like
44
+ * "match-12" or "team-red-12". Hand it to the player's game, which joins with room.voice.join({ ticket }), and send a new
45
+ * one when their team or range changes (room.voice.updateTicket). It lasts 5 minutes: enough to join or update.
46
+ */
47
+ export declare function voiceTicket(playerPass: PassClaims, channelName: string, ticketSecret: string, voiceTicketOptions?: VoiceTicketOptions): Promise<string>;
48
+ /** The channel a ticket names, unchecked: for the SDK to know where to connect. Null for anything else. */
49
+ export declare function voiceTicketChannelName(ticket: unknown): string | null;
50
+ /** Check a voice ticket (Zaisma's voice channels do): its signature with the game's ticket secret, then what it's for. */
51
+ export declare function verifyVoiceTicket(ticket: unknown, ticketSecret: string, expectations: {
52
+ gameSlug: string;
53
+ playerId: string;
54
+ channelName: string;
55
+ nowSec?: number;
56
+ }): Promise<VoiceTicketClaims>;