serverless-ircd 0.4.0 → 0.5.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.
Files changed (124) hide show
  1. package/CHANGELOG.md +175 -0
  2. package/README.md +88 -19
  3. package/apps/aws-stack/README.md +4 -3
  4. package/apps/aws-stack/package.json +1 -1
  5. package/apps/aws-stack/src/aws-stack.ts +32 -4
  6. package/apps/aws-stack/tests/stack.test.ts +47 -1
  7. package/apps/cf-tcp-container/package.json +1 -1
  8. package/apps/cf-worker/package.json +1 -1
  9. package/apps/local-cli/package.json +1 -1
  10. package/apps/local-cli/src/server.ts +129 -21
  11. package/apps/local-cli/tests/e2e.test.ts +1 -1
  12. package/apps/local-cli/tests/ws-subprotocol.test.ts +257 -0
  13. package/package.json +2 -2
  14. package/packages/aws-adapter/package.json +1 -1
  15. package/packages/aws-adapter/src/aws-runtime.ts +69 -0
  16. package/packages/aws-adapter/src/handlers/connect.ts +36 -5
  17. package/packages/aws-adapter/src/handlers/default.ts +63 -5
  18. package/packages/aws-adapter/src/handlers/index.ts +41 -2
  19. package/packages/aws-adapter/src/handlers/nlb-stream.ts +9 -0
  20. package/packages/aws-adapter/src/index.ts +2 -0
  21. package/packages/aws-adapter/src/serialize.ts +11 -1
  22. package/packages/aws-adapter/src/stats.ts +80 -0
  23. package/packages/aws-adapter/tests/aws-integration.test.ts +1 -1
  24. package/packages/aws-adapter/tests/aws-runtime.test.ts +61 -0
  25. package/packages/aws-adapter/tests/connect.test.ts +97 -1
  26. package/packages/aws-adapter/tests/handlers.test.ts +148 -0
  27. package/packages/aws-adapter/tests/nlb-stream.test.ts +2 -0
  28. package/packages/aws-adapter/tests/stats.test.ts +317 -0
  29. package/packages/cf-adapter/package.json +5 -1
  30. package/packages/cf-adapter/src/cf-runtime.ts +66 -1
  31. package/packages/cf-adapter/src/channel-do.ts +2 -2
  32. package/packages/cf-adapter/src/connection-do.ts +182 -54
  33. package/packages/cf-adapter/src/env.ts +25 -6
  34. package/packages/cf-adapter/src/index.ts +2 -0
  35. package/packages/cf-adapter/src/registry-do.ts +22 -3
  36. package/packages/cf-adapter/src/sharding.ts +1 -2
  37. package/packages/cf-adapter/src/stats.ts +65 -0
  38. package/packages/cf-adapter/tests/cf-harness.ts +1 -1
  39. package/packages/cf-adapter/tests/cf-integration.test.ts +4 -4
  40. package/packages/cf-adapter/tests/cf-runtime.test.ts +38 -2
  41. package/packages/cf-adapter/tests/channel-do.test.ts +2 -2
  42. package/packages/cf-adapter/tests/connection-do-channel-registration.test.ts +2 -2
  43. package/packages/cf-adapter/tests/connection-do-no-batching-reservation.test.ts +2 -2
  44. package/packages/cf-adapter/tests/connection-do-ws-spec-contract.test.ts +289 -0
  45. package/packages/cf-adapter/tests/connection-do-ws-subprotocol.test.ts +184 -0
  46. package/packages/cf-adapter/tests/connection-do.test.ts +27 -2
  47. package/packages/cf-adapter/tests/registry-do.test.ts +4 -4
  48. package/packages/cf-adapter/tests/sharding.test.ts +1 -1
  49. package/packages/cf-adapter/tests/stats.test.ts +120 -0
  50. package/packages/cf-adapter/tests/worker/main.ts +7 -7
  51. package/packages/cf-adapter/tests/worker/stubs/channel-stub.ts +2 -2
  52. package/packages/cf-adapter/tests/worker/stubs/registry-stub.ts +8 -2
  53. package/packages/cf-adapter/wrangler.test.toml +7 -0
  54. package/packages/in-memory-runtime/package.json +1 -1
  55. package/packages/in-memory-runtime/src/in-memory-runtime.ts +39 -0
  56. package/packages/in-memory-runtime/tests/in-memory-runtime.test.ts +259 -0
  57. package/packages/irc-core/package.json +1 -1
  58. package/packages/irc-core/src/admission.ts +16 -15
  59. package/packages/irc-core/src/caps/capabilities.ts +1 -1
  60. package/packages/irc-core/src/commands/index.ts +8 -0
  61. package/packages/irc-core/src/commands/invite.ts +2 -4
  62. package/packages/irc-core/src/commands/isupport.ts +6 -2
  63. package/packages/irc-core/src/commands/kick.ts +2 -4
  64. package/packages/irc-core/src/commands/kill.ts +127 -0
  65. package/packages/irc-core/src/commands/list.ts +1 -1
  66. package/packages/irc-core/src/commands/lusers.ts +204 -0
  67. package/packages/irc-core/src/commands/mode.ts +4 -8
  68. package/packages/irc-core/src/commands/names.ts +3 -5
  69. package/packages/irc-core/src/commands/part.ts +2 -4
  70. package/packages/irc-core/src/commands/rehash.ts +119 -0
  71. package/packages/irc-core/src/commands/setname.ts +109 -0
  72. package/packages/irc-core/src/commands/stats.ts +152 -0
  73. package/packages/irc-core/src/commands/topic.ts +2 -4
  74. package/packages/irc-core/src/commands/trace.ts +137 -0
  75. package/packages/irc-core/src/commands/wallops.ts +118 -0
  76. package/packages/irc-core/src/config.ts +7 -0
  77. package/packages/irc-core/src/effects.ts +27 -1
  78. package/packages/irc-core/src/index.ts +2 -0
  79. package/packages/irc-core/src/ports.ts +179 -0
  80. package/packages/irc-core/src/protocol/numerics.ts +42 -11
  81. package/packages/irc-core/src/protocol/outbound.ts +20 -3
  82. package/packages/irc-core/src/types.ts +8 -1
  83. package/packages/irc-core/src/ws-framing.ts +132 -0
  84. package/packages/irc-core/src/ws-subprotocol.ts +66 -0
  85. package/packages/irc-core/tests/admission.test.ts +18 -0
  86. package/packages/irc-core/tests/commands/kill.test.ts +243 -0
  87. package/packages/irc-core/tests/commands/lusers.test.ts +368 -0
  88. package/packages/irc-core/tests/commands/mode.test.ts +57 -0
  89. package/packages/irc-core/tests/commands/rehash.test.ts +171 -0
  90. package/packages/irc-core/tests/commands/setname.test.ts +225 -0
  91. package/packages/irc-core/tests/commands/stats.test.ts +294 -0
  92. package/packages/irc-core/tests/commands/trace.test.ts +282 -0
  93. package/packages/irc-core/tests/commands/wallops.test.ts +231 -0
  94. package/packages/irc-core/tests/dropped-s2s-and-obsolete-verbs.test.ts +90 -0
  95. package/packages/irc-core/tests/effects.test.ts +14 -0
  96. package/packages/irc-core/tests/numerics.test.ts +90 -0
  97. package/packages/irc-core/tests/outbound.test.ts +51 -0
  98. package/packages/irc-core/tests/ports.test.ts +22 -0
  99. package/packages/irc-core/tests/raw-modules.d.ts +11 -0
  100. package/packages/irc-core/tests/stats-store.test.ts +222 -0
  101. package/packages/irc-core/tests/ws-framing.test.ts +213 -0
  102. package/packages/irc-core/tests/ws-subprotocol.test.ts +111 -0
  103. package/packages/irc-server/package.json +1 -1
  104. package/packages/irc-server/src/actor.ts +249 -16
  105. package/packages/irc-server/src/dispatch.ts +1 -0
  106. package/packages/irc-server/src/routing.ts +3 -0
  107. package/packages/irc-server/src/runtime.ts +31 -0
  108. package/packages/irc-server/src/transport.ts +10 -7
  109. package/packages/irc-server/tests/actor.test.ts +1089 -1
  110. package/packages/irc-server/tests/dispatch.test.ts +37 -0
  111. package/packages/irc-server/tests/raw-modules.d.ts +11 -0
  112. package/packages/irc-server/tests/routing.test.ts +1 -0
  113. package/packages/irc-server/tests/runtime.test.ts +7 -0
  114. package/packages/irc-test-support/package.json +1 -1
  115. package/packages/irc-test-support/src/scenarios.ts +9 -1
  116. package/packages/irc-test-support/tests/in-memory-scenarios.test.ts +1 -1
  117. package/pnpm-workspace.yaml +1 -0
  118. package/tools/ci-hardening/package.json +1 -1
  119. package/tools/package.json +6 -1
  120. package/tools/seed-cf-accounts.ts +4 -1
  121. package/tools/tcp-ws-forwarder/package.json +1 -1
  122. package/tools/tcp-ws-forwarder/src/forwarder.ts +57 -9
  123. package/tools/tcp-ws-forwarder/tests/forwarder.test.ts +34 -1
  124. package/tools/tcp-ws-forwarder/tests/framing.test.ts +65 -1
