@crowdedkingdoms/crowdyjs 18.39.1 → 18.40.0-test.1

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.
Files changed (50) hide show
  1. package/MIGRATION.md +62 -0
  2. package/README.md +420 -17
  3. package/dist/binary-wire.d.ts +94 -1
  4. package/dist/binary-wire.d.ts.map +1 -1
  5. package/dist/binary-wire.js +122 -20
  6. package/dist/crowdy-client.d.ts +7 -0
  7. package/dist/crowdy-client.d.ts.map +1 -1
  8. package/dist/crowdy-client.js +3 -0
  9. package/dist/default-origin.d.ts +6 -6
  10. package/dist/default-origin.js +6 -6
  11. package/dist/domains/admin.d.ts +7 -0
  12. package/dist/domains/admin.d.ts.map +1 -1
  13. package/dist/domains/admin.js +1 -0
  14. package/dist/domains/exec.d.ts +91 -3
  15. package/dist/domains/exec.d.ts.map +1 -1
  16. package/dist/domains/exec.js +132 -5
  17. package/dist/domains/fleetSessions.d.ts +87 -0
  18. package/dist/domains/fleetSessions.d.ts.map +1 -0
  19. package/dist/domains/fleetSessions.js +87 -0
  20. package/dist/dropped-read.d.ts +2 -1
  21. package/dist/dropped-read.d.ts.map +1 -1
  22. package/dist/dropped-read.js +2 -6
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +70 -0
  26. package/dist/fleet/index.d.ts +4 -0
  27. package/dist/fleet/index.d.ts.map +1 -0
  28. package/dist/fleet/index.js +21 -0
  29. package/dist/fleet/session.d.ts +730 -0
  30. package/dist/fleet/session.d.ts.map +1 -0
  31. package/dist/fleet/session.js +1376 -0
  32. package/dist/fleet/socket.d.ts +59 -0
  33. package/dist/fleet/socket.d.ts.map +1 -0
  34. package/dist/fleet/socket.js +111 -0
  35. package/dist/fleet-wire.d.ts +272 -0
  36. package/dist/fleet-wire.d.ts.map +1 -0
  37. package/dist/fleet-wire.js +472 -0
  38. package/dist/generated/graphql-schema.d.ts +176 -13
  39. package/dist/generated/graphql-schema.d.ts.map +1 -1
  40. package/dist/generated/graphql-schema.js +15 -3
  41. package/dist/generated/graphql.d.ts +79 -0
  42. package/dist/generated/graphql.d.ts.map +1 -1
  43. package/dist/generated/graphql.js +5 -0
  44. package/dist/index.d.ts +6 -3
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +7 -3
  47. package/dist/server-only.d.ts +54 -0
  48. package/dist/server-only.d.ts.map +1 -0
  49. package/dist/server-only.js +55 -0
  50. package/package.json +5 -1
