@guren/server 2.35.0 → 2.37.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 (54) hide show
  1. package/dist/{DocsViewerServiceProvider-BVPZjwQp.js → DocsViewerServiceProvider-DzrxQoYh.js} +15 -4
  2. package/dist/Event-COT3f5Xd.js +28 -0
  3. package/dist/{McpServiceProvider-CXOokGax.js → McpServiceProvider-BOeQyt7u.js} +2 -0
  4. package/dist/PrivateChannel-1krGz028.js +187 -0
  5. package/dist/{Resource-y-7zzZSB.js → Resource-PhnO_wNO.js} +113 -12
  6. package/dist/agent/derive.d.ts +23 -1
  7. package/dist/agent/dispatch.d.ts +12 -1
  8. package/dist/agent/pipeline.d.ts +6 -0
  9. package/dist/agent/public.d.ts +1 -1
  10. package/dist/agent/public.js +1 -1
  11. package/dist/{api-token-1-INqeVU.js → api-token-Cs1myxf6.js} +15 -1
  12. package/dist/auth/SessionGuard.d.ts +20 -0
  13. package/dist/auth/index.js +2 -2
  14. package/dist/auth/providers/ModelUserProvider.d.ts +3 -0
  15. package/dist/auth/types.d.ts +7 -0
  16. package/dist/{auth-CO9MlQNE.js → auth-X27d4l78.js} +88 -6
  17. package/dist/broadcasting/BroadcastManager.d.ts +19 -5
  18. package/dist/broadcasting/event-target.d.ts +9 -0
  19. package/dist/broadcasting/index.d.ts +3 -1
  20. package/dist/broadcasting/index.js +3 -2
  21. package/dist/broadcasting/sender-envelope.d.ts +26 -0
  22. package/dist/broadcasting/types.d.ts +27 -2
  23. package/dist/{broadcasting-D04a3R02.js → broadcasting-Bh6QoMpy.js} +50 -95
  24. package/dist/{contained-path-BkNSBljW.js → contained-path-DOVauNQC.js} +1 -22
  25. package/dist/{dev-banner-BUrHz-LF.js → dev-banner-Uydpgbrm.js} +3 -3
  26. package/dist/{dispatch-ENWpBxbE.js → dispatch-CDNqcB3Q.js} +51 -12
  27. package/dist/events/index.js +2 -1
  28. package/dist/{events-B6gfJkCH.js → events-DW197Nur.js} +2 -28
  29. package/dist/http/vite-dev-server.d.ts +18 -1
  30. package/dist/http/vite-manifest.d.ts +4 -1
  31. package/dist/index.d.ts +7 -7
  32. package/dist/index.js +110 -23
  33. package/dist/internal/agent-principal.d.ts +8 -0
  34. package/dist/internal/testing.d.ts +1 -0
  35. package/dist/internal/testing.js +2 -2
  36. package/dist/mail/index.js +1 -1
  37. package/dist/mail/types.d.ts +9 -0
  38. package/dist/{mail-BQ2y2U5c.js → mail-D4AP4_Wd.js} +6 -1
  39. package/dist/mcp/index.js +1 -1
  40. package/dist/mvc/Router.d.ts +13 -0
  41. package/dist/mvc/inertia/InertiaEngine.d.ts +3 -0
  42. package/dist/mvc/inertia/props.d.ts +54 -3
  43. package/dist/runtime/index.js +5 -3
  44. package/dist/storage/index.js +1 -1
  45. package/dist/{storage-YPbsV9ju.js → storage-ziIKgHON.js} +2 -1
  46. package/dist/trim-slashes-BLY9hKAa.js +22 -0
  47. package/dist/vite/index.d.ts +2 -0
  48. package/dist/vite/index.js +283 -1
  49. package/dist/vite/mcp-app.d.ts +59 -0
  50. package/dist/vite/plugin.d.ts +12 -0
  51. package/dist/{vite-manifest-DO0pU1vm.js → vite-dev-server-Ag90otai.js} +25 -114
  52. package/dist/vite-manifest-BdXRybeq.js +129 -0
  53. package/package.json +2 -2
  54. package/dist/host-port-t6wQFaRu.js +0 -15
@@ -25,6 +25,9 @@ export declare class ModelUserProvider<User extends Authenticatable = Authentica
25
25
  validateCredentials(user: User, credentials: AuthCredentials): Promise<boolean>;
26
26
  getId(user: User): unknown;
27
27
  rehashPasswordIfRequired(user: User, credentials: AuthCredentials): Promise<void>;
28
+ private opens;
29
+ /** A digest, so the hash itself never reaches the session store. */
30
+ credentialFingerprint(user: User): string | null | undefined;
28
31
  /** forceUpdate keyed on the id column: both credential columns are denied to mass assignment. */
29
32
  private writeColumn;
30
33
  /**
@@ -37,6 +37,13 @@ export interface UserProvider<User = Authenticatable> {
37
37
  * hash needs it, and persist the new value.
38
38
  */