@@ -31,6 +31,68 @@ describe('Numerics registry', () => {
31
31
  expect(Numerics.RPL_ENDOFWHOWAS).toBe(369);
32
32
  });
33
33
 
34
+ it('maps RPL_TRACELINK to 200', () => {
35
+ expect(Numerics.RPL_TRACELINK).toBe(200);
36
+ });
37
+
38
+ it('maps RPL_TRACEOPERATOR to 204', () => {
39
+ expect(Numerics.RPL_TRACEOPERATOR).toBe(204);
40
+ });
41
+
42
+ it('maps RPL_TRACEUSER to 205', () => {
43
+ expect(Numerics.RPL_TRACEUSER).toBe(205);
44
+ });
45
+
46
+ it('maps RPL_TRACESERVER to 206', () => {
47
+ expect(Numerics.RPL_TRACESERVER).toBe(206);
48
+ });
49
+
50
+ it('maps RPL_ENDOFTRACE to 262', () => {
51
+ expect(Numerics.RPL_ENDOFTRACE).toBe(262);
52
+ });
53
+
54
+ // -- LUSERS (RFC 2812 §4.6.2) ----------------------------------------------
55
+ it('maps RPL_LUSERCLIENT to 251', () => {
56
+ expect(Numerics.RPL_LUSERCLIENT).toBe(251);
57
+ });
58
+
59
+ it('maps RPL_LUSEROP to 252', () => {
60
+ expect(Numerics.RPL_LUSEROP).toBe(252);
61
+ });
62
+
63
+ it('maps RPL_LUSERUNKNOWN to 253', () => {
64
+ expect(Numerics.RPL_LUSERUNKNOWN).toBe(253);
65
+ });
66
+
67
+ it('maps RPL_LUSERCHANNELS to 254', () => {
68
+ expect(Numerics.RPL_LUSERCHANNELS).toBe(254);
69
+ });
70
+
71
+ it('maps RPL_LUSERME to 255', () => {
72
+ expect(Numerics.RPL_LUSERME).toBe(255);
73
+ });
74
+
75
+ it('maps RPL_LOCALUSERS to 265', () => {
76
+ expect(Numerics.RPL_LOCALUSERS).toBe(265);
77
+ });
78
+
79
+ it('maps RPL_GLOBALUSERS to 266', () => {
80
+ expect(Numerics.RPL_GLOBALUSERS).toBe(266);
81
+ });
82
+
83
+ // -- STATS (RFC 2812 §4.6.3) -----------------------------------------------
84
+ it('maps RPL_STATSLINKINFO to 211', () => {
85
+ expect(Numerics.RPL_STATSLINKINFO).toBe(211);
86
+ });
87
+
88
+ it('maps RPL_ENDOFSTATS to 219', () => {
89
+ expect(Numerics.RPL_ENDOFSTATS).toBe(219);
90
+ });
91
+
92
+ it('maps RPL_STATSUPTIME to 242', () => {
93
+ expect(Numerics.RPL_STATSUPTIME).toBe(242);
94
+ });
95
+
34
96
  it('maps ERR_WASNOSUCHNICK to 406', () => {
35
97
  expect(Numerics.ERR_WASNOSUCHNICK).toBe(406);
36
98
  });
