serverless-ircd 0.5.0 → 0.6.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 (167) hide show
  1. package/.github/workflows/ci.yml +34 -2
  2. package/.github/workflows/deploy-aws.yml +1 -2
  3. package/.github/workflows/deploy-cf-tcp.yml +1 -5
  4. package/.github/workflows/deploy-cf.yml +1 -2
  5. package/CHANGELOG.md +260 -0
  6. package/README.md +132 -22
  7. package/apps/aws-stack/README.md +33 -0
  8. package/apps/aws-stack/package.json +1 -1
  9. package/apps/aws-stack/src/aws-stack.ts +74 -9
  10. package/apps/aws-stack/tests/coverage-command.test.ts +155 -0
  11. package/apps/aws-stack/tests/stack.test.ts +2 -2
  12. package/apps/aws-stack/tests/synth-no-bundle.test.ts +129 -0
  13. package/apps/aws-stack/tests/vitest.setup.ts +18 -0
  14. package/apps/aws-stack/vitest.config.ts +3 -0
  15. package/apps/cf-tcp-container/package.json +1 -1
  16. package/apps/cf-tcp-container/src/config-loader.ts +6 -7
  17. package/apps/cf-tcp-container/src/container-server.ts +3 -0
  18. package/apps/cf-tcp-container/tests/config-loader.test.ts +10 -3
  19. package/apps/cf-tcp-container/wrangler.toml +1 -1
  20. package/apps/cf-worker/package.json +2 -1
  21. package/apps/cf-worker/vitest.config.ts +1 -1
  22. package/apps/cf-worker/wrangler.toml +5 -3
  23. package/apps/local-cli/package.json +1 -1
  24. package/apps/local-cli/src/config-loader.ts +6 -6
  25. package/apps/local-cli/src/main.ts +20 -0
  26. package/apps/local-cli/src/server.ts +9 -7
  27. package/apps/local-cli/tests/e2e.test.ts +112 -28
  28. package/apps/local-cli/tests/tcp.test.ts +71 -19
  29. package/apps/local-cli/tests/ws-subprotocol.test.ts +12 -7
  30. package/biome.json +1 -0
  31. package/docs/ADR-001-pure-reducers-and-effect-system.md +74 -0
  32. package/docs/ADR-002-location-of-authority.md +82 -0
  33. package/docs/ADR-003-durable-object-sharding.md +110 -0
  34. package/docs/ADR-004-dynamodb-schema.md +96 -0
  35. package/docs/ADR-005-wss-only-transport-v1.md +83 -0
  36. package/docs/ADR-006-sasl-mechanism-scope.md +96 -0
  37. package/docs/ADR-007-deterministic-ports.md +82 -0
  38. package/docs/ADR-008-monorepo-tooling.md +60 -0
  39. package/docs/ADR-009-dual-transport-wss-and-irc-tls.md +138 -0
  40. package/docs/ADR-Index.md +15 -0
  41. package/docs/AWS-Adapter-Architecture.md +496 -0
  42. package/docs/AWS-Deployment.md +1275 -0
  43. package/docs/AWS-TCP-Deployment.md +410 -0
  44. package/docs/Cloudflare-Deployment-Guide.md +719 -0
  45. package/docs/Cloudflare-TCP-Deployment.md +510 -0
  46. package/docs/Home.md +15 -0
  47. package/docs/Observability.md +87 -0
  48. package/docs/PlanExtensions.md +812 -0
  49. package/docs/PlanIRCv3Websocket.md +503 -0
  50. package/docs/PlanWebClient.md +451 -0
  51. package/docs/Release-Process.md +443 -0
  52. package/package.json +2 -2
  53. package/packages/aws-adapter/package.json +1 -1
  54. package/packages/aws-adapter/src/handlers/default.ts +3 -0
  55. package/packages/aws-adapter/src/handlers/nlb-stream.ts +9 -0
  56. package/packages/aws-adapter/src/serialize.ts +29 -1
  57. package/packages/aws-adapter/tests/account-store-dynamo.test.ts +49 -8
  58. package/packages/aws-adapter/tests/account-store.test.ts +4 -7
  59. package/packages/aws-adapter/tests/aws-harness.ts +5 -2
  60. package/packages/aws-adapter/tests/aws-integration.test.ts +8 -4
  61. package/packages/aws-adapter/tests/aws-runtime.test.ts +79 -0
  62. package/packages/aws-adapter/tests/config-loader.test.ts +11 -2
  63. package/packages/aws-adapter/tests/connect.test.ts +9 -9
  64. package/packages/aws-adapter/tests/disconnect-fanout.test.ts +3 -4
  65. package/packages/aws-adapter/tests/global-setup.ts +55 -30
  66. package/packages/aws-adapter/tests/gone-exception.test.ts +4 -9
  67. package/packages/aws-adapter/tests/handlers.test.ts +90 -4
  68. package/packages/aws-adapter/tests/message-store.test.ts +6 -5
  69. package/packages/aws-adapter/tests/nlb-stream.test.ts +60 -8
  70. package/packages/cf-adapter/package.json +2 -1
  71. package/packages/cf-adapter/src/connection-do.ts +3 -0
  72. package/packages/cf-adapter/src/serialize.ts +25 -4
  73. package/packages/cf-adapter/tests/cf-runtime.test.ts +269 -0
  74. package/packages/cf-adapter/tests/channel-do.test.ts +117 -0
  75. package/packages/cf-adapter/tests/config-loader.test.ts +49 -0
  76. package/packages/cf-adapter/tests/connection-do-pure.test.ts +91 -0
  77. package/packages/cf-adapter/tests/d1-account-store.test.ts +48 -0
  78. package/packages/cf-adapter/tests/registry-do.test.ts +104 -0
  79. package/packages/cf-adapter/tests/serialize.test.ts +308 -0
  80. package/packages/cf-adapter/vitest.config.ts +1 -1
  81. package/packages/in-memory-runtime/package.json +1 -1
  82. package/packages/irc-core/package.json +1 -1
  83. package/packages/irc-core/src/caps/capabilities.ts +37 -3
  84. package/packages/irc-core/src/caps/index.ts +1 -0
  85. package/packages/irc-core/src/caps/sts.ts +84 -0
  86. package/packages/irc-core/src/commands/account-notify.ts +53 -0
  87. package/packages/irc-core/src/commands/away.ts +9 -3
  88. package/packages/irc-core/src/commands/cap.ts +23 -5
  89. package/packages/irc-core/src/commands/chathistory.ts +40 -11
  90. package/packages/irc-core/src/commands/index.ts +34 -0
  91. package/packages/irc-core/src/commands/isupport.ts +53 -0
  92. package/packages/irc-core/src/commands/mode.ts +8 -1
  93. package/packages/irc-core/src/commands/monitor.ts +327 -0
  94. package/packages/irc-core/src/commands/multiline.ts +256 -0
  95. package/packages/irc-core/src/commands/pre-away.ts +112 -0
  96. package/packages/irc-core/src/commands/privmsg.ts +19 -12
  97. package/packages/irc-core/src/commands/read-marker.ts +108 -0
  98. package/packages/irc-core/src/commands/registration.ts +8 -0
  99. package/packages/irc-core/src/commands/sasl.ts +24 -1
  100. package/packages/irc-core/src/commands/tagmsg.ts +71 -1
  101. package/packages/irc-core/src/commands/whois.ts +5 -0
  102. package/packages/irc-core/src/config.ts +65 -10
  103. package/packages/irc-core/src/effects.ts +14 -0
  104. package/packages/irc-core/src/ports.ts +389 -0
  105. package/packages/irc-core/src/protocol/index.ts +14 -0
  106. package/packages/irc-core/src/protocol/labeled-response.ts +133 -0
  107. package/packages/irc-core/src/protocol/numerics.ts +15 -0
  108. package/packages/irc-core/src/protocol/outbound.ts +16 -1
  109. package/packages/irc-core/src/protocol/standard-replies.ts +277 -0
  110. package/packages/irc-core/src/state/connection.ts +32 -1
  111. package/packages/irc-core/src/types.ts +112 -0
  112. package/packages/irc-core/stryker.commands.conf.json +1 -2
  113. package/packages/irc-core/tests/away-store.test.ts +73 -0
  114. package/packages/irc-core/tests/caps/capabilities.test.ts +119 -2
  115. package/packages/irc-core/tests/caps/sts.test.ts +123 -0
  116. package/packages/irc-core/tests/commands/account-notify.test.ts +171 -0
  117. package/packages/irc-core/tests/commands/away.test.ts +85 -2
  118. package/packages/irc-core/tests/commands/cap.test.ts +165 -0
  119. package/packages/irc-core/tests/commands/chathistory.test.ts +148 -1
  120. package/packages/irc-core/tests/commands/echo-message.test.ts +9 -3
  121. package/packages/irc-core/tests/commands/isupport.test.ts +80 -0
  122. package/packages/irc-core/tests/commands/mode.test.ts +72 -0
  123. package/packages/irc-core/tests/commands/monitor.test.ts +411 -0
  124. package/packages/irc-core/tests/commands/multiline.test.ts +428 -0
  125. package/packages/irc-core/tests/commands/pre-away.test.ts +241 -0
  126. package/packages/irc-core/tests/commands/privmsg.test.ts +154 -3
  127. package/packages/irc-core/tests/commands/read-marker.test.ts +211 -0
  128. package/packages/irc-core/tests/commands/registration.test.ts +64 -0
  129. package/packages/irc-core/tests/commands/sasl.test.ts +116 -2
  130. package/packages/irc-core/tests/commands/tagmsg.test.ts +357 -0
  131. package/packages/irc-core/tests/commands/whois.test.ts +34 -0
  132. package/packages/irc-core/tests/config.test.ts +103 -13
  133. package/packages/irc-core/tests/labeled-response.test.ts +181 -0
  134. package/packages/irc-core/tests/message-tags.test.ts +114 -0
  135. package/packages/irc-core/tests/monitor-store.test.ts +200 -0
  136. package/packages/irc-core/tests/read-marker-store.test.ts +108 -0
  137. package/packages/irc-core/tests/standard-replies.test.ts +412 -0
  138. package/packages/irc-core/tests/types.test.ts +27 -0
  139. package/packages/irc-server/package.json +1 -1
  140. package/packages/irc-server/src/actor.ts +450 -3
  141. package/packages/irc-server/src/dispatch.ts +108 -16
  142. package/packages/irc-server/tests/actor.test.ts +1432 -39
  143. package/packages/irc-server/tests/dispatch.test.ts +263 -2
  144. package/packages/irc-test-support/package.json +1 -1
  145. package/packages/irc-test-support/src/index.ts +6 -0
  146. package/packages/irc-test-support/src/test-config.ts +54 -0
  147. package/packages/irc-test-support/tests/test-config.test.ts +51 -0
  148. package/tools/ci-hardening/package.json +1 -1
  149. package/tools/ci-hardening/tests/ddb-local.test.ts +82 -0
  150. package/tools/load-test/package.json +33 -0
  151. package/tools/load-test/src/client.ts +351 -0
  152. package/tools/load-test/src/config.ts +313 -0
  153. package/tools/load-test/src/harness.ts +116 -0
  154. package/tools/load-test/src/main.ts +120 -0
  155. package/tools/load-test/src/metrics.ts +168 -0
  156. package/tools/load-test/src/report.ts +106 -0
  157. package/tools/load-test/tests/client.test.ts +212 -0
  158. package/tools/load-test/tests/config.test.ts +152 -0
  159. package/tools/load-test/tests/framing.test.ts +37 -0
  160. package/tools/load-test/tests/harness.test.ts +165 -0
  161. package/tools/load-test/tests/metrics.test.ts +174 -0
  162. package/tools/load-test/tests/report.test.ts +161 -0
  163. package/tools/load-test/tests/smoke.test.ts +67 -0
  164. package/tools/load-test/tsconfig.build.json +12 -0
  165. package/tools/load-test/tsconfig.test.json +10 -0
  166. package/tools/load-test/vitest.config.ts +29 -0
  167. package/tools/tcp-ws-forwarder/package.json +1 -1