39
39
  rehashPasswordIfRequired?(user: User, credentials: AuthCredentials): Promise<void> | void;
40
+ /**
41
+ * A digest of the credential a password change replaces. `SessionGuard`
42
+ * stores it at login and ends a session whose copy differs from it.
43
+ * `null`: the account has no such credential. `undefined`: this record does
44
+ * not carry it (a sanitized one), so the guard reads the stored record.
45
+ */
46
+ credentialFingerprint?(user: User): Promise<string | null | undefined> | string | null | undefined;
40
47
  }
41
48
  /** The conventional credential column names `ModelUserProvider.sanitize()` strips. */
42
49
  export type DefaultSanitizedKeys = 'password' | 'passwordHash' | 'password_hash' | 'rememberToken' | 'remember_token';
@@ -1,6 +1,6 @@
1
1
  import { o as getAppKeyringFromEnv, r as deriveAppKeyring, t as MessageSigner } from "./MessageSigner-DIUT1Yao.js";
2
2
  import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
3
- import { A as secureStringCompare, D as hashToken, E as generateToken, N as readAgentPrincipal, O as parseTokenUrl, T as generateId, c as hasBearerHeader, k as secureCompare, l as parseApiToken, m as tokenAuthenticatesRequest, p as revokePresentedToken, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, w as buildTokenUrl } from "./api-token-1-INqeVU.js";
3
+ import { A as secureStringCompare, D as hashToken, E as generateToken, O as parseTokenUrl, P as readAgentPrincipal, T as generateId, c as hasBearerHeader, k as secureCompare, l as parseApiToken, m as tokenAuthenticatesRequest, p as revokePresentedToken, t as API_TOKEN_KEY, u as readBearerToken, v as verifyApiToken, w as buildTokenUrl } from "./api-token-Cs1myxf6.js";
4
4
  import { a as setResolvedPrincipal, i as getResolvedPrincipal, o as AuthenticationException, r as getAuthContext } from "./context--l2HdOhy.js";
5
5
  import { d as verifyPassword, o as needsRehash, r as hashPassword } from "./Hash-D2DFd8xX.js";
6
6
  import { t as redactQueryParams } from "./redact-query-params-Ba-sAfcP.js";
@@ -808,10 +808,25 @@ var ModelUserProvider = class extends BaseUserProvider {
808
808
  const hashed = user[this.passwordColumn];
809
809
  if (typeof plain !== "string" || typeof hashed !== "string" || !this.hasher.needsRehash?.(hashed)) return;
810
810
  const rehashed = await this.hasher.hash(plain);
811
- user[this.passwordColumn] = rehashed;
811
+ const where = {
812
+ [this.idColumn]: this.getId(user),
813
+ [this.passwordColumn]: hashed
814
+ };
812
815
  const writer = passwordHashWriter(this.model);
813
- if (writer) await writer.storePasswordHash({ [this.idColumn]: this.getId(user) }, this.passwordColumn, rehashed);
814
- else await this.writeColumn(user, this.passwordColumn, rehashed);
816
+ if (writer) await writer.storePasswordHash(where, this.passwordColumn, rehashed);
817
+ else await this.model.forceUpdate(where, { [this.passwordColumn]: rehashed });
818
+ const stored = await this.retrieveById(this.getId(user));
819
+ const current = stored ? stored[this.passwordColumn] : void 0;
820
+ if (current === rehashed || await this.opens(current, plain)) user[this.passwordColumn] = current;
821
+ }
822
+ async opens(hashed, plain) {
823
+ return typeof hashed === "string" && looksLikePasswordHash(hashed) && await this.hasher.verify(hashed, plain);
824
+ }
825
+ /** A digest, so the hash itself never reaches the session store. */
826
+ credentialFingerprint(user) {
827
+ const hashed = user[this.passwordColumn];
828
+ if (hashed === void 0) return void 0;
829
+ return typeof hashed === "string" && hashed !== "" ? hashToken(hashed) : null;
815
830
  }
816
831
  /** forceUpdate keyed on the id column: both credential columns are denied to mass assignment. */