@@ -77,6 +139,26 @@ describe('numericToName', () => {
77
139
  expect(numericToName.get(1)).toBe('RPL_WELCOME');
78
140
  });
79
141
 
142
+ it('reverses RPL_LUSERCLIENT', () => {
143
+ expect(numericToName.get(251)).toBe('RPL_LUSERCLIENT');
144
+ });
145
+
146
+ it('reverses RPL_GLOBALUSERS', () => {
147
+ expect(numericToName.get(266)).toBe('RPL_GLOBALUSERS');
148
+ });
149
+
150
+ it('reverses RPL_STATSLINKINFO', () => {
151
+ expect(numericToName.get(211)).toBe('RPL_STATSLINKINFO');
152
+ });
153
+
154
+ it('reverses RPL_ENDOFSTATS', () => {
155
+ expect(numericToName.get(219)).toBe('RPL_ENDOFSTATS');
156
+ });
157
+
158
+ it('reverses RPL_STATSUPTIME', () => {
159
+ expect(numericToName.get(242)).toBe('RPL_STATSUPTIME');
160
+ });
161
+
80
162
  it('returns undefined for an unregistered code', () => {
81
163
  expect(numericToName.get(600)).toBeUndefined();
82
164
  });
@@ -107,4 +189,12 @@ describe('formatNumeric', () => {
107
189
  it('zero-pads RPL_ISUPPORT', () => {
108
190
  expect(formatNumeric('RPL_ISUPPORT')).toBe('005');
109
191
  });
192
+
193
+ it('formats RPL_LUSERCLIENT as 251', () => {
194
+ expect(formatNumeric('RPL_LUSERCLIENT')).toBe('251');
195
+ });
196
+
197
+ it('formats RPL_ENDOFSTATS as 219', () => {
198
+ expect(formatNumeric('RPL_ENDOFSTATS')).toBe('219');
199
+ });
110
200
  });
@@ -9,6 +9,7 @@ import {
9
9
  } from '../src/protocol/outbound';
