@hadoku/rooms-server 0.45.66 → 0.45.68
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/room/serve-room.d.ts +87 -3
- package/dist/room/serve-room.d.ts.map +1 -1
- package/dist/room/serve-room.js +196 -34
- package/package.json +3 -3
|
@@ -27,6 +27,21 @@
|
|
|
27
27
|
* Identity, names and characters are the app's (`admit` returns who the
|
|
28
28
|
* connection is; `identity` decides a change). Nothing about a person is
|
|
29
29
|
* stored here.
|
|
30
|
+
*
|
|
31
|
+
* WHAT EVERY APP GETS, so no app keeps its own copy (watchparty's room socket
|
|
32
|
+
* runs on this too, with `namespace: '/'` and its playback events beside it):
|
|
33
|
+
* - the room's LINES (`announce: true`): "{name} joined" when a
|
|
34
|
+
* person arrives (not when they come back inside the tracker's grace),
|
|
35
|
+
* "{name} left" when the tracker says they LEFT (after the grace — a blip
|
|
36
|
+
* says nothing), "{name} changed their name" / "changed character" when
|
|
37
|
+
* their identity changes, in every room their account is in;
|
|
38
|
+
* - SAME-TAB TAKEOVER: a join carrying the `tab_id` of a live connection of
|
|
39
|
+
* the same person in the room retires that connection (a server-side close,
|
|
40
|
+
* so it does not reconnect) before the new one is seated. A connection cut
|
|
41
|
+
* upstream never arrives as a close; without this the person shows twice
|
|
42
|
+
* until the idle close. Two tabs are two tab ids, and stay two rows;
|
|
43
|
+
* - an account change WRITTEN THROUGH to the app (`admission.apply`) on every
|
|
44
|
+
* connection of the account, so the app's own reads of a name never go stale.
|
|
30
45
|
*/
|
|
31
46
|
import type { Namespace, Server as SocketIOServer, Socket } from 'socket.io';
|
|
32
47
|
import type { PresenceTracker } from '../presence.js';
|
|
@@ -52,6 +67,19 @@ export interface RoomAdmission<K extends string = string> {
|
|
|
52
67
|
/** Who this connection is right now — re-read for every roster and every
|
|
53
68
|
* chat line, so the app's own renames show at once (call `refresh`). */
|
|
54
69
|
member: () => RoomMember;
|
|
70
|
+
/** The account's identity changed (or was first resolved): write it into the
|
|
71
|
+
* app's own record of this connection. Optional; `member()` is overlaid
|
|
72
|
+
* with it regardless. Called for every connection of the account. */
|
|
73
|
+
apply?: (identity: AccountIdentity) => void;
|
|
74
|
+
}
|
|
75
|
+
/** A join the app refused, with the code the client reads. */
|
|
76
|
+
export interface RoomRefusal {
|
|
77
|
+
error: {
|
|
78
|
+
code: string;
|
|
79
|
+
message: string;
|
|
80
|
+
};
|
|
81
|
+
/** Close the socket after the error (a refusal the client cannot fix by retrying). */
|
|
82
|
+
disconnect?: boolean;
|
|
55
83
|
}
|
|
56
84
|
/** What `identity_update` asked for, validated. */
|
|
57
85
|
export interface IdentityRequest {
|
|
@@ -95,7 +123,44 @@ export interface ServeRoomOptions<K extends string, M extends RoomChatMessage> e
|
|
|
95
123
|
*/
|
|
96
124
|
admit: (socket: Socket, join: {
|
|
97
125
|
room_key: string;
|
|
98
|
-
} & Record<string, unknown>) => Promise<RoomAdmission<K> | null> | RoomAdmission<K> | null;
|
|
126
|
+
} & Record<string, unknown>) => Promise<RoomAdmission<K> | RoomRefusal | null> | RoomAdmission<K> | RoomRefusal | null;
|
|
127
|
+
/**
|
|
128
|
+
* Seat an admitted connection in the app's own room state (claim its
|
|
129
|
+
* character, record the member) — after any same-tab retirement, so what the
|
|
130
|
+
* retired connection held is free again, and before the join ack. Optional.
|
|
131
|
+
*/
|
|
132
|
+
seat?: (socket: Socket, admission: RoomAdmission<K>, join: Record<string, unknown>, ctx: {
|
|
133
|
+
replaced?: string;
|
|
134
|
+
}) => Promise<void> | void;
|
|
135
|
+
/** The join ack. Default: a room with nothing playing. */
|
|
136
|
+
snapshot?: (socket: Socket, admission: RoomAdmission<K>) => unknown;
|
|
137
|
+
/** Right after the ack and the roster; the history and the join line follow. */
|
|
138
|
+
onJoined?: (socket: Socket, admission: RoomAdmission<K>, join: Record<string, unknown>) => Promise<void> | void;
|
|
139
|
+
/**
|
|
140
|
+
* A joined connection closed. Runs synchronously, before the roster is
|
|
141
|
+
* re-sent, so the app can release what the connection held. `replacedBy`
|
|
142
|
+
* is the connection that retired it (same-tab takeover).
|
|
143
|
+
*/
|
|
144
|
+
onLeave?: (socket: Socket, admission: RoomAdmission<K>, info: {
|
|
145
|
+
reason: string;
|
|
146
|
+
replacedBy?: string;
|
|
147
|
+
}) => void;
|
|
148
|
+
/** Post the room's join / leave / rename lines (see the file header). Default false: an app turns them on. */
|
|
149
|
+
announce?: boolean;
|
|
150
|
+
/** Whether lines may still be stored for `roomId` (a deleted room's must not come back). Default: always. */
|
|
151
|
+
roomExists?: (roomId: string) => boolean;
|
|
152
|
+
/**
|
|
153
|
+
* Same-tab takeover: may `next` retire `previous`, which presented the same
|
|
154
|
+
* `tab_id`? Default: the same person (`key`). Refused, it is logged
|
|
155
|
+
* (`room.tab_id_mismatch`) and nothing is retired.
|
|
156
|
+
*/
|
|
157
|
+
sameTab?: (previous: RoomAdmission<K>, next: RoomAdmission<K>) => boolean;
|
|
158
|
+
/** Keep `previous` even so (the app owns its own handoff for it, e.g. a leader). */
|
|
159
|
+
keepOnRejoin?: (previous: RoomAdmission<K>, previousSocketId: string) => boolean;
|
|
160
|
+
/** Rate-limit `identity_update`; false drops it. Default: no limit. */
|
|
161
|
+
allowIdentity?: (socket: Socket) => boolean;
|
|
162
|
+
/** A chat line was sent and broadcast. */
|
|
163
|
+
onChat?: (socket: Socket, admission: RoomAdmission<K>, message: M) => void;
|
|
99
164
|
/**
|
|
100
165
|
* Decide an `identity_update`. Default: a name is taken unless the member's
|
|
101
166
|
* name is their registry name; a character is taken unless another
|
|
@@ -143,7 +208,14 @@ export interface ServeRoomOptions<K extends string, M extends RoomChatMessage> e
|
|
|
143
208
|
name: string;
|
|
144
209
|
sprite: string | null;
|
|
145
210
|
}>;
|
|
146
|
-
onEvent?: (level: 'info' | 'warn', event: string, fields: Record<string, unknown>) => void;
|
|
211
|
+
onEvent?: (level: 'info' | 'warn' | 'debug', event: string, fields: Record<string, unknown>) => void;
|
|
212
|
+
}
|
|
213
|
+
/** A system line, as the app asks for one (`post`). */
|
|
214
|
+
export interface RoomLine {
|
|
215
|
+
/** The connection the line is about; named live (`{name}` in `text`). */
|
|
216
|
+
clientId: string;
|
|
217
|
+
systemType: string;
|
|
218
|
+
text: string;
|
|
147
219
|
}
|
|
148
220
|
export interface ServedRoom<K extends string, M extends RoomChatMessage> {
|
|
149
221
|
namespace: Namespace;
|
|
@@ -156,8 +228,20 @@ export interface ServedRoom<K extends string, M extends RoomChatMessage> {
|
|
|
156
228
|
}>;
|
|
157
229
|
/** Re-send `roomId`'s roster (after the app changed who someone is). */
|
|
158
230
|
refresh(roomId: string): void;
|
|
159
|
-
/** Broadcast a chat line the app composed
|
|
231
|
+
/** Broadcast a chat line the app composed. */
|
|
160
232
|
broadcast(roomId: string, payload: ChatBroadcastPayload): void;
|
|
233
|
+
/** Store and broadcast a system line about a member (`{name}` is filled live). */
|
|
234
|
+
post(roomId: string, line: RoomLine): Promise<void>;
|
|
235
|
+
/** The joined connection `socketId`, if any. */
|
|
236
|
+
connection(socketId: string): {
|
|
237
|
+
roomId: string;
|
|
238
|
+
key: K;
|
|
239
|
+
admission: RoomAdmission<K>;
|
|
240
|
+
} | undefined;
|
|
241
|
+
/** Who `socketId` is as the room shows it now, if joined. */
|
|
242
|
+
member(socketId: string): (RoomMember & {
|
|
243
|
+
clientId: string;
|
|
244
|
+
}) | undefined;
|
|
161
245
|
/** Re-resolve an account fresh and push it to every room it is in (any other change signal). */
|
|
162
246
|
refreshAccount(accountId: string): Promise<void>;
|
|
163
247
|
/** The account's identity as last resolved, if any. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serve-room.d.ts","sourceRoot":"","sources":["../../src/room/serve-room.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"serve-room.d.ts","sourceRoot":"","sources":["../../src/room/serve-room.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;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AgB,oBAAoB,CAAC,OAAO,EAAE,OAAO,GAAG,eAAe,GAAG,IAAI,CAc7E;AAkBD,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,CA4XzI"}
|
package/dist/room/serve-room.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRoomPresence, presenceUser } from '../room-presence.js';
|
|
2
|
-
import { createRoomChat, defaultPresent, toChatBroadcast, CHAT_HISTORY_JOIN_LIMIT, } from '../chat/room-chat.js';
|
|
2
|
+
import { createRoomChat, defaultPresent, toChatBroadcast, CHAT_HISTORY_JOIN_LIMIT, CHAT_NAME_TOKEN, } from '../chat/room-chat.js';
|
|
3
3
|
/** The socket.io room a served room's sockets are in. */
|
|
4
4
|
export function roomChannel(roomId) {
|
|
5
5
|
return `room:${roomId}`;
|
|
@@ -27,16 +27,28 @@ export function parseIdentityRequest(payload) {
|
|
|
27
27
|
out.avatar = true;
|
|
28
28
|
return out;
|
|
29
29
|
}
|
|
30
|
+
function isRefusal(a) {
|
|
31
|
+
return 'error' in a;
|
|
32
|
+
}
|
|
33
|
+
const MAX_TAB_ID_LENGTH = 64;
|
|
30
34
|
export function serveRoom(io, opts) {
|
|
31
35
|
const nsp = io.of(opts.namespace ?? '/room');
|
|
32
36
|
const chat = createRoomChat(opts);
|
|
33
37
|
const log = opts.onEvent ?? (() => { });
|
|
38
|
+
const announce = opts.announce ?? false;
|
|
34
39
|
const conns = new Map(); // socket id → connection
|
|
40
|
+
/** Sockets with a join in flight or done: one join per connection. */
|
|
41
|
+
const joining = new Set();
|
|
35
42
|
/** The one copy of each account's identity in this process. */
|
|
36
43
|
const accounts = new Map();
|
|
37
44
|
/** When each account was last resolved (ms). */
|
|
38
45
|
const resolvedAt = new Map();
|
|
39
46
|
const staleMs = Math.max(0, opts.accountStaleMs ?? DEFAULT_ACCOUNT_STALE_MS);
|
|
47
|
+
/** People who just arrived (not returned inside the grace): their join line is owed. */
|
|
48
|
+
const arrived = new Set();
|
|
49
|
+
/** People whose last connection closed, as the room last showed them: the
|
|
50
|
+
* subject of their "left" line when the tracker says they left. */
|
|
51
|
+
const departed = new Map();
|
|
40
52
|
const presence = createRoomPresence({
|
|
41
53
|
tracker: opts.presence,
|
|
42
54
|
onIdle: (connectionId, ev) => {
|
|
@@ -47,6 +59,18 @@ export function serveRoom(io, opts) {
|
|
|
47
59
|
// The app may move its own tracker (forget a person, drop a connection):
|
|
48
60
|
// every roster that person is in is re-sent.
|
|
49
61
|
onChange: (ev) => {
|
|
62
|
+
if (ev.type === 'online') {
|
|
63
|
+
departed.delete(ev.key);
|
|
64
|
+
if (!ev.returned)
|
|
65
|
+
arrived.add(ev.key);
|
|
66
|
+
}
|
|
67
|
+
else if (ev.type === 'left') {
|
|
68
|
+
arrived.delete(ev.key);
|
|
69
|
+
const gone = departed.get(ev.key);
|
|
70
|
+
departed.delete(ev.key);
|
|
71
|
+
if (gone && announce)
|
|
72
|
+
void postLine(gone.roomId, gone.member, 'leave', `${CHAT_NAME_TOKEN} left`);
|
|
73
|
+
}
|
|
50
74
|
const rooms = new Set();
|
|
51
75
|
for (const c of conns.values())
|
|
52
76
|
if (c.admission.key === ev.key)
|
|
@@ -83,7 +107,10 @@ export function serveRoom(io, opts) {
|
|
|
83
107
|
return live(roomId).map(memberOf);
|
|
84
108
|
}
|
|
85
109
|
function senders(roomId) {
|
|
86
|
-
return members(roomId).map(
|
|
110
|
+
return members(roomId).map(senderOf);
|
|
111
|
+
}
|
|
112
|
+
function senderOf(m) {
|
|
113
|
+
return { clientId: m.clientId, author: m.author, authorId: m.authorId, name: m.name || 'Anon', sprite: m.sprite ?? null };
|
|
87
114
|
}
|
|
88
115
|
function sendPresence(roomId) {
|
|
89
116
|
nsp.to(roomChannel(roomId)).emit('presence', { users: members(roomId).map(presenceUser) });
|
|
@@ -95,8 +122,49 @@ export function serveRoom(io, opts) {
|
|
|
95
122
|
function broadcast(roomId, payload) {
|
|
96
123
|
nsp.to(roomChannel(roomId)).emit('chat_broadcast', payload);
|
|
97
124
|
}
|
|
98
|
-
|
|
125
|
+
/**
|
|
126
|
+
* Store and broadcast a system line about `subject`. The stored line keeps
|
|
127
|
+
* who it is about, never their name (`{name}` is filled when it is SENT).
|
|
128
|
+
*/
|
|
129
|
+
async function postLine(roomId, subject, systemType, text) {
|
|
130
|
+
if (opts.roomExists && !opts.roomExists(roomId))
|
|
131
|
+
return;
|
|
132
|
+
const msg = {
|
|
133
|
+
id: opts.newId ? opts.newId() : globalThis.crypto.randomUUID(),
|
|
134
|
+
clientId: subject?.clientId ?? '',
|
|
135
|
+
...(subject?.author !== undefined ? { author: subject.author } : {}),
|
|
136
|
+
...(subject?.authorId !== undefined ? { authorId: subject.authorId } : {}),
|
|
137
|
+
text,
|
|
138
|
+
ts: (opts.now ?? Date.now)(),
|
|
139
|
+
isSystem: true,
|
|
140
|
+
systemType,
|
|
141
|
+
};
|
|
142
|
+
try {
|
|
143
|
+
await chat.store.appendMessage(roomId, msg);
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
log('warn', 'room.line_append_failed', { room_id: roomId, system_type: systemType, err_message: String(err) });
|
|
147
|
+
}
|
|
148
|
+
broadcast(roomId, toChatBroadcast(msg, { name: subject?.name || 'System', sprite: subject?.sprite ?? null }));
|
|
149
|
+
}
|
|
150
|
+
function leave(c, reason) {
|
|
99
151
|
conns.delete(c.socket.id);
|
|
152
|
+
joining.delete(c.socket.id);
|
|
153
|
+
const key = c.admission.key;
|
|
154
|
+
const lastOfPerson = ![...conns.values()].some((x) => x.admission.key === key);
|
|
155
|
+
// Who they were, read before the app lets go of them: the subject of a
|
|
156
|
+
// "left" line if the tracker says they left. A connection retired by its
|
|
157
|
+
// own tab's rejoin never gets one: the rejoin connects at once, inside
|
|
158
|
+
// the grace, and its `online` clears this.
|
|
159
|
+
if (lastOfPerson)
|
|
160
|
+
departed.set(key, { roomId: c.admission.roomId, member: memberOf(c) });
|
|
161
|
+
// The app releases what the connection held BEFORE the roster is re-sent.
|
|
162
|
+
try {
|
|
163
|
+
opts.onLeave?.(c.socket, c.admission, { reason, ...(c.replacedBy ? { replacedBy: c.replacedBy } : {}) });
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
log('warn', 'room.on_leave_failed', { sid: c.socket.id, err_message: String(err) });
|
|
167
|
+
}
|
|
100
168
|
presence.disconnect(c.socket.id);
|
|
101
169
|
// Forget an account with no connection left, so its next join reads it
|
|
102
170
|
// afresh.
|
|
@@ -105,9 +173,30 @@ export function serveRoom(io, opts) {
|
|
|
105
173
|
accounts.delete(accountId);
|
|
106
174
|
resolvedAt.delete(accountId);
|
|
107
175
|
}
|
|
108
|
-
|
|
176
|
+
void c.socket.leave(roomChannel(c.admission.roomId));
|
|
109
177
|
sendPresence(c.admission.roomId);
|
|
110
178
|
}
|
|
179
|
+
/** Same-tab takeover (see the file header). */
|
|
180
|
+
function retireSameTab(socket, admission, tabId) {
|
|
181
|
+
if (!tabId)
|
|
182
|
+
return undefined;
|
|
183
|
+
for (const old of conns.values()) {
|
|
184
|
+
if (old.socket.id === socket.id || old.tabId !== tabId || old.admission.roomId !== admission.roomId)
|
|
185
|
+
continue;
|
|
186
|
+
const same = opts.sameTab ? opts.sameTab(old.admission, admission) : old.admission.key === admission.key;
|
|
187
|
+
if (!same) {
|
|
188
|
+
log('warn', 'room.tab_id_mismatch', { room_id: admission.roomId, sid: socket.id, other_sid: old.socket.id });
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
if (opts.keepOnRejoin?.(old.admission, old.socket.id))
|
|
192
|
+
return undefined;
|
|
193
|
+
old.replacedBy = socket.id;
|
|
194
|
+
log('info', 'room.tab_replaced', { room_id: admission.roomId, old_sid: old.socket.id, new_sid: socket.id });
|
|
195
|
+
old.socket.disconnect(true);
|
|
196
|
+
return old.socket.id;
|
|
197
|
+
}
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
111
200
|
/** Resolve `accountId` (fresh or cached) and, if it changed, push it to every room it is in. */
|
|
112
201
|
async function resolveAccount(accountId, socket, fresh) {
|
|
113
202
|
if (!opts.account)
|
|
@@ -129,13 +218,21 @@ export function serveRoom(io, opts) {
|
|
|
129
218
|
resolvedAt.set(accountId, Date.now());
|
|
130
219
|
if (before && JSON.stringify(before) === JSON.stringify(next))
|
|
131
220
|
return;
|
|
132
|
-
const rooms = new
|
|
133
|
-
for (const c of conns.values())
|
|
134
|
-
if (c.admission.accountId
|
|
135
|
-
|
|
136
|
-
|
|
221
|
+
const rooms = new Map();
|
|
222
|
+
for (const c of conns.values()) {
|
|
223
|
+
if (c.admission.accountId !== accountId)
|
|
224
|
+
continue;
|
|
225
|
+
c.admission.apply?.(next);
|
|
226
|
+
if (!rooms.has(c.admission.roomId))
|
|
227
|
+
rooms.set(c.admission.roomId, c);
|
|
228
|
+
}
|
|
229
|
+
const renamed = !!before?.name && !!next.name && before.name !== next.name;
|
|
230
|
+
for (const [r, c] of rooms) {
|
|
137
231
|
sendPresence(r);
|
|
138
|
-
|
|
232
|
+
if (renamed && announce)
|
|
233
|
+
void postLine(r, memberOf(c), 'identity_change', `${CHAT_NAME_TOKEN} changed their name`);
|
|
234
|
+
}
|
|
235
|
+
log('info', 'room.account_identity', { account_rooms: rooms.size, fresh, renamed });
|
|
139
236
|
}
|
|
140
237
|
/** The account's own room activity: re-read it if what is cached is stale. */
|
|
141
238
|
function onAccountActivity(accountId, socket) {
|
|
@@ -161,32 +258,48 @@ export function serveRoom(io, opts) {
|
|
|
161
258
|
// Any traffic proves the connection carries it.
|
|
162
259
|
socket.onAny(() => { presence.beat(socket.id); });
|
|
163
260
|
socket.on('join', async (payload) => {
|
|
164
|
-
|
|
165
|
-
|
|
261
|
+
if (joining.has(socket.id)) {
|
|
262
|
+
log('debug', 'room.duplicate_join', { sid: socket.id });
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
const join = payload && typeof payload === 'object' ? payload : undefined;
|
|
266
|
+
const roomKey = join?.room_key;
|
|
267
|
+
if (!join || typeof roomKey !== 'string' || !roomKey)
|
|
166
268
|
return refuse('room/invalid_join', 'join needs a room_key');
|
|
167
|
-
|
|
269
|
+
joining.add(socket.id);
|
|
270
|
+
let admitted;
|
|
168
271
|
try {
|
|
169
|
-
|
|
272
|
+
admitted = await opts.admit(socket, join);
|
|
170
273
|
}
|
|
171
274
|
catch (err) {
|
|
172
275
|
log('warn', 'room.admit_failed', { sid: socket.id, err_message: String(err) });
|
|
173
|
-
|
|
276
|
+
admitted = null;
|
|
277
|
+
}
|
|
278
|
+
if (!socket.connected) {
|
|
279
|
+
joining.delete(socket.id);
|
|
280
|
+
return;
|
|
174
281
|
}
|
|
175
|
-
if (!
|
|
282
|
+
if (!admitted || isRefusal(admitted)) {
|
|
283
|
+
joining.delete(socket.id);
|
|
284
|
+
if (!admitted) {
|
|
285
|
+
log('warn', 'room.join_refused', { sid: socket.id });
|
|
286
|
+
return refuse('auth/forbidden', 'not a member of this room');
|
|
287
|
+
}
|
|
288
|
+
refuse(admitted.error.code, admitted.error.message);
|
|
289
|
+
if (admitted.disconnect)
|
|
290
|
+
socket.disconnect();
|
|
176
291
|
return;
|
|
177
|
-
if (!admission) {
|
|
178
|
-
log('warn', 'room.join_refused', { sid: socket.id });
|
|
179
|
-
return refuse('auth/forbidden', 'not a member of this room');
|
|
180
292
|
}
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
293
|
+
const admission = admitted;
|
|
294
|
+
const tabId = typeof join.tab_id === 'string' && join.tab_id.length <= MAX_TAB_ID_LENGTH ? join.tab_id : undefined;
|
|
295
|
+
const replaced = retireSameTab(socket, admission, tabId);
|
|
296
|
+
if (opts.seat)
|
|
297
|
+
await opts.seat(socket, admission, join, replaced ? { replaced } : {});
|
|
298
|
+
const c = { socket, admission, override: {}, ...(tabId ? { tabId } : {}) };
|
|
185
299
|
conns.set(socket.id, c);
|
|
186
300
|
presence.connect(admission.key, socket.id);
|
|
187
301
|
await socket.join(roomChannel(admission.roomId));
|
|
188
|
-
|
|
189
|
-
socket.emit('snapshot', {
|
|
302
|
+
socket.emit('snapshot', opts.snapshot ? opts.snapshot(socket, admission) : {
|
|
190
303
|
room_id: admission.roomId, play_state: 'paused', playhead_ms: 0, leader_id: null,
|
|
191
304
|
media_id: null, server_seq: 0, server_ts: Date.now(),
|
|
192
305
|
});
|
|
@@ -195,9 +308,23 @@ export function serveRoom(io, opts) {
|
|
|
195
308
|
// above; an unknown one is pushed when it lands.
|
|
196
309
|
if (admission.accountId)
|
|
197
310
|
void onAccountActivity(admission.accountId, socket);
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
311
|
+
// The app's own state for a joiner rides right behind the ack, before
|
|
312
|
+
// anything that waits on storage.
|
|
313
|
+
if (opts.onJoined)
|
|
314
|
+
await opts.onJoined(socket, admission, join);
|
|
315
|
+
if (!conns.has(socket.id))
|
|
316
|
+
return;
|
|
317
|
+
try {
|
|
318
|
+
const stored = await chat.store.recentMessages(admission.roomId, opts.historyJoinLimit ?? CHAT_HISTORY_JOIN_LIMIT);
|
|
319
|
+
const who = await presentStored(admission.roomId, stored);
|
|
320
|
+
socket.emit('chat_history', { messages: stored.map((m, i) => toChatBroadcast(m, who[i] ?? { name: 'Someone', sprite: null })) });
|
|
321
|
+
}
|
|
322
|
+
catch (err) {
|
|
323
|
+
log('warn', 'room.history_failed', { sid: socket.id, room_id: admission.roomId, err_message: String(err) });
|
|
324
|
+
}
|
|
325
|
+
if (arrived.delete(admission.key) && announce && conns.has(socket.id)) {
|
|
326
|
+
await postLine(admission.roomId, memberOf(c), 'join', `${CHAT_NAME_TOKEN} joined`);
|
|
327
|
+
}
|
|
201
328
|
log('info', 'room.joined', { sid: socket.id, room_id: admission.roomId });
|
|
202
329
|
});
|
|
203
330
|
socket.on('time_ping', (payload) => {
|
|
@@ -208,6 +335,10 @@ export function serveRoom(io, opts) {
|
|
|
208
335
|
const c = conns.get(socket.id);
|
|
209
336
|
if (!c)
|
|
210
337
|
return refuse('auth/forbidden', 'join the room first');
|
|
338
|
+
if (opts.allowIdentity && !opts.allowIdentity(socket)) {
|
|
339
|
+
log('warn', 'identity.rate_limit', { sid: socket.id, client_id: socket.id });
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
211
342
|
const req = parseIdentityRequest(payload);
|
|
212
343
|
if (!req)
|
|
213
344
|
return refuse('payload/invalid', 'invalid identity_update');
|
|
@@ -216,9 +347,16 @@ export function serveRoom(io, opts) {
|
|
|
216
347
|
const accountId = c.admission.accountId;
|
|
217
348
|
if (accountId && opts.account && (req.name !== undefined || req.avatar)) {
|
|
218
349
|
await resolveAccount(accountId, socket, true);
|
|
219
|
-
if (accounts.get(accountId)?.name)
|
|
350
|
+
if (req.name !== undefined && accounts.get(accountId)?.name) {
|
|
351
|
+
// The account names them: the client's name is a stale copy. The
|
|
352
|
+
// roster answers with the real one, which the client adopts.
|
|
220
353
|
delete req.name;
|
|
354
|
+
sendPresence(c.admission.roomId);
|
|
355
|
+
}
|
|
221
356
|
}
|
|
357
|
+
if (req.name === undefined && req.sprite === undefined)
|
|
358
|
+
return;
|
|
359
|
+
const before = memberOf(c);
|
|
222
360
|
const decision = await decideIdentity(socket, c, req);
|
|
223
361
|
if ('error' in decision)
|
|
224
362
|
return refuse(decision.error.code, decision.error.message);
|
|
@@ -226,7 +364,18 @@ export function serveRoom(io, opts) {
|
|
|
226
364
|
c.override.name = decision.name;
|
|
227
365
|
if (decision.sprite !== undefined)
|
|
228
366
|
c.override.sprite = decision.sprite;
|
|
367
|
+
if (!conns.has(socket.id))
|
|
368
|
+
return;
|
|
369
|
+
const after = memberOf(c);
|
|
370
|
+
const nameChanged = after.name !== before.name;
|
|
371
|
+
const spriteChanged = after.sprite !== before.sprite;
|
|
372
|
+
if (!nameChanged && !spriteChanged)
|
|
373
|
+
return;
|
|
374
|
+
if (announce) {
|
|
375
|
+
await postLine(c.admission.roomId, after, 'identity_change', nameChanged ? `${CHAT_NAME_TOKEN} changed their name` : `${CHAT_NAME_TOKEN} changed character`);
|
|
376
|
+
}
|
|
229
377
|
sendPresence(c.admission.roomId);
|
|
378
|
+
log('info', 'identity_update', { room_id: c.admission.roomId, client_id: socket.id, name: after.name, sprite: after.sprite });
|
|
230
379
|
});
|
|
231
380
|
socket.on('chat_send', async (payload) => {
|
|
232
381
|
const c = conns.get(socket.id);
|
|
@@ -235,18 +384,19 @@ export function serveRoom(io, opts) {
|
|
|
235
384
|
// A rename made on another device shows on this line, not the next one.
|
|
236
385
|
if (c.admission.accountId)
|
|
237
386
|
await onAccountActivity(c.admission.accountId, socket);
|
|
238
|
-
const
|
|
239
|
-
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);
|
|
387
|
+
const outcome = await chat.send(c.admission.roomId, senderOf(memberOf(c)), payload);
|
|
240
388
|
if (!outcome.ok) {
|
|
241
389
|
log('warn', 'room.chat_refused', { sid: socket.id, room_id: c.admission.roomId, reason: outcome.reason });
|
|
242
|
-
return refuse(outcome.reason === 'rate_limited' ? 'rate/limited' : 'server/error',
|
|
390
|
+
return refuse(outcome.reason === 'rate_limited' ? 'rate/limited' : 'server/error', outcome.reason === 'rate_limited' ? 'chat rate limit' : outcome.reason === 'append_failed' ? 'chat append failed' : 'invalid chat');
|
|
243
391
|
}
|
|
244
392
|
broadcast(c.admission.roomId, outcome.broadcast);
|
|
393
|
+
opts.onChat?.(socket, c.admission, outcome.message);
|
|
245
394
|
});
|
|
246
|
-
socket.on('disconnect', () => {
|
|
395
|
+
socket.on('disconnect', (reason) => {
|
|
396
|
+
joining.delete(socket.id);
|
|
247
397
|
const c = conns.get(socket.id);
|
|
248
398
|
if (c)
|
|
249
|
-
|
|
399
|
+
leave(c, reason);
|
|
250
400
|
});
|
|
251
401
|
});
|
|
252
402
|
return {
|
|
@@ -262,6 +412,18 @@ export function serveRoom(io, opts) {
|
|
|
262
412
|
members,
|
|
263
413
|
refresh: sendPresence,
|
|
264
414
|
broadcast,
|
|
415
|
+
async post(roomId, line) {
|
|
416
|
+
const c = conns.get(line.clientId);
|
|
417
|
+
await postLine(roomId, c ? memberOf(c) : undefined, line.systemType, line.text);
|
|
418
|
+
},
|
|
419
|
+
connection(socketId) {
|
|
420
|
+
const c = conns.get(socketId);
|
|
421
|
+
return c ? { roomId: c.admission.roomId, key: c.admission.key, admission: c.admission } : undefined;
|
|
422
|
+
},
|
|
423
|
+
member(socketId) {
|
|
424
|
+
const c = conns.get(socketId);
|
|
425
|
+
return c ? memberOf(c) : undefined;
|
|
426
|
+
},
|
|
265
427
|
async refreshAccount(accountId) {
|
|
266
428
|
const c = [...conns.values()].find((x) => x.admission.accountId === accountId);
|
|
267
429
|
if (c)
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hadoku/rooms-server",
|
|
3
|
-
"version": "0.45.
|
|
4
|
-
"gitHead": "
|
|
3
|
+
"version": "0.45.68",
|
|
4
|
+
"gitHead": "1d2f3d1b8714baaa2525024d57ef5b43f48fb346",
|
|
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.",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"directory": "packages/rooms-server"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.
|
|
38
|
+
"@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@0.45.68"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
41
41
|
"socket.io": "^4.8.3"
|