@hadoku/rooms-server 0.45.63 → 0.45.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -22,6 +22,7 @@ export * from './emit.js';
22
22
  export * from './gc.js';
23
23
  export * from './rateLimiter.js';
24
24
  export * from './presence.js';
25
+ export * from './room-presence.js';
25
26
  export * from './session-claims.js';
26
27
  export * from './book/index.js';
27
28
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AACpC,cAAc,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,kBAAkB,CAAC;AACjC,cAAc,eAAe,CAAC;AAC9B,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC;AACpC,cAAc,iBAAiB,CAAC"}
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ export * from './emit.js';
22
22
  export * from './gc.js';
23
23
  export * from './rateLimiter.js';
24
24
  export * from './presence.js';
25
+ export * from './room-presence.js';
25
26
  export * from './session-claims.js';
26
27
  export * from './book/index.js';
27
28
  // NOT `export * from '@wolffm/rooms-protocol'`. Re-exporting it would give
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @wolffm/rooms-server/room — a room served by the app that owns it:
3
+ * `serveRoom` puts presence, roster, identity and chat for `RoomChrome`'s
4
+ * `roomOrigin` on the app's own socket.io server, from the app's own
5
+ * `PresenceTracker`.
6
+ *
7
+ * A subpath like `../chat`, which it builds on (chat history reaches
8
+ * `node:fs`); the presence half it shares with watchparty's own room socket
9
+ * (`createRoomPresence`, `presenceUser`) is on the main entry.
10
+ */
11
+ export * from './serve-room.js';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/room/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,cAAc,iBAAiB,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @wolffm/rooms-server/room — a room served by the app that owns it:
3
+ * `serveRoom` puts presence, roster, identity and chat for `RoomChrome`'s
4
+ * `roomOrigin` on the app's own socket.io server, from the app's own
5
+ * `PresenceTracker`.
6
+ *
7
+ * A subpath like `../chat`, which it builds on (chat history reaches
8
+ * `node:fs`); the presence half it shares with watchparty's own room socket
9
+ * (`createRoomPresence`, `presenceUser`) is on the main entry.
10
+ */
11
+ export * from './serve-room.js';
@@ -0,0 +1,163 @@
1
+ /**
2
+ * A room, served by the app that owns it: everything `RoomChrome` needs —
3
+ * join, presence (roster), identity and chat — on a socket.io namespace of the
4
+ * app's OWN server. With `RoomChrome`'s `roomOrigin` pointed here, the chrome
5
+ * sends nothing to watchparty: the room exists only where the app is.
6
+ *
7
+ * THE WIRE IS WATCHPARTY'S ROOM SOCKET, UNCHANGED, so the chrome's client is
8
+ * one piece of code whichever server it talks to:
9
+ *
10
+ * client → `join` (watchparty's join payload), `identity_update`
11
+ * (`{ name?, sprite?, avatar? }`), `chat_send`, `time_ping`,
12
+ * `presence_ping`; anything else is ignored (but counts as traffic)
13
+ * server → `snapshot` (the join ack: a room with nothing playing),
14
+ * `presence { users }` (`presenceUser` rows), `chat_history`,
15
+ * `chat_broadcast`, `time_pong`, `error { code, message }`
16
+ *
17
+ * PRESENCE IS THE APP'S TRACKER. `presence` is the app's own
18
+ * `PresenceTracker` — the instance its seats already listen to — never one
19
+ * made here: a room has one answer to "who is here". Each admitted socket is a
20
+ * connection of the admission's `key`; any traffic is its heartbeat (the
21
+ * chrome pings every 5s); a socket silent for the tracker's `idleMs` is closed
22
+ * from here; the roster is the admitted sockets the tracker still holds live,
23
+ * re-sent on every change, including changes the APP makes to the tracker.
24
+ * `joined` / `offline` / `left` (after the grace) are the tracker's own events:
25
+ * subscribe on it (`tracker.on`) to release a seat, as before.
26
+ *
27
+ * Identity, names and characters are the app's (`admit` returns who the
28
+ * connection is; `identity` decides a change). Nothing about a person is
29
+ * stored here.
30
+ */
31
+ import type { Namespace, Server as SocketIOServer, Socket } from 'socket.io';
32
+ import type { PresenceTracker } from '../presence.js';
33
+ import { type RoomPresenceMember } from '../room-presence.js';
34
+ import { type ChatBroadcastPayload, type ChatSender, type RoomChat, type RoomChatMessage, type RoomChatOptions } from '../chat/room-chat.js';
35
+ /** Who a connection is, as the room shows it right now. */
36
+ export interface RoomMember extends Omit<RoomPresenceMember, 'clientId' | 'name'> {
37
+ name: string;
38
+ /** The account userId, if any (stored on a chat line, never shown). */
39
+ authorId?: string;
40
+ }
41
+ /** A socket admitted to one room. */
42
+ export interface RoomAdmission<K extends string = string> {
43
+ roomId: string;
44
+ /** The PERSON this connection belongs to, as the app's tracker keys people
45
+ * (a participant id, a member id). Two tabs of one person share it. If one
46
+ * tracker spans several rooms, put the room in the key. */
47
+ key: K;
48
+ /** The ACCOUNT (registry userId) behind the connection, when signed in. With
49
+ * the `account` option, its name and picture come from that one resolver
50
+ * and follow the account live, across every room and tab. */
51
+ accountId?: string;
52
+ /** Who this connection is right now — re-read for every roster and every
53
+ * chat line, so the app's own renames show at once (call `refresh`). */
54
+ member: () => RoomMember;
55
+ }
56
+ /** What `identity_update` asked for, validated. */
57
+ export interface IdentityRequest {
58
+ name?: string;
59
+ sprite?: string;
60
+ /** The person changed their picture: re-read it. */
61
+ avatar?: boolean;
62
+ }
63
+ /**
64
+ * Who an account is, as the fleet says: its registry name and its picture.
65
+ * Fields left out fall back to `member()`.
66
+ */
67
+ export interface AccountIdentity {
68
+ name?: string;
69
+ avatarUrl?: string;
70
+ avatarSource?: string;
71
+ cosmetics?: unknown;
72
+ }
73
+ /** The app's answer to an identity change: what to apply, or a refusal. */
74
+ export type IdentityDecision = {
75
+ name?: string;
76
+ sprite?: string | null;
77
+ } | {
78
+ error: {
79
+ code: string;
80
+ message: string;
81
+ };
82
+ };
83
+ export interface ServeRoomOptions<K extends string, M extends RoomChatMessage> extends RoomChatOptions<M> {
84
+ /** Default `/room`. */
85
+ namespace?: string;
86
+ /** The app's tracker (see the file header). */
87
+ presence: PresenceTracker<K>;
88
+ /**
89
+ * The app's membership rule: may this socket be in this room? `join` is the
90
+ * client's join payload (`room_key`, `name` and `sprite` it would like,
91
+ * `device_id`, `tab_id`, …). Return null to refuse; the socket then gets
92
+ * `error { code: 'auth/forbidden' }` and nothing of the room. Authenticate
93
+ * from the socket's handshake (the edge's `X-User-Key`), never from the
94
+ * payload alone.
95
+ */
96
+ admit: (socket: Socket, join: {
97
+ room_key: string;
98
+ } & Record<string, unknown>) => Promise<RoomAdmission<K> | null> | RoomAdmission<K> | null;
99
+ /**
100
+ * Decide an `identity_update`. Default: a name is taken unless the member's
101
+ * name is their registry name; a character is taken unless another
102
+ * connection in the room wears it (`conflict` / `sprite_taken`, which the
103
+ * chrome answers by picking another). What is returned is applied over
104
+ * `member()` for this connection.
105
+ */
106
+ identity?: (socket: Socket, request: IdentityRequest, ctx: {
107
+ roomId: string;
108
+ member: RoomMember;
109
+ others: RoomMember[];
110
+ }) => Promise<IdentityDecision> | IdentityDecision;
111
+ /**
112
+ * THE identity resolver: who `accountId` is (registry name from whoami,
113
+ * picture from prefs-api), or null when unknown. Called once per account and
114
+ * cached; called again with `fresh: true` when the person says they changed
115
+ * (the chrome sends `identity_update` with a name, or `avatar: true`, on the
116
+ * fleet's `hadoku:name` / `hadoku:avatar` events) or when the app calls
117
+ * `refreshAccount`. The answer is pushed to EVERY connection of the account
118
+ * in every room this server serves, through the room's own presence: no
119
+ * app keeps a stale copy. A resolved name is the person's name: a client
120
+ * cannot rename over it.
121
+ */
122
+ account?: (accountId: string, ctx: {
123
+ fresh: boolean;
124
+ socket: Socket;
125
+ }) => Promise<AccountIdentity | null> | AccountIdentity | null;
126
+ /** How many stored lines a joiner gets. Default 100. */
127
+ historyJoinLimit?: number;
128
+ /** Name stored chat lines for a reader. Default: a live member, else "Someone". */
129
+ present?: (roomId: string, messages: M[], members: ChatSender[]) => Promise<Array<{
130
+ name: string;
131
+ sprite: string | null;
132
+ }>> | Array<{
133
+ name: string;
134
+ sprite: string | null;
135
+ }>;
136
+ onEvent?: (level: 'info' | 'warn', event: string, fields: Record<string, unknown>) => void;
137
+ }
138
+ export interface ServedRoom<K extends string, M extends RoomChatMessage> {
139
+ namespace: Namespace;
140
+ chat: RoomChat<M>;
141
+ /** Rooms with at least one live connection here. */
142
+ rooms(): string[];
143
+ /** The roster of `roomId`, as `presence` sends it. */
144
+ members(roomId: string): Array<RoomMember & {
145
+ clientId: string;
146
+ }>;
147
+ /** Re-send `roomId`'s roster (after the app changed who someone is). */
148
+ refresh(roomId: string): void;
149
+ /** Broadcast a chat line the app composed (a system line). */
150
+ broadcast(roomId: string, payload: ChatBroadcastPayload): void;
151
+ /** Re-resolve an account fresh and push it to every room it is in (any other change signal). */
152
+ refreshAccount(accountId: string): Promise<void>;
153
+ /** The account's identity as last resolved, if any. */
154
+ accountIdentity(accountId: string): AccountIdentity | undefined;
155
+ /** Stop listening to the tracker and close every socket of the namespace. */
156
+ close(): void;
157
+ }
158
+ /** The socket.io room a served room's sockets are in. */
159
+ export declare function roomChannel(roomId: string): string;
160
+ /** Validate an `identity_update` payload (watchparty's `IdentityUpdate` shape), or null. */
161
+ export declare function parseIdentityRequest(payload: unknown): IdentityRequest | null;
162
+ export declare function serveRoom<K extends string, M extends RoomChatMessage>(io: SocketIOServer, opts: ServeRoomOptions<K, M>): ServedRoom<K, M>;
163
+ //# sourceMappingURL=serve-room.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve-room.d.ts","sourceRoot":"","sources":["../../src/room/serve-room.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,cAAc,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAC7E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAoC,KAAK,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAChG,OAAO,EAEL,KAAK,oBAAoB,EAAE,KAAK,UAAU,EAAE,KAAK,QAAQ,EAAE,KAAK,eAAe,EAAE,KAAK,eAAe,EACtG,MAAM,sBAAsB,CAAC;AAE9B,2DAA2D;AAC3D,MAAM,WAAW,UAAW,SAAQ,IAAI,CAAC,kBAAkB,EAAE,UAAU,GAAG,MAAM,CAAC;IAC/E,IAAI,EAAE,MAAM,CAAC;IACb,uEAAuE;IACvE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,qCAAqC;AACrC,MAAM,WAAW,aAAa,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM;IACtD,MAAM,EAAE,MAAM,CAAC;IACf;;gEAE4D;IAC5D,GAAG,EAAE,CAAC,CAAC;IACP;;kEAE8D;IAC9D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;6EACyE;IACzE,MAAM,EAAE,MAAM,UAAU,CAAC;CAC1B;AAED,mDAAmD;AACnD,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oDAAoD;IACpD,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;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GAAG,IAAI,CAAC;IAC/D,gGAAgG;IAChG,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjD,uDAAuD;IACvD,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS,CAAC;IAChE,6EAA6E;IAC7E,KAAK,IAAI,IAAI,CAAC;CACf;AAED,yDAAyD;AACzD,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAElD;AAKD,4FAA4F;AAC5F,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,OAAO,GAAG,eAAe,GAAG,IAAI,CAc7E;AASD,wBAAgB,SAAS,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,SAAS,eAAe,EAAE,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,CA4NzI"}
@@ -0,0 +1,260 @@
1
+ import { createRoomPresence, presenceUser } from '../room-presence.js';
2
+ import { createRoomChat, defaultPresent, toChatBroadcast, CHAT_HISTORY_JOIN_LIMIT, } from '../chat/room-chat.js';
3
+ /** The socket.io room a served room's sockets are in. */
4
+ export function roomChannel(roomId) {
5
+ return `room:${roomId}`;
6
+ }
7
+ const MAX_NAME_LENGTH = 64;
8
+ const MAX_SPRITE_LENGTH = 64;
9
+ /** Validate an `identity_update` payload (watchparty's `IdentityUpdate` shape), or null. */
10
+ export function parseIdentityRequest(payload) {
11
+ if (!payload || typeof payload !== 'object')
12
+ return null;
13
+ const p = payload;
14
+ const out = {};
15
+ if (p.name !== undefined) {
16
+ if (typeof p.name !== 'string' || p.name.trim().length === 0 || p.name.length > MAX_NAME_LENGTH)
17
+ return null;
18
+ out.name = p.name.trim();
19
+ }
20
+ if (p.sprite !== undefined && p.sprite !== null) {
21
+ if (typeof p.sprite !== 'string' || p.sprite.length === 0 || p.sprite.length > MAX_SPRITE_LENGTH)
22
+ return null;
23
+ out.sprite = p.sprite;
24
+ }
25
+ if (p.avatar === true)
26
+ out.avatar = true;
27
+ return out;
28
+ }
29
+ export function serveRoom(io, opts) {
30
+ const nsp = io.of(opts.namespace ?? '/room');
31
+ const chat = createRoomChat(opts);
32
+ const log = opts.onEvent ?? (() => { });
33
+ const conns = new Map(); // socket id → connection
34
+ /** The one copy of each account's identity in this process. */
35
+ const accounts = new Map();
36
+ const presence = createRoomPresence({
37
+ tracker: opts.presence,
38
+ onIdle: (connectionId, ev) => {
39
+ const c = conns.get(connectionId);
40
+ log('warn', 'room.idle', { sid: connectionId, room_id: c?.admission.roomId, silent_ms: ev.at - ev.lastSeen });
41
+ c?.socket.disconnect(true);
42
+ },
43
+ // The app may move its own tracker (forget a person, drop a connection):
44
+ // every roster that person is in is re-sent.
45
+ onChange: (ev) => {
46
+ const rooms = new Set();
47
+ for (const c of conns.values())
48
+ if (c.admission.key === ev.key)
49
+ rooms.add(c.admission.roomId);
50
+ for (const r of rooms)
51
+ sendPresence(r);
52
+ },
53
+ });
54
+ function memberOf(c) {
55
+ const m = c.admission.member();
56
+ const a = c.admission.accountId ? accounts.get(c.admission.accountId) : undefined;
57
+ return {
58
+ ...m,
59
+ clientId: c.socket.id,
60
+ ...(c.admission.accountId ? { authorId: m.authorId ?? c.admission.accountId } : {}),
61
+ ...(a?.avatarUrl ? { avatarUrl: a.avatarUrl, avatarSource: a.avatarSource } : {}),
62
+ ...(a?.cosmetics ? { cosmetics: a.cosmetics } : {}),
63
+ ...(c.override.name !== undefined ? { name: c.override.name } : {}),
64
+ // An account's resolved name is its name: it wins over any override.
65
+ ...(a?.name ? { name: a.name, registryName: true } : {}),
66
+ ...(c.override.sprite !== undefined ? { sprite: c.override.sprite } : {}),
67
+ };
68
+ }
69
+ /** The room's live connections: admitted here AND still live on the tracker. */
70
+ function live(roomId) {
71
+ const out = [];
72
+ for (const c of conns.values()) {
73
+ if (c.admission.roomId === roomId && opts.presence.keyOf(c.socket.id) === c.admission.key)
74
+ out.push(c);
75
+ }
76
+ return out;
77
+ }
78
+ function members(roomId) {
79
+ return live(roomId).map(memberOf);
80
+ }
81
+ function senders(roomId) {
82
+ return members(roomId).map((m) => ({ clientId: m.clientId, author: m.author, authorId: m.authorId, name: m.name, sprite: m.sprite ?? null }));
83
+ }
84
+ function sendPresence(roomId) {
85
+ nsp.to(roomChannel(roomId)).emit('presence', { users: members(roomId).map(presenceUser) });
86
+ }
87
+ async function presentStored(roomId, messages) {
88
+ const who = senders(roomId);
89
+ return opts.present ? opts.present(roomId, messages, who) : defaultPresent(messages, who);
90
+ }
91
+ function broadcast(roomId, payload) {
92
+ nsp.to(roomChannel(roomId)).emit('chat_broadcast', payload);
93
+ }
94
+ async function leave(c) {
95
+ conns.delete(c.socket.id);
96
+ presence.disconnect(c.socket.id);
97
+ // Forget an account with no connection left, so its next join reads it
98
+ // afresh (a rename made on another device lands then at the latest).
99
+ const accountId = c.admission.accountId;
100
+ if (accountId && ![...conns.values()].some((x) => x.admission.accountId === accountId))
101
+ accounts.delete(accountId);
102
+ await c.socket.leave(roomChannel(c.admission.roomId));
103
+ sendPresence(c.admission.roomId);
104
+ }
105
+ /** Resolve `accountId` (fresh or cached) and, if it changed, push it to every room it is in. */
106
+ async function resolveAccount(accountId, socket, fresh) {
107
+ if (!opts.account)
108
+ return;
109
+ if (!fresh && accounts.has(accountId))
110
+ return;
111
+ let next;
112
+ try {
113
+ next = await opts.account(accountId, { fresh, socket });
114
+ }
115
+ catch (err) {
116
+ log('warn', 'room.account_resolve_failed', { sid: socket.id, err_message: String(err) });
117
+ return;
118
+ }
119
+ if (!next)
120
+ return;
121
+ const before = accounts.get(accountId);
122
+ accounts.set(accountId, next);
123
+ if (before && JSON.stringify(before) === JSON.stringify(next))
124
+ return;
125
+ const rooms = new Set();
126
+ for (const c of conns.values())
127
+ if (c.admission.accountId === accountId)
128
+ rooms.add(c.admission.roomId);
129
+ for (const r of rooms)
130
+ sendPresence(r);
131
+ log('info', 'room.account_identity', { account_rooms: rooms.size, fresh });
132
+ }
133
+ async function decideIdentity(socket, c, req) {
134
+ const member = memberOf(c);
135
+ const others = live(c.admission.roomId).filter((o) => o !== c).map(memberOf);
136
+ if (opts.identity)
137
+ return opts.identity(socket, req, { roomId: c.admission.roomId, member, others });
138
+ if (req.sprite && others.some((o) => o.sprite === req.sprite)) {
139
+ return { error: { code: 'conflict', message: 'sprite_taken' } };
140
+ }
141
+ return {
142
+ ...(req.name !== undefined && !member.registryName ? { name: req.name } : {}),
143
+ ...(req.sprite !== undefined ? { sprite: req.sprite } : {}),
144
+ };
145
+ }
146
+ nsp.on('connection', (socket) => {
147
+ const refuse = (code, message) => socket.emit('error', { code, message });
148
+ // Any traffic proves the connection carries it.
149
+ socket.onAny(() => { presence.beat(socket.id); });
150
+ socket.on('join', async (payload) => {
151
+ const roomKey = payload && typeof payload === 'object' ? payload.room_key : undefined;
152
+ if (typeof roomKey !== 'string' || !roomKey)
153
+ return refuse('room/invalid_join', 'join needs a room_key');
154
+ let admission;
155
+ try {
156
+ admission = await opts.admit(socket, payload);
157
+ }
158
+ catch (err) {
159
+ log('warn', 'room.admit_failed', { sid: socket.id, err_message: String(err) });
160
+ admission = null;
161
+ }
162
+ if (!socket.connected)
163
+ return;
164
+ if (!admission) {
165
+ log('warn', 'room.join_refused', { sid: socket.id });
166
+ return refuse('auth/forbidden', 'not a member of this room');
167
+ }
168
+ const previous = conns.get(socket.id);
169
+ if (previous)
170
+ await leave(previous);
171
+ const c = { socket, admission, override: {} };
172
+ conns.set(socket.id, c);
173
+ presence.connect(admission.key, socket.id);
174
+ await socket.join(roomChannel(admission.roomId));
175
+ // The join ack. A served room plays nothing, so the playback half is idle.
176
+ socket.emit('snapshot', {
177
+ room_id: admission.roomId, play_state: 'paused', playhead_ms: 0, leader_id: null,
178
+ media_id: null, server_seq: 0, server_ts: Date.now(),
179
+ });
180
+ sendPresence(admission.roomId);
181
+ // Off the join's path: a cached identity is already in the presence
182
+ // above; an unknown one is pushed when it lands.
183
+ if (admission.accountId)
184
+ void resolveAccount(admission.accountId, socket, false);
185
+ const stored = await chat.store.recentMessages(admission.roomId, opts.historyJoinLimit ?? CHAT_HISTORY_JOIN_LIMIT);
186
+ const who = await presentStored(admission.roomId, stored);
187
+ socket.emit('chat_history', { messages: stored.map((m, i) => toChatBroadcast(m, who[i] ?? { name: 'Someone', sprite: null })) });
188
+ log('info', 'room.joined', { sid: socket.id, room_id: admission.roomId });
189
+ });
190
+ socket.on('time_ping', (payload) => {
191
+ const raw = payload?.client_ts;
192
+ socket.emit('time_pong', { server_ts: Date.now(), client_sent_ts: typeof raw === 'number' && Number.isFinite(raw) ? raw : null });
193
+ });
194
+ socket.on('identity_update', async (payload) => {
195
+ const c = conns.get(socket.id);
196
+ if (!c)
197
+ return refuse('auth/forbidden', 'join the room first');
198
+ const req = parseIdentityRequest(payload);
199
+ if (!req)
200
+ return refuse('payload/invalid', 'invalid identity_update');
201
+ // A signed-in person who renamed or changed their picture: re-read the
202
+ // account, for every room and tab of theirs, not just this connection.
203
+ const accountId = c.admission.accountId;
204
+ if (accountId && opts.account && (req.name !== undefined || req.avatar)) {
205
+ await resolveAccount(accountId, socket, true);
206
+ if (accounts.get(accountId)?.name)
207
+ delete req.name;
208
+ }
209
+ const decision = await decideIdentity(socket, c, req);
210
+ if ('error' in decision)
211
+ return refuse(decision.error.code, decision.error.message);
212
+ if (decision.name !== undefined)
213
+ c.override.name = decision.name;
214
+ if (decision.sprite !== undefined)
215
+ c.override.sprite = decision.sprite;
216
+ sendPresence(c.admission.roomId);
217
+ });
218
+ socket.on('chat_send', async (payload) => {
219
+ const c = conns.get(socket.id);
220
+ if (!c)
221
+ return refuse('auth/forbidden', 'join the room before chatting');
222
+ const m = memberOf(c);
223
+ const outcome = await chat.send(c.admission.roomId, { clientId: m.clientId, author: m.author, authorId: m.authorId, name: m.name, sprite: m.sprite ?? null }, payload);
224
+ if (!outcome.ok) {
225
+ log('warn', 'room.chat_refused', { sid: socket.id, room_id: c.admission.roomId, reason: outcome.reason });
226
+ return refuse(outcome.reason === 'rate_limited' ? 'rate/limited' : 'server/error', `chat ${outcome.reason}`);
227
+ }
228
+ broadcast(c.admission.roomId, outcome.broadcast);
229
+ });
230
+ socket.on('disconnect', () => {
231
+ const c = conns.get(socket.id);
232
+ if (c)
233
+ void leave(c);
234
+ });
235
+ });
236
+ return {
237
+ namespace: nsp,
238
+ chat,
239
+ rooms() {
240
+ const out = new Set();
241
+ for (const c of conns.values())
242
+ if (presence.isLive(c.socket.id))
243
+ out.add(c.admission.roomId);
244
+ return [...out];
245
+ },
246
+ members,
247
+ refresh: sendPresence,
248
+ broadcast,
249
+ async refreshAccount(accountId) {
250
+ const c = [...conns.values()].find((x) => x.admission.accountId === accountId);
251
+ if (c)
252
+ await resolveAccount(accountId, c.socket, true);
253
+ },
254
+ accountIdentity: (accountId) => accounts.get(accountId),
255
+ close() {
256
+ presence.dispose();
257
+ nsp.disconnectSockets(true);
258
+ },
259
+ };
260
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * A room's presence on the wire: who is here, as the room chrome reads it, and
3
+ * the liveness rule that decides it — ONE implementation for every app.
4
+ *
5
+ * Two pieces, both used by watchparty's own room socket and by `serveRoom`
6
+ * (`@wolffm/rooms-server/room`), which is how another app serves the same room
7
+ * chrome from its own server:
8
+ *
9
+ * - `presenceUser` is the roster row (`presence { users: [...] }`), byte for
10
+ * byte what watchparty has always sent, so the chrome's client code is one
11
+ * piece of code whichever server it talks to.
12
+ * - `createRoomPresence` puts a room's CONNECTIONS on the app's own
13
+ * `PresenceTracker`: a connection is live while it beats, a silent one is
14
+ * closed (`onIdle`), and the person goes offline only with their last
15
+ * connection. The tracker is the app's, never a private copy: the same
16
+ * instance the app hooks its seat release to (`tracker.on`), so a room has
17
+ * one presence, not one for the chrome and another for the seats.
18
+ */
19
+ import type { PresenceEvent, PresenceTracker } from './presence.js';
20
+ /** One person-connection as the room shows it. */
21
+ export interface RoomPresenceMember {
22
+ /** The connection (socket id). One row per connection: two tabs are two rows. */
23
+ clientId: string;
24
+ /** A stable handle for the person (`participantHandle`), so "my message" survives a reconnect. */
25
+ author?: string;
26
+ /** Undefined (not named yet) is sent as an absent `name`; the client shows "Anon". */
27
+ name: string | undefined;
28
+ /** Undefined (no character yet) is sent as an absent `sprite_id`, as watchparty always has. */
29
+ sprite: string | null | undefined;
30
+ isLeader?: boolean;
31
+ /** `name` is the person's key-registry name; the client adopts it. */
32
+ registryName?: boolean;
33
+ /** Their picture, when it is not the character. */
34
+ avatarUrl?: string;
35
+ avatarSource?: string;
36
+ /** What they wear. Untrusted shape: the client cleans it. */
37
+ cosmetics?: unknown;
38
+ }
39
+ /** A `presence.users[]` entry — watchparty's wire, unchanged. */
40
+ export interface PresenceUserWire {
41
+ client_id: string;
42
+ author?: string;
43
+ name: string | undefined;
44
+ registry_name?: true;
45
+ sprite_id: string | null | undefined;
46
+ avatar_url?: string;
47
+ avatar_source?: string;
48
+ cosmetics?: unknown;
49
+ is_leader: boolean;
50
+ }
51
+ export declare function presenceUser(m: RoomPresenceMember): PresenceUserWire;
52
+ export interface RoomPresenceOptions<K extends string> {
53
+ /** The app's tracker — the one its seats listen to. */
54
+ tracker: PresenceTracker<K>;
55
+ /**
56
+ * A connection stopped beating for the tracker's `idleMs`: close its
57
+ * transport (a server-side close, so the client reconnects and rejoins).
58
+ * Only called for connections registered through this object.
59
+ */
60
+ onIdle: (connectionId: string, event: Extract<PresenceEvent<K>, {
61
+ type: 'idle';
62
+ }>) => void;
63
+ /** A person went online or offline (or left). For re-broadcasting the rosters they are in. */
64
+ onChange?: (event: Exclude<PresenceEvent<K>, {
65
+ type: 'idle';
66
+ }>) => void;
67
+ }
68
+ export interface RoomPresence<K extends string> {
69
+ tracker: PresenceTracker<K>;
70
+ /** A connection joined as `key`. Counts as a heartbeat. */
71
+ connect(key: K, connectionId: string): void;
72
+ /** Any traffic from the connection. False when it is not live. */
73
+ beat(connectionId: string): boolean;
74
+ /** The connection closed. Idempotent. */
75
+ disconnect(connectionId: string): void;
76
+ /** Whether the tracker still holds this connection as live. */
77
+ isLive(connectionId: string): boolean;
78
+ /** Stop listening to the tracker (the tracker itself is the app's to dispose). */
79
+ dispose(): void;
80
+ }
81
+ export declare function createRoomPresence<K extends string>(opts: RoomPresenceOptions<K>): RoomPresence<K>;
82
+ //# sourceMappingURL=room-presence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"room-presence.d.ts","sourceRoot":"","sources":["../src/room-presence.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEpE,kDAAkD;AAClD,MAAM,WAAW,kBAAkB;IACjC,iFAAiF;IACjF,QAAQ,EAAE,MAAM,CAAC;IACjB,kGAAkG;IAClG,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sFAAsF;IACtF,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,+FAA+F;IAC/F,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAClC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,sEAAsE;IACtE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,mDAAmD;IACnD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,6DAA6D;IAC7D,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,iEAAiE;AACjE,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,aAAa,CAAC,EAAE,IAAI,CAAC;IACrB,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACrC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM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3
+ client_id: m.clientId,
4
+ ...(m.author !== undefined ? { author: m.author } : {}),
5
+ name: m.name,
6
+ ...(m.registryName ? { registry_name: true } : {}),
7
+ sprite_id: m.sprite,
8
+ ...(m.avatarUrl ? { avatar_url: m.avatarUrl, avatar_source: m.avatarSource } : {}),
9
+ ...(m.cosmetics ? { cosmetics: m.cosmetics } : {}),
10
+ is_leader: !!m.isLeader,
11
+ };
12
+ }
13
+ export function createRoomPresence(opts) {
14
+ const { tracker } = opts;
15
+ // Connections this object registered. The tracker is shared with the app, so
16
+ // its events also name connections that are none of ours.
17
+ const mine = new Set();
18
+ const unsubscribe = tracker.on((event) => {
19
+ if (event.type === 'idle') {
20
+ if (!mine.has(event.connectionId))
21
+ return;
22
+ opts.onIdle(event.connectionId, event);
23
+ return;
24
+ }
25
+ opts.onChange?.(event);
26
+ });
27
+ return {
28
+ tracker,
29
+ connect(key, connectionId) {
30
+ mine.add(connectionId);
31
+ tracker.connect(key, connectionId);
32
+ },
33
+ beat(connectionId) {
34
+ return tracker.heartbeat(connectionId);
35
+ },
36
+ disconnect(connectionId) {
37
+ mine.delete(connectionId);
38
+ tracker.disconnect(connectionId);
39
+ },
40
+ isLive(connectionId) {
41
+ return tracker.keyOf(connectionId) !== undefined;
42
+ },
43
+ dispose() {
44
+ unsubscribe();
45
+ mine.clear();
46
+ },
47
+ };
48
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/rooms-server",
3
- "version": "0.45.63",
4
- "gitHead": "0ccf8bf6bb8756b4a29b88bb50f71701e11b1233",
3
+ "version": "0.45.64",
4
+ "gitHead": "0000ab7b89ef00d6f2d04d0c03d0abd4d4b69f36",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "Room lifecycle, membership, seating, identity, presence, backpressure-aware emit and durable room storage for a socket.io server.",
@@ -19,6 +19,10 @@
19
19
  "./chat": {
20
20
  "types": "./dist/chat/index.d.ts",
21
21
  "import": "./dist/chat/index.js"
22
+ },
23
+ "./room": {
24
+ "types": "./dist/room/index.d.ts",
25
+ "import": "./dist/room/index.js"
22
26
  }
23
27
  },
24
28
  "files": [
@@ -31,7 +35,7 @@
31
35
  "directory": "packages/rooms-server"
32
36
  },
33
37
  "dependencies": {
34
- "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.63"
38
+ "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.64"
35
39
  },
36
40
  "peerDependencies": {
37
41
  "socket.io": "^4.8.3"