10
10
  import { parse } from '../src/protocol/parser';
11
11
  import { serialize } from '../src/protocol/serializer';
12
+ import { MAX_WS_MESSAGE_BYTES } from '../src/ws-framing';
12
13
 
13
14
  const L = (text: string): RawLine => ({ text });
14
15
 
@@ -192,6 +193,56 @@ describe('enforceLineLimit', () => {
192
193
  });
193
194
  });
194
195
 
196
+ // ============================================================================
197
+ // enforceLineLimit — budget-aware optional WsFrameMode parameter
198
+ // ============================================================================
199
+
200
+ describe('enforceLineLimit — WsFrameMode budget', () => {
201
+ // The optional `mode` parameter selects the byte budget. Spec modes cap at
202
+ // MAX_WS_MESSAGE_BYTES (510) directly — there is no trailing CRLF on a WS
203
+ // message. Legacy mode caps at MAX_LINE_BYTES - 2 (512 - 2 = 510). Both
204
+ // resolve to 510 today, but the API is mode-aware so a future change to
205
+ // either constant needs no call-site edits.
206
+ const SPEC_BUDGET = MAX_WS_MESSAGE_BYTES;
207
+
208
+ it('accepts an optional spec-text mode and caps at MAX_WS_MESSAGE_BYTES', () => {
209
+ const exact: RawLine = L('x'.repeat(SPEC_BUDGET));
210
+ expect(enforceLineLimit(exact, new Set<string>(), 'spec-text')).toBe(exact);
211
+
212
+ const tooLong: RawLine = L('x'.repeat(SPEC_BUDGET + 5));
213
+ const out = enforceLineLimit(tooLong, new Set<string>(), 'spec-text');
214
+ expect(out.text.length).toBe(SPEC_BUDGET);
215
+ });
216
+
217
+ it('accepts an optional spec-binary mode and caps at MAX_WS_MESSAGE_BYTES', () => {
218
+ const tooLong: RawLine = L('x'.repeat(SPEC_BUDGET + 5));
219
+ const out = enforceLineLimit(tooLong, new Set<string>(), 'spec-binary');
220
+ expect(out.text.length).toBe(SPEC_BUDGET);
221
+ });
222
+
223
+ it('uses the legacy budget when mode is explicitly "legacy"', () => {
224
+ const tooLong: RawLine = L('x'.repeat(SPEC_BUDGET + 5));
225
+ const out = enforceLineLimit(tooLong, new Set<string>(), 'legacy');
226
+ expect(out.text.length).toBe(SPEC_BUDGET);
227
+ });
228
+
229
+ it('omitting mode defaults to the legacy budget (backward compatible)', () => {
230
+ const tooLong: RawLine = L('x'.repeat(SPEC_BUDGET + 5));
231
+ const withDefault = enforceLineLimit(tooLong, new Set<string>());
232
+ const withLegacy = enforceLineLimit(tooLong, new Set<string>(), 'legacy');
233
+ expect(withDefault).toEqual(withLegacy);
234
+ });
235
+
236
+ it('preserves the tag section in spec-text mode just as in legacy mode', () => {
237
+ const tagPrefix = '@time=2024-01-15T12:34:56.789Z ';
238
+ const body = `:alice PRIVMSG #foo :${'x'.repeat(500)}`;
239
+ const line: RawLine = L(`${tagPrefix}${body}`);
240
+ const out = enforceLineLimit(line, new Set<string>(['message-tags']), 'spec-text');
241
+ expect(out.text.length).toBe(SPEC_BUDGET);
242
+ expect(out.text.startsWith(tagPrefix)).toBe(true);
243
+ });
244
+ });
245
+
195
246
  // ============================================================================
196
247
  // Round-trip through serialize -> applyServerTime -> parse
197
248
  // ============================================================================