@@ -134,6 +134,11 @@ export function whoisReducer(
134
134
  text: `:${ctx.serverName} ${Numerics.RPL_WHOISOPERATOR.toString().padStart(3, '0')} ${requesterNick} ${tNick} :is an IRC operator`,
135
135
  });
136
136
  }
137
+ if (target.userModes.tls) {
138
+ lines.push({
139
+ text: `:${ctx.serverName} ${Numerics.RPL_WHOISSECURE.toString().padStart(3, '0')} ${requesterNick} ${tNick} :is using a secure connection`,
140
+ });
141
+ }
137
142
  if (target.account !== undefined) {
138
143
  lines.push({
139
144
  text: `:${ctx.serverName} ${Numerics.RPL_WHOISACCOUNT.toString().padStart(3, '0')} ${requesterNick} ${tNick} ${target.account} :is logged in as`,
@@ -18,6 +18,7 @@
18
18
 
19
19
  import { z } from 'zod';
20
20
  import { BUILD_DATE } from './build-info.js';
21
+ import { DEFAULT_MULTILINE_MAX_BYTES } from './caps/capabilities.js';
21
22
 
22
23
  /**
23
24
  * Schema for a single IRC operator credential.
@@ -61,6 +62,33 @@ export const CloakingConfigSchema = z.object({
61
62
  cloakedSuffix: z.string().min(1).optional(),
62
63
  });
63
64
 
65
+ /**
66
+ * IRCv3 `sts` (Strict Transport Security) policy. When supplied, the
67
+ * server advertises an `sts` capability whose value tells compliant
68
+ * clients how long to pin TLS and which port to upgrade to on a
69
+ * plaintext connection. Omit entirely (the default) to disable STS.
70
+ *
71
+ * Spec: https://ircv3.net/specs/extensions/sts
72
+ */
73
+ export const StsConfigSchema = z.object({
74
+ /**
75
+ * Pin duration in seconds. Defaults to 30 days at the cap-builder layer
76
+ * when omitted; supply an explicit value in production.
77
+ */
78
+ duration: z.number().int().positive(),
79
+ /**
80
+ * TLS listener port advertised on plaintext connections. The canonical
81
+ * IRC-over-TLS port is 6697 (RFC 7193). Defaults to 6697 at the
82
+ * cap-builder layer when omitted.
83
+ */
84
+ port: z.number().int().positive(),
85
+ /**
86
+ * Optional preload directive. When true the policy may be hard-coded
87
+ * into a client preload list (only advertised on plaintext connections).
88
+ */
89
+ preload: z.boolean().optional(),
90
+ });
91
+
64
92
  /**
65
93
  * Per-IP connection-rate limit. Caps how many new connections a single
66
94
  * source IP may open within a sliding `windowMs` window before the
@@ -272,6 +300,43 @@ export const ServerConfigSchema = z.object({
272
300
  * lower per deployment. Only consulted when a MessageStore is bound.
273
301
  */
274
302
  chatHistoryPlaybackLimit: z.number().int().positive().default(50),
303
+
304
+ /**
305
+ * IRCv3 `sts` (Strict Transport Security) policy. Omit entirely (the
306
+ * default) to disable STS advertisement; supply `{ duration, port }`
307
+ * (plus optional `preload`) to advertise the cap and let compliant
308
+ * clients upgrade from plaintext to TLS and pin the secure listener.
309
+ */
310
+ sts: StsConfigSchema.optional(),
311
+
312
+ /**
313
+ * IRCv3 `draft/multiline` byte budget. Advertised as
314
+ * `draft/multiline=<n>` in `CAP LS` and enforced on every finalized
315
+ * multi-line batch. Defaults to the IRCv3-recommended 4096; raise or
316
+ * lower per deployment.
317
+ */
318
+ multilineMaxBytes: z.number().int().positive().default(DEFAULT_MULTILINE_MAX_BYTES),
319
+
320
+ /**
321
+ * Per-connection MONITOR watchlist ceiling, advertised as `MONITOR=<n>`
322
+ * in `005 RPL_ISUPPORT`. Omit to inherit the monitor reducer's built-in
323
+ * ceiling (DEFAULT_MONITOR_LIMIT, 30).
324
+ */
325
+ monitorLimit: z.number().int().positive().optional(),
326
+
327
+ /**
328
+ * Extended-ban prefix sigil for `EXTBAN=<prefix>,…` in
329
+ * `005 RPL_ISUPPORT`. Omit for the IRC-standard `~`.
330
+ */
331
+ extbanPrefix: z.string().min(1).optional(),
332
+
333
+ /**
334
+ * Enables IRC-services-derived ISUPPORT tokens (currently
335
+ * `ACCOUNTEXTBAN=a`). Set to true once a `ServicesStore` is bound; until
336
+ * then account-name extended bans are suppressed because unregistered
337
+ * nicks make them meaningless.
338
+ */
339
+ servicesEnabled: z.boolean().optional(),
275
340
  });
276
341
 
277
342
  /** Input type: what adapters supply (fields with defaults may be omitted). */
@@ -303,16 +368,6 @@ export function parseServerConfig(input: unknown): ParsedServerConfig {
303
368
  return result.data;
304
369
  }
305
370
 
306
- /**
307
- * Default server config: the result of parsing an empty input. Useful as a
308
- * known-good baseline for tests and for adapters that want to overlay
309
- * per-deployment overrides via object spread.
310
- */
311
- export const DEFAULT_SERVER_CONFIG: ParsedServerConfig = ServerConfigSchema.parse({
312
- serverName: 'irc.example.com',
313
- networkName: 'ServerlessIRCd',
314
- });
315
-
316
371
  /**
317
372
  * Resolves the effective server version for wire output: the configured
318
373
  * value when present, otherwise {@link DEFAULT_SERVER_VERSION}. Used by the
@@ -43,6 +43,18 @@ export interface BroadcastEffect {
43
43
  except?: ConnId;
44
44
  cap?: string;
45
45
  capLines?: RawLine[];
46
+ /**
47
+ * OR-semantics cap list: the recipient receives `lines` iff they
48
+ * negotiated ANY of the listed caps. Used by capabilities whose delivery
49
+ * rule is the union of two caps — e.g. `draft/typing` TAGMSGs reach
50
+ * peers that announced `draft/typing` OR `message-tags` (the latter
51
+ * because every TAGMSG goes to message-tags peers regardless of tag).
52
+ *
53
+ * Mutually exclusive with {@link cap}: set one or the other, not both.
54
+ * When neither is set, dispatch takes the runtime's bulk broadcast fast
55
+ * path.
56
+ */
57
+ caps?: readonly string[];
46
58
  }