@@ -0,0 +1,472 @@
1
+ /**
2
+ * Wire codecs for a fleet session (realtime servers v0.50.3): one realtime session an
3
+ * organization's game server opens for itself, in which it carries the players who are on it.
4
+ *
5
+ * Pure functions with no I/O: they build and read bytes and compute HMACs with WebCrypto, so
6
+ * they run in any JavaScript runtime. `FleetSession` (`@crowdedkingdoms/crowdyjs/fleet`) is
7
+ * the session that sends and receives them over UDP.
8
+ *
9
+ * **A fleet token signs for every player its session carries. It stays on a server the
10
+ * organization runs, beside the organization's org token, and never goes into a browser page
11
+ * or a game client.**
12
+ *
13
+ * What a game server sends:
14
+ *
15
+ * - **For a carried player**, the message that player's own session would send, with the
16
+ * tail's game token id the player's and the tail's HMAC keyed with the fleet token. Build
17
+ * it with the serializers in binary-wire.ts and {@link carriedPlayerContext}.
18
+ * - **Under the session's own game token id**, only `CLIENT_CAPABILITIES` (29),
19
+ * `FLEET_CARRY` (49), `FLEET_RELEASE` (50) and `CLIENT_ACTOR_HEARTBEAT` (26, with no actor).
20
+ *
21
+ * What it receives is read by {@link parseFleetDatagram}, which verifies before it returns:
22
+ * `FLEET_CARRY_RESULT` (51), `FLEET_RELEASED` (52) and `FLEET_DELIVERY` (53) in both of their
23
+ * forms, plain notifications, and the control frames that move or end the session.
24
+ *
25
+ * All numbers are little endian. Game token ids and user ids are 64-bit and are returned as
26
+ * decimal strings, as the Application API returns them.
27
+ */
28
+ import { CONTROL_NONCE_BYTES, createSignContext, HMAC_SIZE, parseNotification, serializeLongSpatial, SPATIAL_CONTAINS_AUTH_OFFSET, SPATIAL_HEADER_SIZE, TAIL_AUTH_BYTES, TAIL_NO_AUTH_BYTES, verifyControlHmac, verifyWithToken, WireMessageType, } from './binary-wire.js';
29
+ /**
30
+ * The largest datagram a fleet session is sent: a `FLEET_DELIVERY` with one player, alone,
31
+ * with its own HMAC. Nothing else the realtime servers send a client is above 1,232 bytes.
32
+ * Size receive buffers for this.
33
+ */
34
+ export const FLEET_MAX_DATAGRAM_BYTES = 1242;
35
+ /** The most players one `FLEET_DELIVERY` lists; more are split over frames. */
36
+ export const FLEET_MAX_DELIVERY_PLAYERS = 32;
37
+ /** A token, as its 64 octets: a fleet token and a player's app token alike. */
38
+ export const FLEET_TOKEN_CHARS = 64;
39
+ /** The ASCII label a `FLEET_CARRY` proof starts with (14 bytes). */
40
+ export const FLEET_CARRY_PROOF_LABEL = 'ck-fleet-carry';
41
+ /** A `FLEET_CARRY` whose time is further than this from the server's is refused (status 3). */
42
+ export const FLEET_CARRY_CLOCK_TOLERANCE_MS = 30000;
43
+ /** `FLEET_CARRY`'s app payload: `[8B player gameTokenId][8B epoch ms][32B proof]`. */
44
+ export const FLEET_CARRY_PAYLOAD_BYTES = 48;
45
+ /** `FLEET_CARRY_RESULT`: `[1B 51][8B player gameTokenId][8B user id][1B status]`. */
46
+ export const FLEET_CARRY_RESULT_BYTES = 18;
47
+ /** `FLEET_RELEASED`: `[1B 52][8B player gameTokenId][1B reason]`. */
48
+ export const FLEET_RELEASED_BYTES = 10;
49
+ /** `FLEET_CARRY_RESULT`'s status byte. Treat a value not listed as a refusal. */
50
+ export const FleetCarryStatus = {
51
+ /** The session carries the player; the result names their user id. */
52
+ CARRIED: 0,
53
+ /** No live token by that game token id (also: a token of another app). */
54
+ NO_LIVE_TOKEN: 1,
55
+ /** The token is another organization's player's. */
56
+ OTHER_ORGANIZATION: 2,
57
+ /** The proof or its time failed (also: a carry sent again after it ended, a replay). */
58
+ PROOF_FAILED: 3,
59
+ /** The session carries as many players as it may (also: the server has no place for it). */
60
+ SESSION_FULL: 4,
61
+ };
62
+ /** `FLEET_RELEASED`'s reason byte. Treat a value not listed as the carry having ended. */
63
+ export const FleetReleaseReason = {
64
+ /** Another session carries the player now: they moved to another of your servers. */
65
+ CARRIED_ELSEWHERE: 1,
66
+ /** The player's sign-in ended (revoked, or expired and not carried again with a live token). */
67
+ SIGN_IN_ENDED: 2,
68
+ /** No gameplay input from the player for the app's idle timeout. */
69
+ IDLE: 5,
70
+ };
71
+ /** `COMMAND_SESSION_RELEASED`'s reason byte. Treat a value not listed as `STALE`. */
72
+ export const SessionReleaseReason = {
73
+ DEAUTHORIZED: 0,
74
+ STALE: 1,
75
+ TOKEN_EXPIRED: 2,
76
+ OVERLOAD: 3,
77
+ REBALANCE: 4,
78
+ IDLE: 5,
79
+ };
80
+ const INT64_MIN = -(1n << 63n);
81
+ const INT64_MAX = (1n << 63n) - 1n;
82
+ /** `id` as the 64-bit integer the wire carries. */
83
+ function int64(id, what) {
84
+ let value;
85
+ try {
86
+ if (typeof id === 'number' && !Number.isSafeInteger(id))
87
+ throw new RangeError();
88
+ if (typeof id === 'string' && !/^-?\d+$/.test(id))
89
+ throw new RangeError();
90
+ value = BigInt(id);
91
+ }
92
+ catch {
93
+ throw new RangeError(`${what} must be a whole 64-bit number: ${String(id)}`);
94
+ }
95
+ if (value < INT64_MIN || value > INT64_MAX) {
96
+ throw new RangeError(`${what} must be a whole 64-bit number: ${String(id)}`);
97
+ }
98
+ return value;
99
+ }
100
+ function tokenOctets(token, what) {
101
+ if (typeof token !== 'string' || token.length !== FLEET_TOKEN_CHARS) {
102
+ throw new RangeError(`${what} must be ${FLEET_TOKEN_CHARS} characters`);
103
+ }
104
+ const bytes = new Uint8Array(FLEET_TOKEN_CHARS);
105
+ for (let i = 0; i < FLEET_TOKEN_CHARS; i += 1) {
106
+ const code = token.charCodeAt(i);
107
+ if (code > 0xff)
108
+ throw new RangeError(`${what} must be ${FLEET_TOKEN_CHARS} single-byte characters`);
109
+ bytes[i] = code;
110
+ }
111
+ return bytes;
112
+ }
113
+ // ---------------------------------------------------------------------------
114
+ // Signing
115
+ // ---------------------------------------------------------------------------
116
+ /**
117
+ * The fleet session's own signing context: its `gameTokenId` and its token (the 64 characters
118
+ * `openFleetSession` answered) as the HMAC key. It signs the session's own messages
119
+ * (29, 49, 50, 26), verifies everything the session is sent, and is what
120
+ * {@link carriedPlayerContext} derives a player's context from.
121
+ * @throws {RangeError} for a token that is not 64 characters or an id that is not a 64-bit number.
122
+ */
123
+ export async function createFleetSignContext(fleetGameTokenId, fleetToken) {
124
+ tokenOctets(fleetToken, 'the fleet token');
125
+ return createSignContext(int64(fleetGameTokenId, 'the fleet gameTokenId'), fleetToken);
126
+ }
127
+ /**
128
+ * The signing context for a message a fleet session sends for a carried player: the tail's
129
+ * game token id is the player's, and the HMAC is keyed with the fleet token. Pass it to any
130
+ * serializer in binary-wire.ts (`serializeActorUpdate`, `serializeVoxelUpdate`,
131
+ * `serializeClientEvent`, `serializeTextPacket`, `serializeAudioPacket`,
132
+ * `serializeVideoPacket`, `serializeClientMediaSpeakers`, `serializeActorHeartbeat`, the
133
+ * channel serializers) and the result is the message that player's own session would send,
134
+ * signed by the fleet session.
135
+ */
136
+ export function carriedPlayerContext(fleet, playerGameTokenId) {
137
+ return {
138
+ gameTokenId: int64(playerGameTokenId, 'the player gameTokenId'),
139
+ tokenBytes: fleet.tokenBytes,
140
+ key: fleet.key,
141
+ };
142
+ }
143
+ /**
144
+ * The proof inside a `FLEET_CARRY`: it shows the game server holds the player's token.
145
+ *
146
+ * ```
147
+ * HMAC-SHA256(key = the player's 64-octet token,
148
+ * "ck-fleet-carry" (14 ASCII bytes) || 8B fleet gameTokenId ||
149
+ * 8B player gameTokenId || 8B epoch ms)
150
+ * ```
151
+ */
152
+ export async function fleetCarryProof(input) {
153
+ const key = await crypto.subtle.importKey('raw', tokenOctets(input.playerToken, "the player's token"), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
154
+ const label = FLEET_CARRY_PROOF_LABEL.length;
155
+ const message = new Uint8Array(label + 24);
156
+ for (let i = 0; i < label; i += 1)
157
+ message[i] = FLEET_CARRY_PROOF_LABEL.charCodeAt(i);
158
+ const view = new DataView(message.buffer);
159
+ view.setBigInt64(label, int64(input.fleetGameTokenId, 'the fleet gameTokenId'), true);
160
+ view.setBigInt64(label + 8, int64(input.playerGameTokenId, 'the player gameTokenId'), true);
161
+ view.setBigInt64(label + 16, int64(input.epochMillis, 'epochMillis'), true);
162
+ return new Uint8Array(await crypto.subtle.sign('HMAC', key, message));
163
+ }
164
+ /**
165
+ * Build a `FLEET_CARRY` (49): "this session carries this player". The capabilities'
166
+ * long-spatial layout (chunk `(0,0,0)`, distance 0, no actor uuid) under the session's own
167
+ * game token id, with the app payload `[8B player gameTokenId][8B epoch ms][32B proof]`
168
+ * ({@link fleetCarryProof}). 157 bytes. The server answers `FLEET_CARRY_RESULT` (51), or
169
+ * nothing: send it again, with a new time and proof, until it does.
170
+ */
171
+ export async function serializeFleetCarry(fleet, input) {
172
+ const player = int64(input.playerGameTokenId, 'the player gameTokenId');
173
+ const epoch = int64(input.epochMillis, 'epochMillis');
174
+ const proof = await fleetCarryProof({
175
+ playerToken: input.playerToken,
176
+ fleetGameTokenId: fleet.gameTokenId,
177
+ playerGameTokenId: player,
178
+ epochMillis: epoch,
179
+ });
180
+ const payload = new Uint8Array(FLEET_CARRY_PAYLOAD_BYTES);
181
+ const view = new DataView(payload.buffer);
182
+ view.setBigInt64(0, player, true);
183
+ view.setBigInt64(8, epoch, true);
184
+ payload.set(proof, 16);
185
+ return serializeLongSpatial(fleet, WireMessageType.FLEET_CARRY, int64(input.appId, 'appId'), { x: 0, y: 0, z: 0 }, 0, 0, '', payload, input.sequenceNumber ?? 0);
186
+ }
187
+ /**
188
+ * Build a `FLEET_RELEASE` (50): "this player left the game". `FLEET_CARRY`'s layout with the
189
+ * app payload `[8B player gameTokenId]`. 117 bytes. The server sends no answer, and sending
190
+ * it again changes nothing. The player's actors leave as when a player's own session ends.
191
+ */
192
+ export async function serializeFleetRelease(fleet, input) {
193
+ const payload = new Uint8Array(8);
194
+ new DataView(payload.buffer).setBigInt64(0, int64(input.playerGameTokenId, 'the player gameTokenId'), true);
195
+ return serializeLongSpatial(fleet, WireMessageType.FLEET_RELEASE, int64(input.appId, 'appId'), { x: 0, y: 0, z: 0 }, 0, 0, '', payload, input.sequenceNumber ?? 0);
196
+ }
197
+ function view(bytes) {
198
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
199
+ }
200
+ /**
201
+ * Read a `FLEET_CARRY_RESULT` (51) frame, `[1B 51][8B player gameTokenId][8B user id]
202
+ * [1B status]`, without its HMAC. `null` for a frame that is not one. This does not verify:
203
+ * {@link parseFleetDatagram} does.
204
+ */
205
+ export function parseFleetCarryResult(frame) {
206
+ if (frame.length < FLEET_CARRY_RESULT_BYTES || frame[0] !== WireMessageType.FLEET_CARRY_RESULT) {
207
+ return null;
208
+ }
209
+ const v = view(frame);
210
+ return {
211
+ playerGameTokenId: v.getBigInt64(1, true).toString(),
212
+ userId: v.getBigInt64(9, true).toString(),
213
+ status: frame[17],
214
+ };
215
+ }
216
+ /**
217
+ * Read a `FLEET_RELEASED` (52) frame, `[1B 52][8B player gameTokenId][1B reason]`, without
218
+ * its HMAC. `null` for a frame that is not one. This does not verify.
219
+ */
220
+ export function parseFleetReleased(frame) {
221
+ if (frame.length < FLEET_RELEASED_BYTES || frame[0] !== WireMessageType.FLEET_RELEASED) {
222
+ return null;
223
+ }
224
+ return { playerGameTokenId: view(frame).getBigInt64(1, true).toString(), reason: frame[9] };
225
+ }
226
+ /**
227
+ * Read a `FLEET_DELIVERY` (53) frame, `[1B 53][1B count][count x 8B player gameTokenId]
228
+ * [notification]`, without its HMAC, and unwrap the notification inside into the object the
229
+ * SDK's parsers produce. The notification is what a player's own session would have been
230
+ * sent, unsigned: a long-spatial one with its 9-byte tail and `containsAuth` 0, or a channel
231
+ * one (18 or 36). `null` for a count of 0 or above 32, a frame shorter than its count says,
232
+ * and a frame whose contents are not a notification that can be read. This does not verify.
233
+ */
234
+ export function parseFleetDelivery(frame) {
235
+ if (frame.length < 2 || frame[0] !== WireMessageType.FLEET_DELIVERY)
236
+ return null;
237
+ const count = frame[1];
238
+ if (count === 0 || count > FLEET_MAX_DELIVERY_PLAYERS)
239
+ return null;
240
+ const listEnd = 2 + count * 8;
241
+ if (frame.length <= listEnd)
242
+ return null;
243
+ const inner = frame.subarray(listEnd);
244
+ const type = inner[0];
245
+ const channel = type === WireMessageType.CHANNEL_MESSAGE_NOTIFICATION ||
246
+ type === WireMessageType.CHANNEL_AUDIO_NOTIFICATION;
247
+ // A notification only: never an error frame, a control frame or another delivery.
248
+ if (!channel && (type & 0x80) === 0)
249
+ return null;
250
+ if (!channel && inner.length < SPATIAL_HEADER_SIZE + TAIL_NO_AUTH_BYTES)
251
+ return null;
252
+ const notification = parseNotification(inner);
253
+ if (!notification)
254
+ return null;
255
+ const v = view(frame);
256
+ const players = [];
257
+ for (let i = 0; i < count; i += 1)
258
+ players.push(v.getBigInt64(2 + i * 8, true).toString());
259
+ return { players, notification };
260
+ }
261
+ function sameBytes(a, b) {
262
+ if (a.length !== b.length)
263
+ return false;
264
+ let diff = 0;
265
+ for (let i = 0; i < a.length; i += 1)
266
+ diff |= a[i] ^ b[i];
267
+ return diff === 0;
268
+ }
269
+ /**
270
+ * Read one datagram a fleet session was sent, verifying everything in it with the fleet
271
+ * token before returning it. A frame that fails is dropped and counted, never returned.
272
+ *
273
+ * - **`MESSAGE_BUNDLE_SIGNED` (30)**, sent to a session that advertised `BUNDLE_SIGNED`: one
274
+ * HMAC over the datagram, checked once. Its members, 51 to 53 among them, carry none.
275
+ * - **51, 52 and 53 anywhere else** (alone in the datagram, or a member of a
276
+ * `MESSAGE_BUNDLE`, 2): each is followed by its own HMAC, its last 32 bytes:
277
+ * `HMAC-SHA256(key = the fleet token, message = every byte before the HMAC || the fleet
278
+ * token)`. A session that advertised `BUNDLE_SIGNED` is still sent a `FLEET_DELIVERY` above
279
+ * 1,197 bytes this way, alone, so every session reads both forms.
280
+ * - **A plain long-spatial notification** outside a signed bundle carries its own HMAC
281
+ * (`containsAuth` 1) and is checked with it. One with no signature is dropped and counted
282
+ * (`unsigned`).
283
+ * - **An error frame** (`[3][seq][code]`) has no room for an HMAC. It is returned either way,
284
+ * marked `verified` only when it was a member of a signed bundle.
285
+ * - **Control frames** (22, 28, 44, 45, 46) are always their own datagram, signed over their
286
+ * leading bytes.
287
+ *
288
+ * `fleet` is the session's own context ({@link createFleetSignContext}). A datagram above
289
+ * {@link FLEET_MAX_DATAGRAM_BYTES} is malformed.
290
+ */
291
+ export async function parseFleetDatagram(fleet, datagram, options = {}) {
292
+ const out = { messages: [], hmacFailures: 0, malformed: 0, unsigned: 0, staleControl: 0 };
293
+ if (datagram.length === 0 || datagram.length > FLEET_MAX_DATAGRAM_BYTES) {
294
+ out.malformed += 1;
295
+ return out;
296
+ }
297
+ const type = datagram[0];
298
+ if (type === WireMessageType.COMMAND_RECONNECT ||
299
+ type === WireMessageType.COMMAND_SESSION_RELEASED ||
300
+ type === WireMessageType.COMMAND_RECONNECT_BOUND ||
301
+ type === WireMessageType.COMMAND_SESSION_RELEASED_BOUND ||
302
+ type === WireMessageType.CONTROL_BOUND_ACK) {
303
+ await readControl(fleet, datagram, options, out);
304
+ return out;
305
+ }
306
+ if (type === WireMessageType.MESSAGE_BUNDLE_SIGNED) {
307
+ if (datagram.length <= 1 + HMAC_SIZE) {
308
+ out.malformed += 1;
309
+ return out;
310
+ }
311
+ const end = datagram.length - HMAC_SIZE;
312
+ if (!(await verifyWithToken(fleet, datagram.subarray(0, end), datagram.subarray(end)))) {
313
+ out.hmacFailures += 1;
314
+ return out;
315
+ }
316
+ for (const member of bundleMembers(datagram, end, out)) {
317
+ await readMember(fleet, member, true, out);
318
+ }
319
+ return out;
320
+ }
321
+ if (type === WireMessageType.MESSAGE_BUNDLE) {
322
+ for (const member of bundleMembers(datagram, datagram.length, out)) {
323
+ await readMember(fleet, member, false, out);
324
+ }
325
+ return out;
326
+ }
327
+ await readMember(fleet, datagram, false, out);
328
+ return out;
329
+ }
330
+ /** The members of `[1B type]{[2B u16 length][member]}…` up to `end`. A truncated one ends the walk. */
331
+ function bundleMembers(bytes, end, out) {
332
+ const v = view(bytes);
333
+ const members = [];
334
+ let off = 1;
335
+ while (off < end) {
336
+ if (off + 2 > end) {
337
+ out.malformed += 1;
338
+ break;
339
+ }
340
+ const len = v.getUint16(off, true);
341
+ off += 2;
342
+ if (len === 0 || off + len > end) {
343
+ out.malformed += 1;
344
+ break;
345
+ }
346
+ members.push(bytes.subarray(off, off + len));
347
+ off += len;
348
+ }
349
+ return members;
350
+ }
351
+ async function readControl(fleet, datagram, options, out) {
352
+ const type = datagram[0];
353
+ const bound = type !== WireMessageType.COMMAND_RECONNECT && type !== WireMessageType.COMMAND_SESSION_RELEASED;
354
+ const released = type === WireMessageType.COMMAND_SESSION_RELEASED ||
355
+ type === WireMessageType.COMMAND_SESSION_RELEASED_BOUND;
356
+ // [type][reason, for a release][nonce, for a bound form] then the HMAC over those bytes.
357
+ const signedLen = 1 + (released ? 1 : 0) + (bound ? CONTROL_NONCE_BYTES : 0);
358
+ if (datagram.length !== signedLen + HMAC_SIZE) {
359
+ out.malformed += 1;
360
+ return;
361
+ }
362
+ if (!(await verifyControlHmac(fleet, datagram.subarray(0, signedLen), datagram.subarray(signedLen)))) {
363
+ out.hmacFailures += 1;
364
+ return;
365
+ }
366
+ if (bound) {
367
+ const nonce = datagram.subarray(signedLen - CONTROL_NONCE_BYTES, signedLen);
368
+ if (!options.controlNonce || !sameBytes(nonce, options.controlNonce)) {
369
+ out.staleControl += 1;
370
+ return;
371
+ }
372
+ }
373
+ if (type === WireMessageType.CONTROL_BOUND_ACK)
374
+ out.messages.push({ kind: 'controlBoundAck' });
375
+ else if (released)
376
+ out.messages.push({ kind: 'sessionReleased', reason: datagram[1], bound });
377
+ else
378
+ out.messages.push({ kind: 'reconnect', bound });
379
+ }
380
+ /**
381
+ * One complete message: a member of a bundle, or a datagram that is not a bundle.
382
+ * `inSignedBundle` says the bundle's own HMAC already vouched for it.
383
+ */
384
+ async function readMember(fleet, message, inSignedBundle, out) {
385
+ const type = message[0];
386
+ if (type === WireMessageType.FLEET_CARRY_RESULT ||
387
+ type === WireMessageType.FLEET_RELEASED ||
388
+ type === WireMessageType.FLEET_DELIVERY) {
389
+ let frame = message;
390
+ if (!inSignedBundle) {
391
+ // Its own HMAC: the last 32 bytes, over every byte before them and then the token. A
392
+ // frame too short to hold one came without it.
393
+ if (message.length <= HMAC_SIZE) {
394
+ out.hmacFailures += 1;
395
+ return;
396
+ }
397
+ const end = message.length - HMAC_SIZE;
398
+ frame = message.subarray(0, end);
399
+ if (!(await verifyWithToken(fleet, frame, message.subarray(end)))) {
400
+ out.hmacFailures += 1;
401
+ return;
402
+ }
403
+ }
404
+ if (type === WireMessageType.FLEET_CARRY_RESULT) {
405
+ const result = parseFleetCarryResult(frame);
406
+ if (result)
407
+ out.messages.push({ kind: 'carryResult', ...result });
408
+ else
409
+ out.malformed += 1;
410
+ }
411
+ else if (type === WireMessageType.FLEET_RELEASED) {
412
+ const released = parseFleetReleased(frame);
413
+ if (released)
414
+ out.messages.push({ kind: 'released', ...released });
415
+ else
416
+ out.malformed += 1;
417
+ }
418
+ else {
419
+ const delivery = parseFleetDelivery(frame);
420
+ if (delivery)
421
+ out.messages.push({ kind: 'delivery', ...delivery });
422
+ else
423
+ out.malformed += 1;
424
+ }
425
+ return;
426
+ }
427
+ if (type === WireMessageType.GENERIC_ERROR_MESSAGE) {
428
+ // [3][seq][code] has no room for an HMAC: it is as good as the bundle it came in, and a
429
+ // caller is told which (`verified`).
430
+ const error = parseNotification(message);
431
+ if (error)
432
+ out.messages.push({ kind: 'notification', notification: error, verified: inSignedBundle });
433
+ else
434
+ out.malformed += 1;
435
+ return;
436
+ }
437
+ const channel = type === WireMessageType.CHANNEL_MESSAGE_NOTIFICATION ||
438
+ type === WireMessageType.CHANNEL_AUDIO_NOTIFICATION;
439
+ if (!channel && (type & 0x80) === 0)
440
+ return; // not a notification: nothing a session reads
441
+ let verified = inSignedBundle;
442
+ if (!channel) {
443
+ if (message.length < SPATIAL_HEADER_SIZE + TAIL_NO_AUTH_BYTES) {
444
+ out.malformed += 1;
445
+ return;
446
+ }
447
+ if (message[SPATIAL_CONTAINS_AUTH_OFFSET] !== 0) {
448
+ // Its own HMAC sits before the 9-byte tail, over the header and the payload.
449
+ if (message.length < SPATIAL_HEADER_SIZE + TAIL_AUTH_BYTES) {
450
+ out.malformed += 1;
451
+ return;
452
+ }
453
+ const prefix = message.length - TAIL_AUTH_BYTES;
454
+ const tag = message.subarray(prefix, prefix + HMAC_SIZE);
455
+ if (!(await verifyWithToken(fleet, message.subarray(0, prefix), tag))) {
456
+ out.hmacFailures += 1;
457
+ return;
458
+ }
459
+ verified = true;
460
+ }
461
+ }
462
+ if (!verified) {
463
+ out.unsigned += 1;
464
+ return;
465
+ }
466
+ const notification = parseNotification(message);
467
+ if (notification)
468
+ out.messages.push({ kind: 'notification', notification, verified });
469
+ else if (channel)
470
+ out.malformed += 1;
471
+ // An unknown spatial type is skipped: the protocol grows by adding types.
472
+ }