@socket-mesh/server 18.0.5 → 18.1.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 (73) hide show
  1. package/README.md +6 -6
  2. package/dist/broker/broker-events.d.ts +16 -0
  3. package/dist/broker/broker.d.ts +28 -0
  4. package/dist/broker/broker.js +17 -0
  5. package/dist/broker/exchange-client.d.ts +5 -0
  6. package/dist/broker/exchange.d.ts +4 -0
  7. package/dist/broker/exchange.js +3 -0
  8. package/dist/broker/simple-broker.d.ts +16 -0
  9. package/dist/broker/simple-broker.js +65 -0
  10. package/dist/broker/simple-exchange.d.ts +13 -0
  11. package/dist/broker/simple-exchange.js +33 -0
  12. package/dist/handlers/authenticate.d.ts +20 -0
  13. package/dist/handlers/authenticate.js +67 -0
  14. package/dist/handlers/handshake.d.ts +7 -0
  15. package/dist/handlers/handshake.js +61 -0
  16. package/dist/handlers/publish.d.ts +9 -0
  17. package/dist/handlers/publish.js +21 -0
  18. package/dist/handlers/remove-auth-token.d.ts +3 -0
  19. package/dist/handlers/remove-auth-token.js +7 -0
  20. package/dist/handlers/subscribe.d.ts +7 -0
  21. package/dist/handlers/subscribe.js +43 -0
  22. package/dist/handlers/unsubscribe.d.ts +6 -0
  23. package/dist/handlers/unsubscribe.js +9 -0
  24. package/dist/index.d.ts +30 -0
  25. package/{index.js → dist/index.js} +6 -6
  26. package/dist/maps/client-map.d.ts +10 -0
  27. package/dist/maps/client-map.js +1 -0
  28. package/dist/maps/server-map.d.ts +24 -0
  29. package/dist/maps/server-map.js +1 -0
  30. package/dist/maps/socket-map.d.ts +19 -0
  31. package/dist/maps/socket-map.js +1 -0
  32. package/dist/plugin/server-plugin.d.ts +33 -0
  33. package/dist/plugin/server-plugin.js +2 -0
  34. package/dist/server-event.d.ts +54 -0
  35. package/dist/server-event.js +1 -0
  36. package/dist/server-options.d.ts +25 -0
  37. package/dist/server-options.js +1 -0
  38. package/dist/server-socket-state.d.ts +6 -0
  39. package/dist/server-socket-state.js +1 -0
  40. package/dist/server-socket.d.ts +27 -0
  41. package/dist/server-socket.js +47 -0
  42. package/dist/server-transport.d.ts +39 -0
  43. package/dist/server-transport.js +246 -0
  44. package/dist/server.d.ts +125 -0
  45. package/dist/server.js +266 -0
  46. package/package.json +33 -47
  47. package/action.d.ts +0 -106
  48. package/action.js +0 -141
  49. package/auth-engine.d.ts +0 -13
  50. package/auth-engine.js +0 -32
  51. package/events.d.ts +0 -54
  52. package/inbound-packet.d.ts +0 -48
  53. package/inbound-packet.js +0 -18
  54. package/index.d.ts +0 -32
  55. package/middleware-stream.d.ts +0 -7
  56. package/middleware-stream.js +0 -8
  57. package/middleware-type.d.ts +0 -6
  58. package/middleware-type.js +0 -7
  59. package/outbound-packet.d.ts +0 -25
  60. package/outbound-packet.js +0 -3
  61. package/remote-procedure.d.ts +0 -13
  62. package/remote-procedure.js +0 -9
  63. package/request.d.ts +0 -24
  64. package/request.js +0 -16
  65. package/server-options.d.ts +0 -38
  66. package/server.d.ts +0 -113
  67. package/server.js +0 -361
  68. package/serversocket.d.ts +0 -182
  69. package/serversocket.js +0 -1262
  70. package/socket-state.d.ts +0 -5
  71. package/socket-state.js +0 -6
  72. /package/{events.js → dist/broker/broker-events.js} +0 -0
  73. /package/{server-options.js → dist/broker/exchange-client.js} +0 -0
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
- # SocketCluster server
2
- Minimal server module for SocketCluster.
1
+ # SocketMesh server
2
+ Minimal server module for SocketMesh.
3
3
 
4
- This is a stand-alone server module for SocketCluster.
4
+ This is a stand-alone server module for SocketMesh.
5
5
  SocketCluster's protocol is backwards compatible with the SocketCluster protocol.