817
832
  async writeColumn(user, column, value) {
@@ -882,6 +897,10 @@ var SessionGuard = class {
882
897
  this.currentSession.forget(this.rememberSessionKey());
883
898
  return null;
884
899
  }
900
+ if (!await this.holdsCurrentCredential(this.currentSession, user)) {
901
+ this.forgetLogin(this.currentSession);
902
+ return null;
903
+ }
885
904
  await this.provider.setRememberToken?.(user, rememberToken);
886
905
  const sanitized = this.sanitizeUser(user);
887
906
  this.cachedUser = sanitized;
@@ -890,6 +909,60 @@ var SessionGuard = class {
890
909
  sanitizeUser(user) {
891
910
  return sanitizeUser(this.provider, user);
892
911
  }
912
+ fingerprintSessionKey() {
913
+ return `${this.sessionKey()}:fingerprint`;
914
+ }
915
+ /**
916
+ * Whether the session was opened under the credential `user` holds now. A
917
+ * session with no fingerprint fails for an account that has a credential:
918
+ * nothing shows it was opened under the current one.
919
+ */
920
+ async holdsCurrentCredential(session, user) {
921
+ const current = await this.provider.credentialFingerprint?.(user);
922
+ const stored = session.get(this.fingerprintSessionKey());
923
+ if (current == null) return stored == null;
924
+ return typeof stored === "string" && secureStringCompare(stored, current);
925
+ }
926
+ async bindCredential(session, user, identifier) {
927
+ const provider = this.provider;
928
+ if (!provider.credentialFingerprint) return;
929
+ let fingerprint = await provider.credentialFingerprint(user);
930
+ if (fingerprint === void 0) {
931
+ const stored = await provider.retrieveById(identifier);
932
+ fingerprint = stored ? await provider.credentialFingerprint(stored) : void 0;
933
+ }
934
+ if (typeof fingerprint === "string") session.set(this.fingerprintSessionKey(), fingerprint);
935
+ else session.forget(this.fingerprintSessionKey());
936
+ }
937
+ /**
938
+ * validate() may rehash the password of the user this session belongs to
939
+ * (a profile form confirming the current password). The session moves to the
940
+ * new hash, or its own next request would read as a password change.
941
+ */
942
+ async followRehash(user, before, owner) {
943
+ const session = this.currentSession;
944
+ if (!session || typeof before !== "string") return;
945
+ const after = await this.provider.credentialFingerprint?.(user);
946
+ if (typeof after !== "string" || after === before) return;
947
+ if (owner == null || owner !== this.provider.getId(user)) return;
948
+ const stored = session.get(this.fingerprintSessionKey());
949
+ if (typeof stored === "string" && secureStringCompare(stored, before)) session.set(this.fingerprintSessionKey(), after);
950
+ }
951
+ /**
952
+ * Whose session this is. A remembered session carries no id key, and must be
953
+ * resolved before a rehash: afterwards its fingerprint reads as stale.
954
+ */
955
+ async sessionUserId() {
956
+ const identifier = this.currentSession?.get(this.sessionKey());
957
+ if (identifier != null) return identifier;
958
+ const user = await this.resolveUser();
959
+ return user ? this.provider.getId(user) : null;
960
+ }
961
+ forgetLogin(session) {
962
+ session.forget(this.sessionKey());
963
+ session.forget(this.rememberSessionKey());
964
+ session.forget(this.fingerprintSessionKey());
965
+ }
893
966
  async resolveUser() {
894
967
  if (this.cachedUser !== void 0) return this.cachedUser;
895
968
  const session = this.currentSession;
@@ -909,6 +982,11 @@ var SessionGuard = class {
909
982
  this.cachedUser = null;
910
983
  return null;
911
984
  }
985
+ if (!await this.holdsCurrentCredential(session, user)) {
986
+ this.forgetLogin(session);
987
+ this.cachedUser = null;
988
+ return null;
989
+ }
912
990
  const sanitized = this.sanitizeUser(user);
913
991
  this.cachedUser = sanitized;
914
992
  return sanitized;
@@ -925,6 +1003,7 @@ var SessionGuard = class {
925
1003
  async id() {
926
1004
  const session = this.currentSession;
927
1005
  if (!session) return null;
1006
+ if (this.provider.credentialFingerprint && !await this.resolveUser()) return null;
928
1007
  return session.get(this.sessionKey()) ?? null;
929
1008
  }
930
1009
  async remember(user) {
@@ -940,6 +1019,7 @@ var SessionGuard = class {
940
1019
  session.regenerate();
941
1020
  const identifier = this.provider.getId(castUser);
942
1021
  session.set(this.sessionKey(), identifier);
1022
+ await this.bindCredential(session, castUser, identifier);
943
1023
  this.cachedUser = this.sanitizeUser(castUser);
944
1024
  if (remember) await this.remember(castUser);
945
1025
  else session.forget(this.rememberSessionKey());
@@ -947,8 +1027,7 @@ var SessionGuard = class {
947
1027
  async logout() {
948
1028
  const session = this.currentSession;
949
1029
  if (!session) return;
950
- session.forget(this.sessionKey());
951
- session.forget(this.rememberSessionKey());
1030
+ this.forgetLogin(session);
952
1031
  this.cachedUser = null;
953
1032
  }
954
1033
  async attempt(credentials, remember = false) {
@@ -964,11 +1043,14 @@ var SessionGuard = class {
964
1043
  return null;
965
1044
  }
966
1045
  if (!await this.provider.validateCredentials(user, credentials)) return null;
1046
+ const fingerprint = await this.provider.credentialFingerprint?.(user);
1047
+ const owner = typeof fingerprint === "string" ? await this.sessionUserId() : null;
967
1048
  try {
968
1049
  await this.provider.rehashPasswordIfRequired?.(user, credentials);
969
1050
  } catch (error) {
970
1051
  console.warn(`[guren] Rehashing the password for user ${this.describeUser(user)} failed; the login continues.`, redactQueryParams(error));
971
1052
  }
1053
+ await this.followRehash(user, fingerprint, owner);
972
1054
  return user;
973
1055
  }
974
1056
  /** Never the plaintext or the hash: a warning is a log line, and both belong in neither. */
@@ -1,4 +1,4 @@
1
- import type { BroadcastDriver, BroadcastDriverFactory, BroadcastManagerOptions, ChannelAuthorizer, PresenceChannelAuthorizer, ChannelRegistration, SSEMiddlewareOptions, WebSocketMiddlewareOptions, AuthMiddlewareOptions, SSEClient, WebSocketClient, BroadcastEvent } from './types.js';
1
+ import type { BroadcastDriver, BroadcastDriverFactory, BroadcastManagerOptions, ChannelAuthorizer, PresenceChannelAuthorizer, ChannelRegistration, SSEMiddlewareOptions, WebSocketMiddlewareOptions, AuthMiddlewareOptions, SSEClient, WebSocketClient, BroadcastEvent, BroadcastEventOptions, BroadcastableEvent } from './types.js';
2
2
  import { Channel, PrivateChannel, PresenceChannel } from './channels/index.js';
3
3
  import type { Middleware } from '../http/middleware/index.js';
4
4
  /** Broadcast manager for real-time event broadcasting. */
@@ -23,6 +23,20 @@ export declare class BroadcastManager {
23
23
  privateChannel(pattern: string, authorizer: ChannelAuthorizer): this;
24
24
  presenceChannel(pattern: string, authorizer: PresenceChannelAuthorizer): this;
25
25
  broadcast(channelName: string, event: string, data: unknown): Promise<void>;
26
+ /**
27
+ * Publishes `broadcastWith()` (else `{}`) as `broadcastNameOf(event)` on every
28
+ * channel `broadcastOn()` names: the name a `live()` prop listening for this
29
+ * event subscribes to.
30
+ */
31
+ broadcastEvent(event: BroadcastableEvent, options?: BroadcastEventOptions): Promise<void>;
32
+ /** A sender is only worth marking with a socket id this manager could have issued and a user to bind it to. */
33
+ private resolveSender;
34
+ /**
35
+ * What one client receives of a delivered event: nothing when it is the
36
+ * sender's own socket, else the payload without the reserved fields. The ids
37
+ * compare strictly, as `authMiddleware()` compares an owner: `7` is not `'7'`.
38
+ */
39
+ private deliveryFor;
26
40
  toChannel(name: string): Channel;
27
41
  toPrivate(name: string): PrivateChannel;
28
42
  toPresence(name: string): PresenceChannel;
@@ -37,9 +51,9 @@ export declare class BroadcastManager {
37
51
  /**
38
52
  * A route that upgrades to a WebSocket carrying broadcast events, the socket
39
53
  * counterpart of `sseMiddleware()`; it needs `Application.listen()` on Bun.
40
- * Frames are JSON. The server sends `{ event, data }`, first `connected` with
41
- * `{ clientId, channels }`; the client sends `{ action: 'subscribe' | 'unsubscribe',
42
- * channel }`, answered by a `subscription` event, and anything else is ignored.
54
+ * JSON frames: an event `{ event, channel, data }`, the server's own `{ event, data }`
55
+ * (first `connected` with `{ clientId, socketId, channels }`). The client sends
56
+ * `{ action: 'subscribe' | 'unsubscribe', channel }`, answered by `subscription`.
43
57
  */
44
58
  webSocketMiddleware(options?: WebSocketMiddlewareOptions): Middleware;
45
59
  private handleWebSocketMessage;
@@ -64,7 +78,7 @@ export declare class BroadcastManager {
64
78
  */
65
79
  protected releaseDriverSubscriptions(clientId: string): void;
66
80
  /** Returns the generated client ID. */
67
- registerWebSocketClient(client: Omit<WebSocketClient, 'id' | 'channels'> & {
81
+ registerWebSocketClient(client: Omit<WebSocketClient, 'id' | 'channels' | 'socketId'> & {
68
82
  userId?: string | number;
69
83
  }): string;
70
84
  removeWebSocketClient(clientId: string): boolean;
@@ -0,0 +1,9 @@
1
+ import type { BroadcastableEvent } from './types.js';
2
+ /** An event as `live()` and `broadcastEvent()` read it. `eventName` is `Event`'s own getter. */
3
+ export type BroadcastTarget = Pick<BroadcastableEvent, 'broadcastOn' | 'broadcastAs'> & {
4
+ readonly eventName?: string;
5
+ };
6
+ /** `broadcastAs()`, else the event's `eventName`, else its class name. */
7
+ export declare function broadcastNameOf(event: BroadcastTarget): string;
8
+ /** The wire names `broadcastOn()` returns, prefix included, verbatim. */
9
+ export declare function broadcastChannelsOf(event: BroadcastTarget): string[];
@@ -1,6 +1,8 @@
1
- export type { BroadcastEvent, BroadcastDriver, PresenceBroadcastDriver, ChannelAuthorizer, PresenceChannelAuthorizer, PresenceMember, SSEClient, WebSocketClient, BroadcastManagerOptions, BroadcastDriverFactory, ChannelRegistration, SSEMiddlewareOptions, WebSocketMiddlewareOptions, AuthMiddlewareOptions, BroadcastableEvent, } from './types.js';
1
+ export type { BroadcastEvent, BroadcastDriver, PresenceBroadcastDriver, ChannelAuthorizer, PresenceChannelAuthorizer, PresenceMember, SSEClient, WebSocketClient, BroadcastManagerOptions, BroadcastDriverFactory, ChannelRegistration, SSEMiddlewareOptions, WebSocketMiddlewareOptions, AuthMiddlewareOptions, BroadcastableEvent, BroadcastEventOptions, BroadcastSender, } from './types.js';
2
2
  export { BroadcastManager, setBroadcastManager, getBroadcastManager, createBroadcastManager, } from './BroadcastManager.js';
3
3
  export { createTypedBroadcaster, } from './typed.js';
4
+ export { broadcastChannelsOf, broadcastNameOf } from './event-target.js';
5
+ export type { BroadcastTarget } from './event-target.js';
4
6
  export type { TypedBroadcaster, TypedChannelHandle, TypedPrivateChannelHandle, TypedPresenceChannelHandle, } from './typed.js';
5
7
  export { Channel, PrivateChannel, PresenceChannel } from './channels/index.js';
6
8
  export { MemoryDriver, RedisDriver, type MemoryDriverOptions, type RedisClient, type RedisDriverOptions, } from './drivers/index.js';
@@ -1,2 +1,3 @@
1
- import { a as setBroadcastManager, c as PresenceChannel, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "../broadcasting-D04a3R02.js";
2
- export { BroadcastManager, Channel, MemoryDriver, PresenceChannel, PrivateChannel, RedisDriver, createBroadcastManager, createTypedBroadcaster, getBroadcastManager, setBroadcastManager };
1
+ import { l as broadcastChannelsOf, n as PresenceChannel, r as Channel, t as PrivateChannel, u as broadcastNameOf } from "../PrivateChannel-1krGz028.js";
2
+ import { a as setBroadcastManager, i as getBroadcastManager, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster } from "../broadcasting-Bh6QoMpy.js";
3
+ export { BroadcastManager, Channel, MemoryDriver, PresenceChannel, PrivateChannel, RedisDriver, broadcastChannelsOf, broadcastNameOf, createBroadcastManager, createTypedBroadcaster, getBroadcastManager, setBroadcastManager };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The sender of a broadcast, carried inside its payload (RFC 0037 §4) so every
3
+ * driver passes it across instances. `__inertia.socketId` and `__inertia.userId`
4
+ * are reserved: every manager publish path strips them from what the app passes
5
+ * before marking, so a relayed payload cannot forge a mark, and delivery strips
6
+ * them before any client sees the payload.
7
+ */
8
+ export interface BroadcastSenderMark {
9
+ readonly socketId: string;
10
+ readonly userId: string | number;
11
+ }
12
+ export declare function isSocketId(value: unknown): value is string;
13
+ /** A user id that survives JSON as itself: `NaN` and the infinities become `null` on the Redis driver. */
14
+ export declare function isSenderUserId(value: unknown): value is string | number;
15
+ /**
16
+ * The payload with the sender added. An object that is not plain (a class
17
+ * instance, one with `toJSON()`) is marked as the JSON a client would receive;
18
+ * an array or a primitive cannot carry a mark.
19
+ */
20
+ export declare function markSender(data: unknown, sender: BroadcastSenderMark): unknown;
21
+ export declare function readSender(data: unknown): BroadcastSenderMark | undefined;
22
+ /**
23
+ * The payload without the reserved fields, valid or not, and without the
24
+ * envelope once nothing else is in it.
25
+ */
26
+ export declare function stripSender(data: unknown): unknown;
@@ -31,16 +31,41 @@ export interface SSEClient {
31
31
  id: string;
32
32
  userId?: string | number;
33
33
  channels: Set<string>;
34
- send(event: string, data: unknown): void;
34
+ /** `channel` is the one an event arrived on; absent on control events (`connected`, `ping`). */
35
+ send(event: string, data: unknown, channel?: string): void;
35
36
  close(): void;
36
37
  }
37
38
  export interface WebSocketClient {
38
39
  id: string;
39
40
  userId?: string | number;
41
+ /**
42
+ * Issued by `registerWebSocketClient()` and sent in `connected`: the value a
43
+ * request names as `X-Socket-Id` to skip its own broadcast (RFC 0037 §4).
44
+ */
45
+ socketId?: string;
40
46
  channels: Set<string>;
41
- send(event: string, data: unknown): void | Promise<void>;
47
+ /** `channel` is the one an event arrived on; absent on control events (`connected`, `subscription`). */
48
+ send(event: string, data: unknown, channel?: string): void | Promise<void>;
42
49
  close(): void;
43
50
  }
51
+ /** Who sent a broadcast, so their own sockets can be skipped. */
52
+ export interface BroadcastSender {
53
+ /** The `X-Socket-Id` the request carried. */
54
+ readonly socketId?: string | null;
55
+ readonly user?: unknown;
56
+ }
57
+ export interface BroadcastEventOptions {
58
+ /**
59
+ * Skip the sender's own socket: the request's context (its `X-Socket-Id`
60
+ * header and signed-in user), or the two given by hand. Only a socket owned
61
+ * by that same user is skipped.
62
+ */
63
+ readonly except?: BroadcastSender | {
64
+ readonly req: {
65
+ header(name: string): string | undefined;
66
+ };
67
+ } | null;
68
+ }
44
69
  export interface BroadcastManagerOptions {
45
70
  default?: string;
46
71
  drivers?: Record<string, BroadcastDriverFactory>;
@@ -1,5 +1,6 @@
1
1
  import { a as parseRequestPayload, t as asRecord } from "./request-CLOYytGP.js";
2
2
  import { g as warnDeprecatedSetter, h as warnDeprecatedGetter, i as bindAmbient, n as ambientBinding } from "./default-application-s9SE-Er7.js";
3
+ import { a as isSocketId, c as stripSender, i as isSenderUserId, l as broadcastChannelsOf, n as PresenceChannel, o as markSender, r as Channel, s as readSender, t as PrivateChannel, u as broadcastNameOf } from "./PrivateChannel-1krGz028.js";
3
4
  import { r as getAuthContext } from "./context--l2HdOhy.js";
4
5
  import { t as redactQueryParams } from "./redact-query-params-Ba-sAfcP.js";
5
6
  import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-W2fH-GID.js";
@@ -43,93 +44,6 @@ function createWebSocketOriginGuard(options = {}) {
43
44
  };
44
45
  }
45
46
  //#endregion
46
- //#region src/broadcasting/channels/Channel.ts
47
- var Channel = class {
48
- name;
49
- driver;
50
- constructor(name, driver) {
51
- this.name = name;
52
- this.driver = driver;
53
- }
54
- async broadcast(event, data) {
55
- await this.driver.publish(this.name, event, data);
56
- }
57
- /** Returns an unsubscribe function. */
58
- subscribe(callback) {
59
- return this.driver.subscribe(this.name, (e) => {
60
- callback(e.event, e.data);
61
- });
62
- }
63
- getChannelName() {
64
- return this.name;
65
- }
66
- };
67
- //#endregion
68
- //#region src/broadcasting/channels/PrivateChannel.ts
69
- /** Broadcast channel that requires authentication to subscribe. */
70
- var PrivateChannel = class PrivateChannel extends Channel {
71
- static PREFIX = "private-";
72
- constructor(name, driver) {
73
- const channelName = name.startsWith(PrivateChannel.PREFIX) ? name : `${PrivateChannel.PREFIX}${name}`;
74
- super(channelName, driver);
75
- }
76
- getBaseName() {
77
- return this.name.startsWith(PrivateChannel.PREFIX) ? this.name.slice(PrivateChannel.PREFIX.length) : this.name;
78
- }
79
- static isPrivateChannel(name) {
80
- return name.startsWith(PrivateChannel.PREFIX);
81
- }
82
- static normalize(name) {
83
- return name.startsWith(PrivateChannel.PREFIX) ? name : `${PrivateChannel.PREFIX}${name}`;
84
- }
85
- };
86
- //#endregion
87
- //#region src/broadcasting/channels/PresenceChannel.ts
88
- /** Broadcast channel that tracks the members who have joined it. */
89
- var PresenceChannel = class PresenceChannel extends Channel {
90
- static PREFIX = "presence-";
91
- presenceDriver;
92
- constructor(name, driver) {
93
- const channelName = name.startsWith(PresenceChannel.PREFIX) ? name : `${PresenceChannel.PREFIX}${name}`;
94
- super(channelName, driver);
95
- if (this.isPresenceDriver(driver)) this.presenceDriver = driver;
96
- else throw new Error("Driver does not support presence channels. Ensure the driver implements PresenceBroadcastDriver interface.");
97
- }
98
- isPresenceDriver(driver) {
99
- return "getMembers" in driver && "addMember" in driver && "removeMember" in driver;
100
- }
101
- members() {
102
- return this.presenceDriver.getMembers(this.name);
103
- }
104
- async join(member) {
105
- this.presenceDriver.addMember(this.name, member);
106
- await this.broadcast("presence:joining", { member });
107
- }
108
- async leave(memberId) {
109
- const member = this.members().find((m) => m.id === memberId);
110
- this.presenceDriver.removeMember(this.name, memberId);
111
- if (member) await this.broadcast("presence:leaving", { member });
112
- }
113
- hasMember(memberId) {
114
- return this.members().some((m) => m.id === memberId);
115
- }
116
- getMember(memberId) {
117
- return this.members().find((m) => m.id === memberId);
118
- }
119
- count() {
120
- return this.members().length;
121
- }
122
- getBaseName() {
123
- return this.name.startsWith(PresenceChannel.PREFIX) ? this.name.slice(PresenceChannel.PREFIX.length) : this.name;
124
- }
125
- static isPresenceChannel(name) {
126
- return name.startsWith(PresenceChannel.PREFIX);
127
- }
128
- static normalize(name) {
129
- return name.startsWith(PresenceChannel.PREFIX) ? name : `${PresenceChannel.PREFIX}${name}`;
130
- }
131
- };
132
- //#endregion
133
47
  //#region src/broadcasting/drivers/MemoryDriver.ts
134
48
  /**
135
49
  * Keeps subscriptions and presence data in memory — for testing and
@@ -465,7 +379,39 @@ var BroadcastManager = class {
465
379
  return this;
466
380
  }
467
381
  async broadcast(channelName, event, data) {
468
- await this.driver().publish(channelName, event, data);
382
+ await this.driver().publish(channelName, event, stripSender(data));
383
+ }
384
+ /**
385
+ * Publishes `broadcastWith()` (else `{}`) as `broadcastNameOf(event)` on every
386
+ * channel `broadcastOn()` names: the name a `live()` prop listening for this
387
+ * event subscribes to.
388
+ */
389
+ async broadcastEvent(event, options = {}) {
390
+ const name = broadcastNameOf(event);
391
+ const payload = stripSender(event.broadcastWith?.() ?? {});
392
+ const sender = options.except ? await this.resolveSender(options.except) : void 0;
393
+ const data = sender ? markSender(payload, sender) : payload;
394
+ for (const channel of broadcastChannelsOf(event)) await this.driver().publish(channel, name, data);
395
+ }
396
+ /** A sender is only worth marking with a socket id this manager could have issued and a user to bind it to. */
397
+ async resolveSender(except) {
398
+ const fromContext = "req" in except;
399
+ const socketId = fromContext ? except.req.header("X-Socket-Id") : except.socketId;
400
+ if (!isSocketId(socketId)) return void 0;
401
+ const userId = resolveClientUserId(fromContext ? await resolveRequestUser(except, void 0) : except.user);
402
+ return isSenderUserId(userId) ? {
403
+ socketId,
404
+ userId
405
+ } : void 0;
406
+ }
407
+ /**
408
+ * What one client receives of a delivered event: nothing when it is the
409
+ * sender's own socket, else the payload without the reserved fields. The ids
410
+ * compare strictly, as `authMiddleware()` compares an owner: `7` is not `'7'`.
411
+ */
412
+ deliveryFor(client, data) {
413
+ const sender = readSender(data);
414
+ return sender !== void 0 && "socketId" in client && client.socketId === sender.socketId && client.userId !== void 0 && client.userId === sender.userId ? void 0 : { data: stripSender(data) };
469
415
  }
470
416
  toChannel(name) {
471
417
  return new Channel(name, this.driver());
@@ -577,9 +523,9 @@ var BroadcastManager = class {
577
523
  /**
578
524
  * A route that upgrades to a WebSocket carrying broadcast events, the socket
579
525
  * counterpart of `sseMiddleware()`; it needs `Application.listen()` on Bun.
580
- * Frames are JSON. The server sends `{ event, data }`, first `connected` with
581
- * `{ clientId, channels }`; the client sends `{ action: 'subscribe' | 'unsubscribe',
582
- * channel }`, answered by a `subscription` event, and anything else is ignored.
526
+ * JSON frames: an event `{ event, channel, data }`, the server's own `{ event, data }`
527
+ * (first `connected` with `{ clientId, socketId, channels }`). The client sends
528
+ * `{ action: 'subscribe' | 'unsubscribe', channel }`, answered by `subscription`.
583
529
  */
584
530
  webSocketMiddleware(options = {}) {
585
531
  const isAllowedOrigin = webSocketOriginCheck(options.allowedOrigins);
@@ -597,8 +543,12 @@ var BroadcastManager = class {
597
543
  const { upgradeWebSocket } = await import("hono/bun");
598
544
  return await upgradeWebSocket(() => ({
599
545
  onOpen: (_event, ws) => {
600
- const send = (event, data) => ws.send(JSON.stringify({
546
+ const send = (event, data, channel) => ws.send(JSON.stringify(channel === void 0 ? {
547
+ event,
548
+ data
549
+ } : {
601
550
  event,
551
+ channel,
602
552
  data
603
553
  }));
604
554
  clientId = this.registerWebSocketClient({
@@ -606,8 +556,10 @@ var BroadcastManager = class {
606
556
  send,
607
557
  close: () => ws.close()
608
558
  });
559
+ const { socketId } = this.wsClients.get(clientId);
609
560
  send("connected", {
610
561
  clientId,
562
+ socketId,
611
563
  channels: authorizedChannels
612
564
  });
613
565
  for (const channelName of authorizedChannels) this.subscribeWebSocketClient(clientId, channelName);
@@ -689,7 +641,8 @@ var BroadcastManager = class {
689
641
  if (!client) return false;
690
642
  client.channels.add(channel);
691
643
  this.openDriverSubscription(clientId, channel, (event) => {
692
- if (client.channels.has(channel)) client.send(event.event, event.data);
644
+ const delivery = client.channels.has(channel) ? this.deliveryFor(client, event.data) : void 0;
645
+ if (delivery) client.send(event.event, delivery.data, channel);
693
646
  });
694
647
  return true;
695
648
  }
@@ -735,6 +688,7 @@ var BroadcastManager = class {
735
688
  this.wsClients.set(clientId, {
736
689
  ...client,
737
690
  id: clientId,
691
+ socketId: `s_${randomHex(16)}`,
738
692
  channels: /* @__PURE__ */ new Set()
739
693
  });
740
694
  return clientId;
@@ -757,7 +711,8 @@ var BroadcastManager = class {
757
711
  if (!client) return false;
758
712
  client.channels.add(channel);
759
713
  this.openDriverSubscription(clientId, channel, async (event) => {
760
- if (client.channels.has(channel)) await client.send(event.event, event.data);
714
+ const delivery = client.channels.has(channel) ? this.deliveryFor(client, event.data) : void 0;
715
+ if (delivery) await client.send(event.event, delivery.data, channel);
761
716
  });
762
717
  return true;
763
718
  }
@@ -868,4 +823,4 @@ function wrapChannel(name, channel) {
868
823
  };
869
824
  }
870
825
  //#endregion
871
- export { setBroadcastManager as a, PresenceChannel as c, createWebSocketOriginGuard as d, getBroadcastManager as i, PrivateChannel as l, BroadcastManager as n, RedisDriver as o, createBroadcastManager as r, MemoryDriver as s, createTypedBroadcaster as t, Channel as u };
826
+ export { setBroadcastManager as a, createWebSocketOriginGuard as c, getBroadcastManager as i, BroadcastManager as n, RedisDriver as o, createBroadcastManager as r, MemoryDriver as s, createTypedBroadcaster as t };
@@ -1,26 +1,5 @@
1
1
  import { basename, dirname, join, sep } from "node:path";
2
2
  import { realpath } from "node:fs/promises";
3
- //#region src/support/trim-slashes.ts
4
- /**
5
- * No regex: patterns like `/\/+$/` backtrack quadratically on long slash runs
6
- * mid-string, and several call sites feed request-derived paths.
7
- *
8
- * Twins that cannot import this module: `@guren/cli` (`src/utils.ts`) and
9
- * `@guren/plugin-cloudflare` (`src/storage/R2Driver.ts`) — keep them in step.
10
- */
11
- function trimTrailingSlashes(value) {
12
- let end = value.length;
13
- while (end > 0 && value[end - 1] === "/") end--;
14
- return value.slice(0, end);
15
- }
16
- function trimSlashes(value) {
17
- let start = 0;
18
- let end = value.length;
19
- while (start < end && value[start] === "/") start++;
20
- while (end > start && value[end - 1] === "/") end--;
21
- return value.slice(start, end);
22
- }
23
- //#endregion
24
3
  //#region src/support/contained-path.ts
25
4
  /**
26
5
  * Lexical containment. The trailing separator keeps out a sibling whose name
@@ -75,4 +54,4 @@ async function realPathOfNearestExisting(path) {
75
54
  }
76
55
  }
77
56
  //#endregion
78
- export { trimTrailingSlashes as a, trimSlashes as i, isRealPathWithin as n, realPathOfNearestExisting as r, isPathWithin as t };
57
+ export { isRealPathWithin as n, realPathOfNearestExisting as r, isPathWithin as t };
@@ -1,10 +1,10 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.js";
2
- import { n as isWildcardHost, t as formatHostPort } from "./host-port-t6wQFaRu.js";
2
+ import { d as formatHostPort, f as isWildcardHost, t as DEFAULT_DEV_SERVER_URL } from "./vite-manifest-BdXRybeq.js";
3
3
  import chalk from "chalk";
4
4
  import figlet from "figlet";
5
5
  import standard from "figlet/importable-fonts/Standard.js";
6
6
  //#region package.json
7
- var version = "2.35.0";
7
+ var version = "2.37.0";
8
8
  //#endregion
9
9
  //#region src/http/dev-banner.ts
10
10
  var dev_banner_exports = /* @__PURE__ */ __exportAll({
@@ -30,7 +30,7 @@ const ASSET_SERVER_LABELS = {
30
30
  managed: "Vite, started by Guren",
31
31
  external: "not started by Guren, run it yourself"
32
32
  };
33
- function logDevServerBanner({ hostname, port, assetsUrl = "http://localhost:5173", assetServer }) {
33
+ function logDevServerBanner({ hostname, port, assetsUrl = DEFAULT_DEV_SERVER_URL, assetServer }) {
34
34
  const localUrl = `http://localhost:${port}`;
35
35
  const boundUrl = `http://${formatHostPort(hostname, port)}`;
36
36
  const boundLabel = isWildcardHost(hostname) ? " (all interfaces)" : "";