47
59
 
48
60
  export interface DisconnectEffect {
@@ -150,11 +162,13 @@ export const Effect = {
150
162
  except?: ConnId,
151
163
  cap?: string,
152
164
  capLines?: RawLine[],
165
+ caps?: readonly string[],
153
166
  ): Effect {
154
167
  const e: BroadcastEffect = { tag: 'Broadcast', chan, lines };
155
168
  if (except !== undefined) e.except = except;
156
169
  if (cap !== undefined) e.cap = cap;
157
170
  if (capLines !== undefined) e.capLines = capLines;
171
+ if (caps !== undefined) e.caps = caps;
158
172
  return e;
159
173
  },
160
174
  disconnect(conn: ConnId, reason?: string): Effect {
@@ -340,6 +340,13 @@ export type StoredCommand = 'PRIVMSG' | 'NOTICE' | 'TAGMSG';
340
340
  * is reconstructed by the reducer from the authoritative {@link ChannelState}
341
341
  * when building replay lines. `time` is epoch milliseconds from the injected
342
342
  * {@link Clock}; `msgid` is a fresh nonce from {@link IdFactory}.
343
+ *
344
+ * `clientTags` carries optional IRCv3 message-tags client-only entries
345
+ * (keys prefixed with `+`) that the recording reducer wants preserved on
346
+ * replay — e.g. `+draft/multiline` so a chathistory client can recognise
347
+ * that a stored PRIVMSG originated from a multi-line batch. Omitted (or
348
+ * empty) for normal PRIVMSG/NOTICE/TAGMSG. The chathistory replay weaves
349
+ * these into the `@time=…;msgid=…` tag section verbatim.
343
350
  */
344
351
  export interface StoredMessage {
345
352
  msgid: string;
@@ -350,6 +357,7 @@ export interface StoredMessage {
350
357
  user?: string;
351
358
  host?: string;
352
359
  text: string;
360
+ readonly clientTags?: readonly string[];
353
361
  }
354
362
 
355
363
  /** Subcommands of `CHATHISTORY` that select a slice of the backlog. */
@@ -570,6 +578,180 @@ function tail<T>(arr: readonly T[], n: number): T[] {
570
578
  return arr.slice(start);
571
579
  }
572
580
 
581
+ // ============================================================================
582
+ // Read-marker persistence (IRCv3 draft/read-marker)
583
+ // ============================================================================
584
+
585
+ /**
586
+ * One persisted last-read marker, keyed per `(account, channel)`.
587
+ *
588
+ * `channel` is the lowercased channel name (the storage key); `msgid` is the
589
+ * msgid of the most recent message the account has read in that channel.
590
+ * Returned by {@link ReadMarkerStore.forAccount} when seeding a fresh
591
+ * connection at identify time.
592
+ */
593
+ export interface ReadMarkerEntry {
594
+ /** Canonical account name (as recorded by SASL). */
595
+ account: string;
596
+ /** Lowercased channel name (rfc1459-folded storage key). */
597
+ channel: string;
598
+ /** Msgid of the most recent read message in this channel. */
599
+ msgid: string;
600
+ }
601
+
602
+ /**
603
+ * Persistence port for IRCv3 `draft/read-marker`.
604
+ *
605
+ * The chathistory command keeps a per-`(connection, channel)`
606
+ * last-read marker in {@link ConnectionState.lastReadMarkers}; this port
607
+ * promotes that marker to a per-`(account, channel)` record so it survives
608
+ * reconnects and is shared across an account's connections.
609
+ *
610
+ * Mirrors the {@link MessageStore} / {@link AccountStore} pattern: the port
611
+ * is **synchronous** (reducers must stay pure and free of IO) and injected
612
+ * via {@link Ctx}. Adapters that need async storage (D1, DynamoDB) pre-load
613
+ * the relevant slice into a synchronously-readable store; the in-memory
614
+ * reference implementation ({@link InMemoryReadMarkerStore}) ships here.
615
+ *
616
+ * Account and channel keys are both case-folded (rfc1459) so lookups are
617
+ * case-insensitive, matching the rest of the server's comparison semantics.
618
+ */
619
+ export interface ReadMarkerStore {
620
+ /**
621
+ * Returns the stored last-read msgid for `(account, channel)`, or
622
+ * `undefined` when no marker has been recorded.
623
+ */
624
+ get(account: string, channel: string): string | undefined;
625
+ /**
626
+ * Records (or replaces) the last-read msgid for `(account, channel)`.
627
+ * Callers MUST only move the marker forward (towards newer messages);
628
+ * the store itself does not order msgids, it stores the latest value set.
629
+ */
630
+ set(account: string, channel: string, msgid: string): void;
631
+ /**
632
+ * Enumerates every recorded marker for `account`. Used at identify time to
633
+ * seed a fresh connection's {@link ConnectionState.lastReadMarkers} so a
634
+ * reconnect restores the user's read position across all their channels.
635
+ */
636
+ forAccount(account: string): ReadonlyArray<ReadMarkerEntry>;
637
+ }
638
+
639
+ /**
640
+ * Reference in-memory {@link ReadMarkerStore} backed by a
641
+ * `foldedAccount → (foldedChannel → msgid)` nested map.
642
+ *
643
+ * Used by the local CLI, integration tests, and any deployment that has not
644
+ * bound a distributed backend. Cloud adapters replace this with a D1 /
645
+ * DynamoDB-backed implementation against the same surface.
646
+ *
647
+ * Both keys are folded via {@link caseFold} (`rfc1459`) so lookups are
648
+ * case-insensitive; the returned {@link ReadMarkerEntry.channel} carries the
649
+ * folded spelling and {@link ReadMarkerEntry.account} the canonical name
650
+ * passed to {@link ReadMarkerStore.forAccount}.
651
+ */
652
+ export class InMemoryReadMarkerStore implements ReadMarkerStore {
653
+ private readonly byAccount = new Map<string, Map<string, string>>();
654
+
655
+ get(account: string, channel: string): string | undefined {
656
+ return this.byAccount.get(folded(account))?.get(folded(channel));
657
+ }
658
+
659
+ set(account: string, channel: string, msgid: string): void {
660
+ const acct = folded(account);
661
+ let chanMap = this.byAccount.get(acct);
662
+ if (chanMap === undefined) {
663
+ chanMap = new Map<string, string>();
664
+ this.byAccount.set(acct, chanMap);
665
+ }
666
+ chanMap.set(folded(channel), msgid);
667
+ }
668
+
669
+ forAccount(account: string): ReadonlyArray<ReadMarkerEntry> {
670
+ const chanMap = this.byAccount.get(folded(account));
671
+ if (chanMap === undefined) return [];
672
+ const out: ReadMarkerEntry[] = [];
673
+ for (const [channel, msgid] of chanMap) {
674
+ out.push({ account, channel, msgid });
675
+ }
676
+ return out;
677
+ }
678
+ }
679
+
680
+ /** rfc1459 case-fold used for both account and channel keys. */
681
+ function folded(value: string): string {
682
+ return caseFold('rfc1459', value);
683
+ }
684
+
685
+ // ============================================================================
686
+ // Away-status persistence (IRCv3 draft/pre-away)
687
+ // ============================================================================
688
+
689
+ /**
690
+ * Persistence port for IRCv3 `draft/pre-away`.
691
+ *
692
+ * The base `AWAY` reducer keeps the away reason in
693
+ * {@link ConnectionState.away} for the lifetime of a single connection; this
694
+ * port promotes that reason to a per-`account` record so it survives
695
+ * reconnects and is shared across an account's connections.
696
+ *
697
+ * Mirrors the {@link ReadMarkerStore} pattern: the port is
698
+ * **synchronous** (reducers must stay pure and free of IO) and injected
699
+ * via {@link Ctx}. Adapters that need async storage (D1, DynamoDB) pre-load
700
+ * the relevant slice into a synchronously-readable store; the in-memory
701
+ * reference implementation ({@link InMemoryAwayStore}) ships here.
702
+ *
703
+ * The account key is case-folded (rfc1459) so lookups are
704
+ * case-insensitive, matching the rest of the server's comparison
705
+ * semantics. The unified services `UserStore` should fold this store in
706
+ * when it lands.
707
+ */
708
+ export interface AwayStore {
709
+ /**
710
+ * Returns the stored away reason for `account`, or `undefined` when no
711
+ * reason has been recorded.
712
+ */
713
+ get(account: string): string | undefined;
714
+ /**
715
+ * Records (or replaces) the away reason for `account`. An empty string
716
+ * is permitted at the store layer (callers avoid it via
717
+ * {@link clearAway}).
718
+ */
719
+ set(account: string, reason: string): void;
720
+ /**
721
+ * Removes the stored away reason for `account`. Used when the user
722
+ * unsets `AWAY` so the next reconnect does not auto-mark them away.
723
+ */
724
+ clear(account: string): void;
725
+ }
726
+
727
+ /**
728
+ * Reference in-memory {@link AwayStore} backed by a
729
+ * `foldedAccount → reason` map.
730
+ *
731
+ * Used by the local CLI, integration tests, and any deployment that has
732
+ * not bound a distributed backend. Cloud adapters replace this with a D1
733
+ * / DynamoDB-backed implementation against the same surface.
734
+ *
735
+ * The account key is folded via {@link caseFold} (`rfc1459`) so lookups
736
+ * are case-insensitive, matching the IRC nick-comparison semantics
737
+ * advertised via `005 RPL_ISUPPORT CASEMAPPING=rfc1459`.
738
+ */
739
+ export class InMemoryAwayStore implements AwayStore {
740
+ private readonly byAccount = new Map<string, string>();
741
+
742
+ get(account: string): string | undefined {
743
+ return this.byAccount.get(folded(account));
744
+ }
745
+
746
+ set(account: string, reason: string): void {
747
+ this.byAccount.set(folded(account), reason);
748
+ }
749
+
750
+ clear(account: string): void {
751
+ this.byAccount.delete(folded(account));
752
+ }
753
+ }
754
+
573
755
  // ============================================================================
574
756
  // Nick history (WHOWAS)
575
757
  // ============================================================================
@@ -672,6 +854,213 @@ export class InMemoryNickHistoryStore implements NickHistoryStore {
672
854
  }
673
855
  }
674
856
 
857
+ // ============================================================================
858
+ // MONITOR subscription registry (IRCv3 MONITOR)
859
+ // ============================================================================
860
+
861
+ /**
862
+ * One async push notification the {@link MonitorStore} requests from the
863
+ * actor layer. The actor turns each push into one or more `Send` effects
864
+ * addressed to the watcher's connection.
865
+ *
866
+ * - `online` — the nick came online; the watcher should receive a
867
+ * `730 RPL_MONONLINE` line naming `display`.
868
+ * - `offline` — the nick went offline; the watcher should receive a
869
+ * `731 RPL_MONOFFLINE` line naming `display`.
870
+ */
871
+ export interface MonitorPush {
872
+ /** Watcher's connection id. */
873
+ connId: string;
874
+ /** Display spelling of the nick that changed state. */
875
+ display: string;
876
+ /** New state. */
877
+ status: 'online' | 'offline';
878
+ }
879
+
880
+ /**
881
+ * Subscription registry for the IRCv3 `MONITOR` command.
882
+ *
883
+ * The watchlist itself lives on {@link ConnectionState.monitorList} (so it
884
+ * persists across actor re-bindings); this port owns the **reverse index**
885
+ * (nick → set of watcher connIds) and the **online set** the actor consults
886
+ * when synchronously resolving `MONITOR +` / `MONITOR S`.
887
+ *
888
+ * Mirrors the {@link MessageStore} / {@link AccountStore} pattern: the port
889
+ * is **synchronous** (reducers must stay pure and free of IO). The actor
890
+ * layer drains pending pushes after each command via {@link drainPushes};
891
+ * adapters that need to fan notifications out across processes (CF
892
+ * ConnectionDO sharding, AWS WebSocket fanout) replace
893
+ * {@link InMemoryMonitorStore} with their own implementation against the
894
+ * same surface.
895
+ *
896
+ * Lifecycle:
897
+ * - On `MONITOR +`, the actor calls {@link sync} with the before/after
898
+ * watchlist snapshots; the store records each newly-added nick →
899
+ * watcher mapping.
900
+ * - On `MONITOR -` / `C`, {@link sync} drops the removed mappings.
901
+ * - On `NICK` (reserve/change) the actor calls {@link onNickOnline} for
902
+ * each newly-reserved nick; the store appends a {@link MonitorPush}
903
+ * for every watcher of that nick.
904
+ * - On `QUIT` (or any release) the actor calls {@link onNickOffline};
905
+ * same flow with a `731` push.
906
+ * - On connection teardown, the actor calls {@link unsubscribe} so the
907
+ * reverse index does not leak.
908
+ */
909
+ export interface MonitorStore {
910
+ /**
911
+ * Reconciles the reverse index for `connId` against a watchlist delta.
912
+ * `before` is the watchlist at the start of the command (folded nicks);
913
+ * `after` is the watchlist after the reducer ran. The store adds
914
+ * mappings for entries in `after` not in `before`, and removes mappings
915
+ * for entries in `before` not in `after`.
916
+ */
917
+ sync(connId: string, before: ReadonlySet<string>, after: ReadonlySet<string>): void;
918
+ /**
919
+ * Removes every subscription for `connId`. Safe to call when the
920
+ * connection had no subscriptions. Idempotent.
921
+ */
922
+ unsubscribe(connId: string): void;
923
+ /**
924
+ * Records `nick` as online and enqueues a `730 RPL_MONONLINE` push to
925
+ * every watcher currently subscribed to that nick. `display` is the
926
+ * registered spelling the wire line should carry.
927
+ *
928
+ * Idempotent: a no-op when `nick` was already online (the second call
929
+ * enqueues nothing — prevents double-pushes on a `ReserveNick` for an
930
+ * already-reserved nick the runtime allowed through as a same-conn
931
+ * re-reserve).
932
+ */
933
+ onNickOnline(display: string): void;
934
+ /**
935
+ * Records `nick` as offline and enqueues a `731 RPL_MONOFFLINE` push to
936
+ * every watcher currently subscribed to that nick. Idempotent in the
937
+ * same way {@link onNickOnline} is.
938
+ */
939
+ onNickOffline(display: string): void;
940
+ /**
941
+ * Returns every display spelling currently marked online, in insertion
942
+ * order. Used by the actor's synchronous `MONITOR +` / `MONITOR S`
943
+ * resolution so the reducer can emit `730`/`731` lines without an
944
+ * O(N) `lookupNick` per requested nick.
945
+ */
946
+ onlineNicks(): string[];
947
+ /**
948
+ * Drains the queue of pending {@link MonitorPush}es the store has
949
+ * enqueued since the last drain. The actor calls this once per
950
+ * dispatched batch (after `NICK`/`QUIT` reducers release/reserve
951
+ * nicks) and turns each push into a `Send` effect for the watcher.
952
+ */
953
+ drainPushes(): MonitorPush[];
954
+ }
955
+
956
+ /**
957
+ * Reference in-memory {@link MonitorStore} used by the local CLI, the
958
+ * integration tests, and any deployment that has not bound a distributed
959
+ * backend.
960
+ *
961
+ * Backed by three plain `Map`s:
962
+ * - `watchers` connId → set of folded watched nicks.
963
+ * - `reverse` folded nick → set of watcher connIds.
964
+ * - `online` folded nick → display spelling (insertion-ordered).
965
+ *
966
+ * Plus a `pending` array of {@link MonitorPush} entries drained by the
967
+ * actor after each dispatched batch.
968
+ */
969
+ export class InMemoryMonitorStore implements MonitorStore {
970
+ private readonly watchers = new Map<string, Set<string>>();
971
+ private readonly reverse = new Map<string, Set<string>>();
972
+ private readonly online = new Map<string, string>();
973
+ private readonly pending: MonitorPush[] = [];
974
+
975
+ sync(connId: string, before: ReadonlySet<string>, after: ReadonlySet<string>): void {
976
+ // Compute the delta without mutating `before`/`after` (callers pass
977
+ // references to their own state).
978
+ const added: string[] = [];
979
+ const removed: string[] = [];
980
+ for (const n of after) if (!before.has(n)) added.push(n);
981
+ for (const n of before) if (!after.has(n)) removed.push(n);
982
+
983
+ if (added.length === 0 && removed.length === 0) return;
984
+
985
+ // Look up (or allocate) the watcher's per-connection set; cleared from
986
+ // `watchers` when it ends up empty so unsubscribed connections do not
987
+ // leak in the forward map.
988
+ let wSet = this.watchers.get(connId);
989
+ if (wSet === undefined) {
990
+ wSet = new Set<string>();
991
+ this.watchers.set(connId, wSet);
992
+ }
993
+
994
+ for (const folded of added) {
995
+ wSet.add(folded);
996
+ let watchers = this.reverse.get(folded);
997
+ if (watchers === undefined) {
998
+ watchers = new Set<string>();
999
+ this.reverse.set(folded, watchers);
1000
+ }
1001
+ watchers.add(connId);
1002
+ }
1003
+ for (const folded of removed) {
1004
+ wSet.delete(folded);
1005
+ // The forward (`watchers`) and reverse indexes are kept in lockstep
1006
+ // by sync, so any folded nick present in `before` has a
1007
+ // corresponding reverse entry. The non-null assertion encodes that
1008
+ // invariant; the alternative `if (watchers === undefined) return`
1009
+ // would introduce an unreachable branch that violates the project's
1010
+ // 100% branch-coverage threshold.
1011
+ // biome-ignore lint/style/noNonNullAssertion: invariant — see above.
1012
+ const watchers = this.reverse.get(folded)!;
1013
+ watchers.delete(connId);
1014
+ if (watchers.size === 0) this.reverse.delete(folded);
1015
+ }
1016
+ if (wSet.size === 0) this.watchers.delete(connId);
1017
+ }
1018
+
1019
+ unsubscribe(connId: string): void {
1020
+ const wSet = this.watchers.get(connId);
1021
+ if (wSet === undefined) return;
1022
+ for (const folded of wSet) {
1023
+ // Same invariant as in `sync`: the forward/reverse indexes are kept
1024
+ // in lockstep, so every folded nick in `wSet` has a reverse entry.
1025
+ // biome-ignore lint/style/noNonNullAssertion: invariant — see above.
1026
+ const watchers = this.reverse.get(folded)!;
1027
+ watchers.delete(connId);
1028
+ if (watchers.size === 0) this.reverse.delete(folded);
1029
+ }
1030
+ this.watchers.delete(connId);
1031
+ }
1032
+
1033
+ onNickOnline(display: string): void {
1034
+ const folded = display.toLowerCase();
1035
+ if (this.online.has(folded)) return;
1036
+ this.online.set(folded, display);
1037
+ const watchers = this.reverse.get(folded);
1038
+ if (watchers === undefined) return;
1039
+ for (const connId of watchers) {
1040
+ this.pending.push({ connId, display, status: 'online' });
1041
+ }
1042
+ }
1043
+
1044
+ onNickOffline(display: string): void {
1045
+ const folded = display.toLowerCase();
1046
+ if (!this.online.has(folded)) return;
1047
+ this.online.delete(folded);
1048
+ const watchers = this.reverse.get(folded);
1049
+ if (watchers === undefined) return;
1050
+ for (const connId of watchers) {
1051
+ this.pending.push({ connId, display, status: 'offline' });
1052
+ }
1053
+ }
1054
+
1055
+ onlineNicks(): string[] {
1056
+ return Array.from(this.online.values());
1057
+ }
1058
+
1059
+ drainPushes(): MonitorPush[] {
1060
+ return this.pending.splice(0);
1061
+ }
1062
+ }
1063
+
675
1064
  // ============================================================================
676
1065
  // Network statistics (LUSERS / STATS)
677
1066
  // ============================================================================
@@ -9,6 +9,14 @@ export {
9
9
  formatServerTime,
10
10
  } from './outbound.js';
11
11
  export { wrapBatch, type BatchFrame } from './batch.js';
12
+ export {
13
+ LABELED_RESPONSE_CAP_NAME,
14
+ LABEL_TAG,
15
+ applyLabelToEffects,
16
+ type LabelApplyOptions,
17
+ extractLabel,
18
+ wrapLabeledResponse,
19
+ } from './labeled-response.js';
12
20
  export { decodeBase64, encodeBase64 } from './base64.js';
13
21
  export {
14
22
  formatNumeric,
@@ -17,3 +25,9 @@ export {
17
25
  numericToName,
18
26
  Numerics,
19
27
  } from './numerics.js';
28
+ export {
29
+ type ReplyKind,
30
+ type StandardReplyMapping,
31
+ numericToStandardReply,
32
+ toStandardReply,
33
+ } from './standard-replies.js';