6
6
 
7
7
  ## Setting up
@@ -82,16 +82,16 @@ let agServer = socketClusterServer.attach(httpServer, {
82
82
  - **More readable**: Code is written sequentially from top to bottom. It avoids event handler callback hell. It's also much easier to write and read complex integration test scenarios.
83
83
  - **More succinct**: Event streams can be easily chained, filtered and combined using a declarative syntax (e.g. using async generators).
84
84
  - **More manageable**: No need to remember to unbind listeners with `removeListener(...)`; just `break` out of the `for-await-of` loop to stop consuming. This also encourages a more declarative style of coding which reduces the likelihood of memory leaks and unintended side effects.
85
- - **Less error-prone**: Each event/RPC/message can be processed sequentially in the same order that they were sent without missing any data; even if asynchronous calls are made inside middleware or listeners. On the other hand, with `EventEmitter`, the listener function for the same event cannot be prevented from running multiple times in parallel; also, asynchronous calls within middleware and listeners can affect the final order of actions; all this can cause unintended side effects.
85
+ - **Less error-prone**: Each event/RPC/message can be processed sequentially in the same order that they were sent without missing any data; even if asynchronous calls are made inside plugin or listeners. On the other hand, with `EventEmitter`, the listener function for the same event cannot be prevented from running multiple times in parallel; also, asynchronous calls within plugin and listeners can affect the final order of actions; all this can cause unintended side effects.
86
86
 
87
87
  ## License
88
88
 
89
89
  (The MIT License)
90
90
 
91
- Copyright (c) 2013-2023 SocketCluster.io
91
+ Copyright (c) 2013-2024 SocketMesh.io
92
92
 
93
93
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
94
94
 
95
95
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
96
96
 
97
- THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
97
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,16 @@
1
+ export type BrokerEvent<T> = ErrorEvent | PublishEvent<T> | ReadyEvent | SubscribeEvent | UnsubscribeEvent;
2
+ export interface ErrorEvent {
3
+ error: Error;
4
+ }
5
+ export interface ReadyEvent {
6
+ }
7
+ export interface SubscribeEvent {
8
+ channel: string;
9
+ }
10
+ export interface UnsubscribeEvent {
11
+ channel: string;
12
+ }
13
+ export interface PublishEvent<T> {
14
+ channel: string;
15
+ data: T;
16
+ }
@@ -0,0 +1,28 @@
1
+ import { AsyncStreamEmitter } from "@socket-mesh/async-stream-emitter";
2
+ import { DemuxedConsumableStream, StreamEvent } from "@socket-mesh/stream-demux";
3
+ import { BrokerEvent, ErrorEvent, PublishEvent, ReadyEvent, SubscribeEvent, UnsubscribeEvent } from "./broker-events.js";
4
+ import { ChannelMap } from "@socket-mesh/channels";
5
+ import { Exchange } from "./exchange.js";
6
+ import { ExchangeClient } from "./exchange-client.js";
7
+ export declare abstract class Broker<T extends ChannelMap> extends AsyncStreamEmitter<BrokerEvent<T[keyof T]>> {
8
+ isReady: boolean;
9
+ constructor();
10
+ emit(event: 'error', data: ErrorEvent): void;
11
+ emit(event: 'publish', data: PublishEvent<T[keyof T]>): void;
12
+ emit(event: 'ready', data: ReadyEvent): void;
13
+ emit(event: 'subscribe', data: SubscribeEvent): void;
14
+ emit(event: 'unsubscribe', data: UnsubscribeEvent): void;
15
+ listen(): DemuxedConsumableStream<StreamEvent<BrokerEvent<T[keyof T]>>>;
16
+ listen(event: 'ready'): DemuxedConsumableStream<ReadyEvent>;
17
+ listen(event: 'publish'): DemuxedConsumableStream<PublishEvent<T[keyof T]>>;
18
+ listen(event: 'error'): DemuxedConsumableStream<ErrorEvent>;
19
+ listen(event: 'subscribe'): DemuxedConsumableStream<SubscribeEvent>;
20
+ listen(event: 'unsubscribe'): DemuxedConsumableStream<UnsubscribeEvent>;
21
+ abstract readonly exchange: Exchange<T>;
22
+ abstract subscribe(socket: ExchangeClient, channelName: string): Promise<void>;
23
+ abstract subscriptions(): string[];
24
+ abstract isSubscribed(channelName: string): boolean;
25
+ abstract unsubscribe(socket: ExchangeClient, channelName: string): Promise<void>;
26
+ abstract transmitPublish<U extends keyof T & string>(channelName: U, data: T[U], suppressEvent?: boolean): Promise<void>;
27
+ abstract invokePublish<U extends keyof T & string>(channelName: U, data: T[U], suppressEvent?: boolean): Promise<void>;
28
+ }
@@ -0,0 +1,17 @@
1
+ import { AsyncStreamEmitter } from "@socket-mesh/async-stream-emitter";
2
+ export class Broker extends AsyncStreamEmitter {
3
+ constructor() {
4
+ super();
5
+ this.isReady = false;
6
+ setTimeout(() => {
7
+ this.isReady = true;
8
+ this.emit('ready', {});
9
+ }, 0);
10
+ }
11
+ emit(event, data) {
12
+ super.emit(event, data);
13
+ }
14
+ listen(event) {
15
+ return super.listen(event);
16
+ }
17
+ }
@@ -0,0 +1,5 @@
1
+ import { PublishOptions } from "@socket-mesh/channels";
2
+ export interface ExchangeClient {
3
+ id: string;
4
+ transmit(event: '#publish', options: PublishOptions): Promise<void>;
5
+ }
@@ -0,0 +1,4 @@
1
+ import { ChannelMap, Channels } from "@socket-mesh/channels";
2
+ export declare abstract class Exchange<T extends ChannelMap> extends Channels<T> {
3
+ id: string;
4
+ }
@@ -0,0 +1,3 @@
1
+ import { Channels } from "@socket-mesh/channels";
2
+ export class Exchange extends Channels {
3
+ }
@@ -0,0 +1,16 @@
1
+ import { Broker } from "./broker.js";
2
+ import { ChannelMap } from "@socket-mesh/channels";
3
+ import { SimpleExchange } from "./simple-exchange.js";
4
+ import { ExchangeClient } from "./exchange-client.js";
5
+ export declare class SimpleBroker<T extends ChannelMap> extends Broker<T> {
6
+ readonly exchange: SimpleExchange<T>;
7
+ private readonly _clientSubscribers;
8
+ private readonly _clientSubscribersCounter;
9
+ constructor();
10
+ subscribe(client: ExchangeClient, channelName: string): Promise<void>;
11
+ unsubscribe(client: ExchangeClient, channelName: string): Promise<void>;
12
+ subscriptions(): string[];
13
+ isSubscribed(channelName: string): boolean;
14
+ invokePublish<U extends keyof T & string>(channelName: U, data: T[U], suppressEvent?: boolean): Promise<void>;
15
+ transmitPublish<U extends keyof T & string>(channelName: U, data: T[U], suppressEvent?: boolean): Promise<void>;
16
+ }
@@ -0,0 +1,65 @@
1
+ import { Broker } from "./broker.js";
2
+ import { SimpleExchange } from "./simple-exchange.js";
3
+ export class SimpleBroker extends Broker {
4
+ constructor() {
5
+ super();
6
+ this.exchange = new SimpleExchange(this);
7
+ this._clientSubscribers = {};
8
+ this._clientSubscribersCounter = {};
9
+ }
10
+ async subscribe(client, channelName) {
11
+ if (!this._clientSubscribers[channelName]) {
12
+ this._clientSubscribers[channelName] = {};
13
+ this._clientSubscribersCounter[channelName] = 0;
14
+ this.emit('subscribe', { channel: channelName });
15
+ }
16
+ if (!this._clientSubscribers[channelName][client.id]) {
17
+ this._clientSubscribersCounter[channelName]++;
18
+ }
19
+ this._clientSubscribers[channelName][client.id] = client;
20
+ }
21
+ async unsubscribe(client, channelName) {
22
+ if (this._clientSubscribers[channelName]) {
23
+ if (this._clientSubscribers[channelName][client.id]) {
24
+ this._clientSubscribersCounter[channelName]--;
25
+ delete this._clientSubscribers[channelName][client.id];
26
+ if (this._clientSubscribersCounter[channelName] <= 0) {
27
+ delete this._clientSubscribers[channelName];
28
+ delete this._clientSubscribersCounter[channelName];
29
+ this.emit('unsubscribe', { channel: channelName });
30
+ }
31
+ }
32
+ }
33
+ }
34
+ subscriptions() {
35
+ return Object.keys(this._clientSubscribers);
36
+ }
37
+ isSubscribed(channelName) {
38
+ return !!this._clientSubscribers[channelName];
39
+ }
40
+ // In this implementation of the broker engine, both invokePublish and transmitPublish
41
+ // methods are the same. In alternative implementations, they could be different.
42
+ invokePublish(channelName, data, suppressEvent) {
43
+ return this.transmitPublish(channelName, data, suppressEvent);
44
+ }
45
+ async transmitPublish(channelName, data, suppressEvent) {
46
+ const packet = {
47
+ channel: channelName,
48
+ data
49
+ };
50
+ const subscriberClients = this._clientSubscribers[channelName] || {};
51
+ const work = [];
52
+ for (const i in subscriberClients) {
53
+ work.push(subscriberClients[i].transmit('#publish', packet));
54
+ }
55
+ const result = await Promise.allSettled(work);
56
+ for (const item of result) {
57
+ if (item.status === 'rejected') {
58
+ this.emit('error', item.reason);
59
+ }
60
+ }
61
+ if (!suppressEvent) {
62
+ this.emit('publish', packet);
63
+ }
64
+ }
65
+ }
@@ -0,0 +1,13 @@
1
+ import { ChannelDetails, ChannelMap, ChannelsOptions, PublishOptions } from "@socket-mesh/channels";
2
+ import { Broker } from "./broker.js";
3
+ import { Exchange } from "./exchange.js";
4
+ export declare class SimpleExchange<T extends ChannelMap> extends Exchange<T> {
5
+ readonly id: string;
6
+ private readonly _broker;
7
+ constructor(broker: Broker<T>, options?: ChannelsOptions);
8
+ protected trySubscribe(channel: ChannelDetails): Promise<void>;
9
+ protected tryUnsubscribe(channel: ChannelDetails): Promise<void>;
10
+ transmit(event: '#publish', packet: PublishOptions): Promise<void>;
11
+ transmitPublish<U extends keyof T & string>(channelName: U, data: T[U]): Promise<void>;
12
+ invokePublish<U extends keyof T & string>(channelName: U, data: T[U]): Promise<void>;
13
+ }
@@ -0,0 +1,33 @@
1
+ import { Exchange } from "./exchange.js";
2
+ export class SimpleExchange extends Exchange {
3
+ constructor(broker, options) {
4
+ super(options);
5
+ this.id = 'exchange';
6
+ this._broker = broker;
7
+ }
8
+ async trySubscribe(channel) {
9
+ channel.state = 'subscribed';
10
+ this._channelEventDemux.write(`${channel.name}/subscribe`, { channel: channel.name });
11
+ this._broker.subscribe(this, channel.name);
12
+ this.emit('subscribe', { channel: channel.name, options: channel.options });
13
+ }
14
+ async tryUnsubscribe(channel) {
15
+ delete this._channelMap[channel.name];
16
+ if (channel.state === 'subscribed') {
17
+ this._channelEventDemux.write(`${channel.name}/unsubscribe`, { channel: channel.name });
18
+ await this._broker.unsubscribe(this, channel.name);
19
+ this.emit('unsubscribe', { channel: channel.name });
20
+ }
21
+ }
22
+ async transmit(event, packet) {
23
+ if (event === '#publish') {
24
+ this._channelDataDemux.write(packet.channel, packet.data);
25
+ }
26
+ }
27
+ async transmitPublish(channelName, data) {
28
+ await this._broker.transmitPublish(channelName, data);
29
+ }
30
+ async invokePublish(channelName, data) {
31
+ await this._broker.invokePublish(channelName, data);
32
+ }
33
+ }
@@ -0,0 +1,20 @@
1
+ import { RequestHandlerArgs, SocketTransport } from "@socket-mesh/core";
2
+ import jwt from "jsonwebtoken";
3
+ import { AuthTokenError } from "@socket-mesh/errors";
4
+ import { AuthEngine } from "@socket-mesh/auth-engine";
5
+ import { AuthToken, SignedAuthToken } from "@socket-mesh/auth";
6
+ import { BasicSocketMapServer } from "../maps/socket-map.js";
7
+ import { ServerSocket } from "../server-socket.js";
8
+ import { BasicServerMap } from "../maps/server-map.js";
9
+ export type AuthInfo = ValidAuthInfo | InvalidAuthInfo;
10
+ export interface InvalidAuthInfo {
11
+ signedAuthToken: SignedAuthToken;
12
+ authError: AuthTokenError;
13
+ }
14
+ export interface ValidAuthInfo {
15
+ signedAuthToken: SignedAuthToken;
16
+ authToken: AuthToken;
17
+ }
18
+ export declare function authenticateHandler({ isRpc, options: signedAuthToken, socket, transport }: RequestHandlerArgs<string, BasicSocketMapServer, ServerSocket<BasicServerMap>>): Promise<void>;
19
+ export declare function validateAuthToken(auth: AuthEngine, authToken: SignedAuthToken, verificationOptions?: jwt.VerifyOptions): Promise<AuthInfo>;
20
+ export declare function processAuthentication(socket: ServerSocket<BasicServerMap>, transport: SocketTransport<BasicSocketMapServer>, authInfo: AuthInfo): Promise<boolean>;
@@ -0,0 +1,67 @@
1
+ import { AuthTokenError, AuthTokenExpiredError, AuthTokenInvalidError, AuthTokenNotBeforeError, InvalidActionError } from "@socket-mesh/errors";
2
+ const HANDSHAKE_REJECTION_STATUS_CODE = 4008;
3
+ ;
4
+ export async function authenticateHandler({ isRpc, options: signedAuthToken, socket, transport }) {
5
+ if (!isRpc) {
6
+ socket.disconnect(HANDSHAKE_REJECTION_STATUS_CODE);
7
+ throw new InvalidActionError('Handshake request was malformatted');
8
+ }
9
+ const authInfo = await validateAuthToken(socket.server.auth, signedAuthToken);
10
+ await processAuthentication(socket, transport, authInfo);
11
+ }
12
+ export async function validateAuthToken(auth, authToken, verificationOptions) {
13
+ try {
14
+ return {
15
+ signedAuthToken: authToken,
16
+ authToken: await auth.verifyToken(authToken, verificationOptions)
17
+ };
18
+ }
19
+ catch (error) {
20
+ return {
21
+ signedAuthToken: authToken,
22
+ authError: processTokenError(error)
23
+ };
24
+ }
25
+ }
26
+ function processTokenError(err) {
27
+ if (err.name === 'TokenExpiredError' && 'expiredAt' in err) {
28
+ return new AuthTokenExpiredError(err.message, err.expiredAt);
29
+ }
30
+ if (err.name === 'JsonWebTokenError') {
31
+ return new AuthTokenInvalidError(err.message);
32
+ }
33
+ if (err.name === 'NotBeforeError' && 'date' in err) {
34
+ // In this case, the token is good; it's just not active yet.
35
+ return new AuthTokenNotBeforeError(err.message, err.date);
36
+ }
37
+ return new AuthTokenError(err.message);
38
+ }
39
+ export async function processAuthentication(socket, transport, authInfo) {
40
+ if ('authError' in authInfo) {
41
+ await transport.changeToUnauthenticatedState();
42
+ // If the error is related to the JWT being badly formatted, then we will
43
+ // treat the error as a socket error.
44
+ if (authInfo.signedAuthToken != null) {
45
+ transport.onError(authInfo.authError);
46
+ if (authInfo.authError instanceof AuthTokenError) {
47
+ socket.emit('badAuthToken', { error: authInfo.authError, signedAuthToken: authInfo.signedAuthToken });
48
+ }
49
+ }
50
+ throw authInfo.authError;
51
+ }
52
+ for (const plugin of socket.server.plugins) {
53
+ if (plugin.onAuthenticate) {
54
+ try {
55
+ plugin.onAuthenticate(authInfo);
56
+ }
57
+ catch (err) {
58
+ await transport.changeToUnauthenticatedState();
59
+ if (err instanceof AuthTokenError) {
60
+ socket.emit('badAuthToken', { error: err, signedAuthToken: authInfo.signedAuthToken });
61
+ }
62
+ throw err;
63
+ }
64
+ }
65
+ }
66
+ return await transport.setAuthorization(authInfo.signedAuthToken, authInfo.authToken);
67
+ }
@@ -0,0 +1,7 @@
1
+ import { HandshakeOptions, HandshakeStatus } from "@socket-mesh/client";
2
+ import { RequestHandlerArgs } from "@socket-mesh/core";
3
+ import { BasicServerMap } from "../maps/server-map.js";
4
+ import { BasicSocketMapServer } from "../maps/socket-map.js";
5
+ import { ServerSocket } from "../server-socket.js";
6
+ import { ServerTransport } from "../server-transport.js";
7
+ export declare function handshakeHandler({ options, socket, transport }: RequestHandlerArgs<HandshakeOptions, BasicSocketMapServer, ServerSocket<BasicServerMap>, ServerTransport<BasicServerMap>>): Promise<HandshakeStatus>;
@@ -0,0 +1,61 @@
1
+ import { wait } from "@socket-mesh/core";
2
+ import { processAuthentication, validateAuthToken } from "./authenticate.js";
3
+ import { dehydrateError } from "@socket-mesh/errors";
4
+ const HANDSHAKE_REJECTION_STATUS_CODE = 4008;
5
+ export async function handshakeHandler({ options, socket, transport }) {
6
+ const server = socket.server;
7
+ const wasAuthenticated = !!transport.signedAuthToken;
8
+ const authInfo = await validateAuthToken(server.auth, options.authToken);
9
+ for (const plugin of server.plugins) {
10
+ if (plugin.onHandshake) {
11
+ try {
12
+ await plugin.onHandshake({
13
+ socket,
14
+ transport,
15
+ authInfo: 'authError' in authInfo ?
16
+ { signedAuthToken: options.authToken, authError: authInfo.authError } :
17
+ { signedAuthToken: options.authToken, authToken: authInfo.authToken }
18
+ });
19
+ }
20
+ catch (err) {
21
+ if (err.statusCode == null) {
22
+ err.statusCode = HANDSHAKE_REJECTION_STATUS_CODE;
23
+ }
24
+ throw err;
25
+ }
26
+ }
27
+ }
28
+ let authError = undefined;
29
+ let changed;
30
+ try {
31
+ changed = await processAuthentication(socket, transport, authInfo);
32
+ if (socket.status === 'closed') {
33
+ return;
34
+ }
35
+ }
36
+ catch (err) {
37
+ if (options.authToken) {
38
+ // Because the token is optional as part of the handshake, we don't count
39
+ // it as an error if the token wasn't provided.
40
+ authError = dehydrateError(err);
41
+ }
42
+ }
43
+ transport.setReadyStatus(server.pingTimeoutMs, authError);
44
+ // Needs to be executed after the connection event to allow consumers to be setup.
45
+ await wait(0);
46
+ if (changed) {
47
+ transport.triggerAuthenticationEvents(false, wasAuthenticated);
48
+ }
49
+ if (authError) {
50
+ return {
51
+ id: socket.id,
52
+ pingTimeoutMs: server.pingTimeoutMs,
53
+ authError
54
+ };
55
+ }
56
+ return {
57
+ id: socket.id,
58
+ pingTimeoutMs: server.pingTimeoutMs,
59
+ authToken: options.authToken
60
+ };
61
+ }
@@ -0,0 +1,9 @@
1
+ import { RequestHandlerArgs } from "@socket-mesh/core";
2
+ import { BasicSocketMapServer } from "../maps/socket-map.js";
3
+ import { PublishOptions } from "@socket-mesh/channels";
4
+ import { ServerSocket } from "../server-socket.js";
5
+ import { BasicServerMap } from "../maps/server-map.js";
6
+ import { ServerTransport } from "../server-transport.js";
7
+ export declare function publishHandler({ socket, transport, options }: RequestHandlerArgs<PublishOptions, BasicSocketMapServer<{}, {
8
+ [channel: string]: any;
9
+ }>, ServerSocket<BasicServerMap>, ServerTransport<BasicServerMap>>): Promise<void>;
@@ -0,0 +1,21 @@
1
+ import { InvalidActionError } from "@socket-mesh/errors";
2
+ export async function publishHandler({ socket, transport, options }) {
3
+ if (!socket.server.allowClientPublish) {
4
+ throw new InvalidActionError('Client publish feature is disabled');
5
+ }
6
+ if (typeof options.channel !== 'string' || !options.data) {
7
+ throw new InvalidActionError('Publish channel name was malformatted');
8
+ }
9
+ let data = options.data;
10
+ for (const plugin of socket.server.plugins) {
11
+ if (plugin.onPublishIn) {
12
+ data = await plugin.onPublishIn({
13
+ channel: options.channel,
14
+ data,
15
+ socket,
16
+ transport
17
+ });
18
+ }
19
+ }
20
+ await socket.server.exchange.invokePublish(options.channel, data);
21
+ }
@@ -0,0 +1,3 @@
1
+ import { BasicSocketMapServer } from "../maps/socket-map.js";
2
+ import { SocketTransport } from "@socket-mesh/core";
3
+ export declare function deauthenticate(transport: SocketTransport<BasicSocketMapServer>): Promise<boolean>;
@@ -0,0 +1,7 @@
1
+ export async function deauthenticate(transport) {
2
+ if (await transport.changeToUnauthenticatedState()) {
3
+ await transport.transmit('#removeAuthToken');
4
+ return true;
5
+ }
6
+ return false;
7
+ }
@@ -0,0 +1,7 @@
1
+ import { BasicServerMap } from "../maps/server-map.js";
2
+ import { BasicSocketMapServer } from "../maps/socket-map.js";
3
+ import { SubscribeOptions } from "@socket-mesh/client";
4
+ import { RequestHandlerArgs } from "@socket-mesh/core";
5
+ import { ServerSocket } from "../server-socket.js";
6
+ import { ServerTransport } from "../server-transport.js";
7
+ export declare function subscribeHandler({ socket, transport, options }: RequestHandlerArgs<SubscribeOptions, BasicSocketMapServer, ServerSocket<BasicServerMap>, ServerTransport<BasicServerMap>>): Promise<void>;
@@ -0,0 +1,43 @@
1
+ import { BrokerError, InvalidActionError } from "@socket-mesh/errors";
2
+ export async function subscribeHandler({ socket, transport, options }) {
3
+ if (socket.status !== 'ready') {
4
+ // This is an invalid state; it means the client tried to subscribe before
5
+ // having completed the handshake.
6
+ throw new InvalidActionError('Cannot subscribe socket to a channel before it has completed the handshake');
7
+ }
8
+ const state = socket.state;
9
+ const server = socket.server;
10
+ if (server.socketChannelLimit && state.channelSubscriptionsCount >= server.socketChannelLimit) {
11
+ throw new InvalidActionError(`Socket ${socket.id} tried to exceed the channel subscription limit of ${server.socketChannelLimit}`);
12
+ }
13
+ const { channel, ...channelOptions } = options;
14
+ for (const plugin of socket.server.plugins) {
15
+ if (plugin.onSubscribe) {
16
+ await plugin.onSubscribe({ channel, options, socket, transport });
17
+ }
18
+ }
19
+ try {
20
+ if (state.channelSubscriptions == null) {
21
+ state.channelSubscriptions = {};
22
+ }
23
+ if (state.channelSubscriptionsCount == null) {
24
+ state.channelSubscriptionsCount = 0;
25
+ }
26
+ if (state.channelSubscriptions[channel] == null) {
27
+ state.channelSubscriptions[channel] = true;
28
+ state.channelSubscriptionsCount++;
29
+ }
30
+ try {
31
+ await server.brokerEngine.subscribe(transport, channel);
32
+ }
33
+ catch (error) {
34
+ delete state.channelSubscriptions[channel];
35
+ state.channelSubscriptionsCount--;
36
+ throw error;
37
+ }
38
+ server.exchange.emit('subscribe', { channel, options: channelOptions });
39
+ }
40
+ catch (err) {
41
+ throw new BrokerError(`Failed to subscribe socket to the ${options.channel} channel - ${err}`);
42
+ }
43
+ }
@@ -0,0 +1,6 @@
1
+ import { RequestHandlerArgs } from "@socket-mesh/core";
2
+ import { BasicSocketMapServer } from "../maps/socket-map.js";
3
+ import { ServerSocket } from "../server-socket.js";
4
+ import { BasicServerMap } from "../maps/server-map.js";
5
+ import { ServerTransport } from "../server-transport.js";
6
+ export declare function unsubscribeHandler({ transport, options: channel }: RequestHandlerArgs<string, BasicSocketMapServer, ServerSocket<BasicServerMap>, ServerTransport<BasicServerMap>>): Promise<void>;
@@ -0,0 +1,9 @@
1
+ import { BrokerError } from "@socket-mesh/errors";
2
+ export async function unsubscribeHandler({ transport, options: channel }) {
3
+ try {
4
+ await transport.unsubscribe(channel);
5
+ }
6
+ catch (err) {
7
+ throw new BrokerError(`Failed to unsubscribe socket from the ${channel} channel - ${err}`);
8
+ }
9
+ }
@@ -0,0 +1,30 @@
1
+ import http from "http";
2
+ import { Server } from "./server.js";
3
+ import { ServerOptions } from "./server-options.js";
4
+ import { ServerMap } from "./maps/server-map.js";
5
+ export { Server } from "./server.js";
6
+ export { ServerSocket } from "./server-socket.js";
7
+ export { PluginType } from "@socket-mesh/core";
8
+ export { BasicServerMap } from "./maps/server-map.js";
9
+ export { BasicSocketMapServer } from "./maps/socket-map.js";
10
+ /**
11
+ * Creates an http.Server exclusively used for WS upgrades.
12
+ *
13
+ * @param {Number} port
14
+ * @param {Function} callback
15
+ * @param {Object} options
16
+ * @return {AGServer} websocket cluster server
17
+ * @api public
18
+ */
19
+ export declare function listen<T extends ServerMap>(): Server<T>;
20
+ export declare function listen<T extends ServerMap>(port: number, options: ServerOptions<T>): Server<T>;
21
+ export declare function listen<T extends ServerMap>(port: number, options: ServerOptions<T>, fn: () => void): Server<T>;
22
+ /**
23
+ * Captures upgrade requests for a http.Server.
24
+ *
25
+ * @param {http.Server} server
26
+ * @param {Object} options
27
+ * @return {AGServer} websocket cluster server
28
+ * @api public
29
+ */
30
+ export declare function attach<T extends ServerMap>(server: http.Server, options?: ServerOptions<T>): Server<T>;
@@ -1,21 +1,21 @@
1
1
  import http from "http";
2
2
  import { Server } from "./server.js";
3
3
  export { Server } from "./server.js";
4
- export { ServerSocket } from "./serversocket.js";
5
- export { SocketState } from "./socket-state.js";
6
- export { MiddlewareType } from "./middleware-type.js";
7
- export * from "./action.js";
4
+ export { ServerSocket } from "./server-socket.js";
8
5
  export function listen(port, options, fn) {
9
6
  if (typeof options === 'function') {
10
7
  fn = options;
11
8
  options = {};
12
9
  }
10
+ else if (!options) {
11
+ options = {};
12
+ }
13
13
  const server = http.createServer((req, res) => {
14
14
  res.writeHead(501);
15
15
  res.end('Not Implemented');
16
16
  });
17
+ options.server = server;
17
18
  const socketClusterServer = attach(server, options);
18
- socketClusterServer.httpServer = server;
19
19
  server.listen(port, fn);
20
20
  return socketClusterServer;
21
21
  }
@@ -32,7 +32,7 @@ export function attach(server, options) {
32
32
  if (options == null) {
33
33
  options = {};
34
34
  }
35
- options.httpServer = server;
35
+ options.server = server;
36
36
  return new Server(options);
37
37
  }
38
38
  ;
@@ -0,0 +1,10 @@
1
+ import { PublicMethodMap } from "@socket-mesh/core";
2
+ import { ServerMap } from "./server-map.js";
3
+ export interface ClientMapFromServer<T extends ServerMap> {
4
+ Channel: T['Channel'];
5
+ Incoming: T['Outgoing'] & T['PrivateOutgoing'];
6
+ Service: T['Service'];
7
+ Outgoing: PublicMethodMap;
8
+ PrivateOutgoing: T['PrivateIncoming'];
9
+ State: object;
10
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,24 @@
1
+ import { ChannelMap } from "@socket-mesh/channels";
2
+ import { ClientPrivateMap, ServerPrivateMap } from "@socket-mesh/client";
3
+ import { PrivateMethodMap, PublicMethodMap, ServiceMap } from "@socket-mesh/core";
4
+ import { ServerSocketState } from "../server-socket-state.js";
5
+ export interface ServerMap {
6
+ Channel: ChannelMap;
7
+ Service: ServiceMap;
8
+ Incoming: PublicMethodMap;
9
+ Outgoing: PublicMethodMap;
10
+ PrivateIncoming: PrivateMethodMap;
11
+ PrivateOutgoing: PrivateMethodMap;
12
+ ServerState: object;
13
+ State: object;
14
+ }
15
+ export interface BasicServerMap<TIncoming extends PublicMethodMap = {}, TChannels extends ChannelMap = {}, TState extends object = {}, TOutgoing extends object = {}> {
16
+ Channel: TChannels;
17
+ Service: {};
18
+ Incoming: TIncoming;
19
+ Outgoing: TOutgoing;
20
+ PrivateIncoming: ServerPrivateMap;
21
+ PrivateOutgoing: ClientPrivateMap;
22
+ ServerState: {};
23
+ State: TState & ServerSocketState;
24
+ }
@@ -0,0 +1 @@
1
+ export {};