@@ -5,6 +5,7 @@ import {
5
5
  ConsoleLogger,
6
6
  FakeClock,
7
7
  type IdFactory,
8
+ InMemoryMtlsIdentityProvider,
8
9
  LogLevel,
9
10
  type LogRecord,
10
11
  type Logger,
@@ -362,3 +363,24 @@ const _assertLogRecord: LogRecord = {
362
363
  msg: '',
363
364
  };
364
365
  void _assertLogRecord;
366
+
367
+ describe('InMemoryMtlsIdentityProvider', () => {
368
+ it('returns the certificate subject for a known connection id', () => {
369
+ const provider = new InMemoryMtlsIdentityProvider([
370
+ { connId: 'c1', identity: 'CN=alice' },
371
+ { connId: 'c2', identity: 'CN=bob' },
372
+ ]);
373
+ expect(provider.getIdentity('c1')).toBe('CN=alice');
374
+ expect(provider.getIdentity('c2')).toBe('CN=bob');
375
+ });
376
+
377
+ it('returns undefined for an unknown connection id', () => {
378
+ const provider = new InMemoryMtlsIdentityProvider([{ connId: 'c1', identity: 'CN=alice' }]);
379
+ expect(provider.getIdentity('nope')).toBeUndefined();
380
+ });
381
+
382
+ it('handles an empty identity table', () => {
383
+ const provider = new InMemoryMtlsIdentityProvider([]);
384
+ expect(provider.getIdentity('c1')).toBeUndefined();
385
+ });
386
+ });
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Ambient declaration so `?raw` imports (Vite's built-in transform that
3
+ * inlines a file's text at bundle time) typecheck under the strict
4
+ * `tsconfig.test.json`. Used by source-level regression guards that
5
+ * assert removed numerics stay removed.
6
+ */
7
+ declare module '*?raw' {
8
+ const content: string;
9
+ // eslint-disable-next-line import/no-default-export
10
+ export default content;
11
+ }
@@ -0,0 +1,222 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ FakeClock,
4
+ InMemoryStats,
5
+ type ServerStats,
6
+ type ServerStatsSnapshot,
7
+ computeStatsSnapshot,
8
+ } from '../src/ports';
9
+ import type { ChannelState } from '../src/state/channel';
10
+ import { createChannel } from '../src/state/channel';
11
+ import type { ConnId, ConnectionState } from '../src/state/connection';
12
+ import { createConnection } from '../src/state/connection';
13
+
14
+ /** Builds a registered connection with the supplied modes. */
15
+ function makeConn(
16
+ id: ConnId,
17
+ opts: { oper?: boolean; invisible?: boolean; registered?: boolean } = {},
18
+ ): ConnectionState {
19
+ const s = createConnection({ id, connectedSince: 0 });
20
+ s.nick = id;
21
+ s.user = id;
22
+ s.host = 'example.com';
23
+ s.realname = id;
24
+ s.registration = opts.registered === false ? 'pre-registration' : 'registered';
25
+ if (opts.oper !== undefined) s.userModes.oper = opts.oper;
26
+ if (opts.invisible !== undefined) s.userModes.invisible = opts.invisible;
27
+ return s;
28
+ }
29
+
30
+ function emptyChannel(name: string): ChannelState {
31
+ return createChannel({ name, nameLower: name.toLowerCase(), createdAt: 0 });
32
+ }
33
+
34
+ describe('InMemoryStats', () => {
35
+ it('implements the ServerStats port', () => {
36
+ const stats: ServerStats = new InMemoryStats({
37
+ connections: new Map(),
38
+ channels: new Map(),
39
+ uptimeStartedAt: 0,
40
+ });
41
+ expect(stats).toBeDefined();
42
+ });
43
+
44
+ it('returns zero counts for an empty deployment', async () => {
45
+ const stats = new InMemoryStats({
46
+ connections: new Map(),
47
+ channels: new Map(),
48
+ uptimeStartedAt: 0,
49
+ });
50
+
51
+ const snap = await stats.getStats();
52
+
53
+ expect(snap).toEqual<ServerStatsSnapshot>({
54
+ users: 0,
55
+ invisible: 0,
56
+ opers: 0,
57
+ unknownConnections: 0,
58
+ channels: 0,
59
+ servers: 1,
60
+ localConns: 0,
61
+ globalConns: 0,
62
+ uptimeStartedAt: 0,
63
+ maxLocalConns: 0,
64
+ maxGlobalConns: 0,
65
+ });
66
+ });
67
+
68
+ it('derives the seed counts from the maps (3 conns, 1 oper, 2 channels)', async () => {
69
+ const conns = new Map<ConnId, ConnectionState>([
70
+ ['c1', makeConn('c1')],
71
+ ['c2', makeConn('c2', { invisible: true })],
72
+ ['c3', makeConn('c3', { oper: true })],
73
+ ]);
74
+ const channels = new Map<string, ChannelState>([
75
+ ['#a', emptyChannel('#a')],
76
+ ['#b', emptyChannel('#b')],
77
+ ]);
78
+ const stats = new InMemoryStats({
79
+ connections: conns,
80
+ channels,
81
+ uptimeStartedAt: 1_000,
82
+ });
83
+
84
+ const snap = await stats.getStats();
85
+
86
+ // 3 registered (2 visible + 1 invisible), 1 oper, 0 unknown, 2 channels.
87
+ expect(snap.users).toBe(2); // visible registered
88
+ expect(snap.invisible).toBe(1);
89
+ expect(snap.opers).toBe(1);
90
+ expect(snap.unknownConnections).toBe(0);
91
+ expect(snap.channels).toBe(2);
92
+ expect(snap.servers).toBe(1);
93
+ expect(snap.localConns).toBe(3);
94
+ expect(snap.globalConns).toBe(3);
95
+ expect(snap.uptimeStartedAt).toBe(1_000);
96
+ });
97
+
98
+ it('counts pre-registration connections as unknown', async () => {
99
+ const conns = new Map<ConnId, ConnectionState>([
100
+ ['c1', makeConn('c1')],
101
+ ['c2', makeConn('c2', { registered: false })],
102
+ ]);
103
+ const stats = new InMemoryStats({
104
+ connections: conns,
105
+ channels: new Map(),
106
+ uptimeStartedAt: 0,
107
+ });
108
+
109
+ const snap = await stats.getStats();
110
+
111
+ expect(snap.users).toBe(1);
112
+ expect(snap.unknownConnections).toBe(1);
113
+ expect(snap.localConns).toBe(2);
114
+ });
115
+
116
+ it('reports the live max as equal to current count when never higher', async () => {
117
+ const conns = new Map<ConnId, ConnectionState>([['c1', makeConn('c1')]]);
118
+ const stats = new InMemoryStats({
119
+ connections: conns,
120
+ channels: new Map(),
121
+ uptimeStartedAt: 0,
122
+ maxLocalConns: 5,
123
+ maxGlobalConns: 7,
124
+ });
125
+
126
+ const snap = await stats.getStats();
127
+
128
+ expect(snap.maxLocalConns).toBe(5);
129
+ expect(snap.maxGlobalConns).toBe(7);
130
+ });
131
+
132
+ it('clamps max to the current count when the live count exceeds the recorded max', async () => {
133
+ const conns = new Map<ConnId, ConnectionState>([
134
+ ['c1', makeConn('c1')],
135
+ ['c2', makeConn('c2')],
136
+ ['c3', makeConn('c3')],
137
+ ]);
138
+ const stats = new InMemoryStats({
139
+ connections: conns,
140
+ channels: new Map(),
141
+ uptimeStartedAt: 0,
142
+ maxLocalConns: 2,
143
+ maxGlobalConns: 2,
144
+ });
145
+
146
+ const snap = await stats.getStats();
147
+
148
+ // Live count (3) > seeded max (2); the snapshot reports the live value
149
+ // so the wire numeric never claims a max below the current count.
150
+ expect(snap.maxLocalConns).toBe(3);
151
+ expect(snap.maxGlobalConns).toBe(3);
152
+ });
153
+
154
+ it('reflects map mutations on subsequent getStats() calls', async () => {
155
+ const conns = new Map<ConnId, ConnectionState>([['c1', makeConn('c1')]]);
156
+ const stats = new InMemoryStats({
157
+ connections: conns,
158
+ channels: new Map(),
159
+ uptimeStartedAt: 0,
160
+ });
161
+
162
+ let snap = await stats.getStats();
163
+ expect(snap.users).toBe(1);
164
+
165
+ conns.set('c2', makeConn('c2'));
166
+ conns.set('c3', makeConn('c3', { invisible: true }));
167
+ snap = await stats.getStats();
168
+ expect(snap.users).toBe(2);
169
+ expect(snap.invisible).toBe(1);
170
+ expect(snap.localConns).toBe(3);
171
+ });
172
+ });
173
+
174
+ describe('computeStatsSnapshot', () => {
175
+ it('counts opers separately from users (an oper still counts as a user)', () => {
176
+ const snap = computeStatsSnapshot([makeConn('c1'), makeConn('c2', { oper: true })], 0, 0);
177
+ expect(snap.users).toBe(2);
178
+ expect(snap.opers).toBe(1);
179
+ });
180
+
181
+ it('counts an oper who is also invisible under invisible + opers (not users)', () => {
182
+ const snap = computeStatsSnapshot([makeConn('c1', { oper: true, invisible: true })], 0, 0);
183
+ expect(snap.invisible).toBe(1);
184
+ expect(snap.opers).toBe(1);
185
+ // users = visible registered (total registered − invisible).
186
+ expect(snap.users).toBe(0);
187
+ });
188
+
189
+ it('reports users as the visible-only count (total registered − invisible)', () => {
190
+ const snap = computeStatsSnapshot(
191
+ [
192
+ makeConn('c1'),
193
+ makeConn('c2'),
194
+ makeConn('c3', { invisible: true }),
195
+ makeConn('c4', { invisible: true }),
196
+ ],
197
+ 0,
198
+ 0,
199
+ );
200
+ expect(snap.users).toBe(2);
201
+ expect(snap.invisible).toBe(2);
202
+ expect(snap.localConns).toBe(4);
203
+ });
204
+
205
+ it('defaults maxConns to the live count when seed omitted', () => {
206
+ const snap = computeStatsSnapshot([makeConn('c1'), makeConn('c2')], 0, 0);
207
+ expect(snap.maxLocalConns).toBe(2);
208
+ expect(snap.maxGlobalConns).toBe(2);
209
+ });
210
+
211
+ it('uses the FakeClock only for uptime (not in the snapshot)', async () => {
212
+ const clock = new FakeClock(99_000);
213
+ const stats = new InMemoryStats({
214
+ connections: new Map(),
215
+ channels: new Map(),
216
+ uptimeStartedAt: 1_000,
217
+ clock,
218
+ });
219
+ const snap = await stats.getStats();
220
+ expect(snap.uptimeStartedAt).toBe(1_000);
221
+ });
222
+ });
@@ -0,0 +1,213 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ MAX_WS_MESSAGE_BYTES,
4
+ type WsFrameMode,
5
+ frameToLines,
6
+ isWithinWsByteBudget,
7
+ sanitizeForTextMode,
8
+ stripTrailingCrLf,
9
+ wsFrameModeFor,
10
+ } from '../src/ws-framing';
11
+
12
+ // ============================================================================
13
+ // MAX_WS_MESSAGE_BYTES constant
14
+ // ============================================================================
15
+
16
+ describe('MAX_WS_MESSAGE_BYTES', () => {
17
+ it('is 510 (the IRC line-content limit; WS spec omits the trailing CRLF)', () => {
18
+ expect(MAX_WS_MESSAGE_BYTES).toBe(510);
19
+ });
20
+ });
21
+
22
+ // ============================================================================
23
+ // wsFrameModeFor — subprotocol → WsFrameMode mapping
24
+ // ============================================================================
25
+
26
+ describe('wsFrameModeFor', () => {
27
+ it('maps text.ircv3.net to spec-text', () => {
28
+ expect(wsFrameModeFor('text.ircv3.net')).toBe('spec-text');
29
+ });
30
+
31
+ it('maps binary.ircv3.net to spec-binary', () => {
32
+ expect(wsFrameModeFor('binary.ircv3.net')).toBe('spec-binary');
33
+ });
34
+
35
+ it('maps undefined (no subprotocol) to legacy', () => {
36
+ expect(wsFrameModeFor(undefined)).toBe('legacy');
37
+ });
38
+ });
39
+
40
+ // ============================================================================
41
+ // stripTrailingCrLf
42
+ // ============================================================================
43
+
44
+ describe('stripTrailingCrLf', () => {
45
+ it('strips a trailing CR-LF', () => {
46
+ expect(stripTrailingCrLf('NICK bob\r\n')).toBe('NICK bob');
47
+ });
48
+
49
+ it('strips a trailing bare LF', () => {
50
+ expect(stripTrailingCrLf('NICK bob\n')).toBe('NICK bob');
51
+ });
52
+
53
+ it('leaves a string with no trailing terminator unchanged', () => {
54
+ expect(stripTrailingCrLf('NICK bob')).toBe('NICK bob');
55
+ });
56
+
57
+ it('strips only a single trailing terminator', () => {
58
+ expect(stripTrailingCrLf('a\r\n\r\n')).toBe('a\r\n');
59
+ });
60
+
61
+ it('returns the empty string unchanged', () => {
62
+ expect(stripTrailingCrLf('')).toBe('');
63
+ });
64
+
65
+ it('does not strip a leading CR-LF', () => {
66
+ expect(stripTrailingCrLf('\r\nNICK bob')).toBe('\r\nNICK bob');
67
+ });
68
+ });
69
+
70
+ // ============================================================================
71
+ // frameToLines — spec-text / spec-binary modes (one IRC message per frame)
72
+ // ============================================================================
73
+
74
+ describe('frameToLines — spec-text', () => {
75
+ it('strips a trailing CR-LF and returns a single-element array', () => {
76
+ expect(frameToLines('NICK bob\r\n', 'spec-text')).toEqual(['NICK bob']);
77
+ });
78
+
79
+ it('strips a trailing bare LF', () => {
80
+ expect(frameToLines('NICK bob\n', 'spec-text')).toEqual(['NICK bob']);
81
+ });
82
+
83
+ it('does not split on an embedded LF (one WS message === one IRC line)', () => {
84
+ expect(frameToLines('NICK bob\nextra', 'spec-text')).toEqual(['NICK bob\nextra']);
85
+ });
86
+
87
+ it('returns an empty array for an empty frame', () => {
88
+ expect(frameToLines('', 'spec-text')).toEqual([]);
89
+ });
90
+
91
+ it('returns an empty array for a frame that is only a terminator', () => {
92
+ expect(frameToLines('\r\n', 'spec-text')).toEqual([]);
93
+ });
94
+
95
+ it('returns a single bare line unchanged when there is no terminator', () => {
96
+ expect(frameToLines('PING :tok', 'spec-text')).toEqual(['PING :tok']);
97
+ });
98
+ });
99
+
100
+ describe('frameToLines — spec-binary', () => {
101
+ it('behaves identically to spec-text (single line, terminator stripped)', () => {
102
+ expect(frameToLines('NICK bob\n', 'spec-binary')).toEqual(['NICK bob']);
103
+ });
104
+
105
+ it('does not split on an embedded LF', () => {
106
+ expect(frameToLines('a\nb', 'spec-binary')).toEqual(['a\nb']);
107
+ });
108
+ });
109
+
110
+ // ============================================================================
111
+ // frameToLines — legacy mode (the pre-spec split-on-/\r?\n/ behaviour)
112
+ // ============================================================================
113
+
114
+ describe('frameToLines — legacy', () => {
115
+ it('splits on CR-LF into separate lines', () => {
116
+ expect(frameToLines('a\r\nb', 'legacy')).toEqual(['a', 'b']);
117
+ });
118
+
119
+ it('splits on bare LF', () => {
120
+ expect(frameToLines('a\nb', 'legacy')).toEqual(['a', 'b']);
121
+ });
122
+
123
+ it('returns an empty array for the empty string', () => {
124
+ expect(frameToLines('', 'legacy')).toEqual([]);
125
+ });
126
+
127
+ it('returns a single bare line with no terminator unchanged', () => {
128
+ expect(frameToLines('PING :tok', 'legacy')).toEqual(['PING :tok']);
129
+ });
130
+
131
+ it('emits a trailing empty string for a terminated frame', () => {
132
+ expect(frameToLines('PING :tok\r\n', 'legacy')).toEqual(['PING :tok', '']);
133
+ });
134
+
135
+ it('splits several joined messages keeping a trailing empty string', () => {
136
+ expect(frameToLines('a\r\nb\r\n', 'legacy')).toEqual(['a', 'b', '']);
137
+ });
138
+ });
139
+
140
+ // Exhaustiveness guard: every declared mode is covered by the specs above.
141
+ describe('frameToLines — mode coverage', () => {
142
+ const modes: WsFrameMode[] = ['spec-text', 'spec-binary', 'legacy'];
143
+ for (const mode of modes) {
144
+ it(`accepts the '${mode}' mode without throwing`, () => {
145
+ expect(Array.isArray(frameToLines('x', mode))).toBe(true);
146
+ });
147
+ }
148
+ });
149
+
150
+ // ============================================================================
151
+ // isWithinWsByteBudget — the IRCv3 WS message byte cap
152
+ // ============================================================================
153
+
154
+ describe('isWithinWsByteBudget', () => {
155
+ it('accepts a frame whose length equals the 510-byte budget', () => {
156
+ expect(isWithinWsByteBudget('a'.repeat(510))).toBe(true);
157
+ });
158
+
159
+ it('rejects a frame whose length is one byte over the budget', () => {
160
+ expect(isWithinWsByteBudget('a'.repeat(511))).toBe(false);
161
+ });
162
+
163
+ it('accepts the empty string', () => {
164
+ expect(isWithinWsByteBudget('')).toBe(true);
165
+ });
166
+
167
+ it('accepts a short frame', () => {
168
+ expect(isWithinWsByteBudget('NICK bob')).toBe(true);
169
+ });
170
+ });
171
+
172
+ // ============================================================================
173
+ // sanitizeForTextMode — replace lone surrogates with U+FFFD
174
+ // ============================================================================
175
+
176
+ describe('sanitizeForTextMode', () => {
177
+ it('replaces a lone high surrogate with U+FFFD', () => {
178
+ expect(sanitizeForTextMode('\uD800')).toBe('\uFFFD');
179
+ });
180
+
181
+ it('replaces a lone low surrogate with U+FFFD', () => {
182
+ expect(sanitizeForTextMode('\uDC00')).toBe('\uFFFD');
183
+ });
184
+
185
+ it('leaves a valid surrogate pair (a supplementary code point) unchanged', () => {
186
+ // U+10000 = \uD800\uDC00
187
+ expect(sanitizeForTextMode('\uD800\uDC00')).toBe('\uD800\uDC00');
188
+ });
189
+
190
+ it('leaves plain ASCII text unchanged', () => {
191
+ expect(sanitizeForTextMode('hello')).toBe('hello');
192
+ });
193
+
194
+ it('replaces a lone surrogate embedded in normal text', () => {
195
+ expect(sanitizeForTextMode('a\uD800b')).toBe('a\uFFFDb');
196
+ });
197
+
198
+ it('replaces two consecutive lone high surrogates with two U+FFFD', () => {
199
+ expect(sanitizeForTextMode('\uD800\uD800')).toBe('\uFFFD\uFFFD');
200
+ });
201
+
202
+ it('preserves a valid pair surrounded by normal text', () => {
203
+ expect(sanitizeForTextMode('x\uD83D\uDE00y')).toBe('x\uD83D\uDE00y');
204
+ });
205
+
206
+ it('replaces a lone high surrogate followed later by a lone low surrogate', () => {
207
+ expect(sanitizeForTextMode('\uD800a\uDC00')).toBe('\uFFFDa\uFFFD');
208
+ });
209
+
210
+ it('returns the empty string unchanged', () => {
211
+ expect(sanitizeForTextMode('')).toBe('');
212
+ });
213
+ });