@nage-api/realtime 1.0.0-beta.2
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.
- package/LICENSE +202 -0
- package/README.md +88 -0
- package/dist/gateway.d.ts +54 -0
- package/dist/gateway.js +157 -0
- package/dist/handshake.d.ts +21 -0
- package/dist/handshake.js +54 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +28 -0
- package/dist/memory.d.ts +35 -0
- package/dist/memory.js +49 -0
- package/dist/ports.d.ts +84 -0
- package/dist/ports.js +22 -0
- package/dist/realtime.module.d.ts +32 -0
- package/dist/realtime.module.js +88 -0
- package/dist/tokens.d.ts +8 -0
- package/dist/tokens.js +9 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# @nage-api/realtime
|
|
2
|
+
|
|
3
|
+
Authenticated sockets and a cross-instance propagator (PLAN.md §8, §12, §25 P2).
|
|
4
|
+
|
|
5
|
+
§12 names three specific defects in the legacy socket layer. This package exists
|
|
6
|
+
to make all three unrepresentable.
|
|
7
|
+
|
|
8
|
+
**No token in the query string.** A token in a URL is written to every access
|
|
9
|
+
log, every proxy log, every `Referer` sent to a third-party asset, and the
|
|
10
|
+
browser history. The handshake reads `Authorization: Bearer …` and nothing else
|
|
11
|
+
— and _refuses_ a connection that puts a credential in the query rather than
|
|
12
|
+
quietly ignoring it, because a client sending one has tokens in its URLs and its
|
|
13
|
+
author needs to know.
|
|
14
|
+
|
|
15
|
+
**No default guest.** A connection with no valid bearer token is refused. The
|
|
16
|
+
legacy gateway assigned an identity, which made every "authenticated" room
|
|
17
|
+
reachable by anyone who opened a socket.
|
|
18
|
+
|
|
19
|
+
**Rooms are authorised.** Joining a room named by the client is an authorization
|
|
20
|
+
decision, so `RoomPolicy.canJoin` runs on every join and the default policy
|
|
21
|
+
refuses everything — an unconfigured gateway must not be an open one. A refusal
|
|
22
|
+
never names the room back, because which rooms exist is not something an
|
|
23
|
+
unauthorised caller may enumerate.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { Module } from '@nestjs/common';
|
|
27
|
+
import { NageRealtimeModule, type Propagator, type RealtimeTransport } from '@nage-api/realtime';
|
|
28
|
+
import type { AuthUser } from '@nage-api/contracts';
|
|
29
|
+
|
|
30
|
+
// The application's own token verification, over `@nage-api/auth`: a feature package
|
|
31
|
+
// may not import a sibling feature package (§7.2), so the socket layer takes the
|
|
32
|
+
// resolution as a port.
|
|
33
|
+
declare const principals: { fromAccessToken(token: string): Promise<AuthUser> };
|
|
34
|
+
// Both bindings are yours today; neither the Socket.IO transport nor the Redis
|
|
35
|
+
// propagator is written (see "Not yet implemented").
|
|
36
|
+
declare const socketIo: RealtimeTransport;
|
|
37
|
+
declare const redisPropagator: Propagator;
|
|
38
|
+
|
|
39
|
+
@Module({
|
|
40
|
+
imports: [
|
|
41
|
+
NageRealtimeModule.forRoot({
|
|
42
|
+
realtime: { enabled: true, adapter: 'redis' },
|
|
43
|
+
authenticator: { authenticate: (token) => principals.fromAccessToken(token) },
|
|
44
|
+
roomPolicy: { canJoin: (user, room) => room === `user:${String(user.id)}` },
|
|
45
|
+
transport: socketIo,
|
|
46
|
+
propagator: redisPropagator,
|
|
47
|
+
}),
|
|
48
|
+
],
|
|
49
|
+
})
|
|
50
|
+
export class AppModule {}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`authenticator` is required and has no default, because the only possible
|
|
54
|
+
default would be "accept anyone". `realtime.enabled` must be `true`: anything
|
|
55
|
+
else contributes no providers at all, so `RealtimeGateway` is unavailable rather
|
|
56
|
+
than present and inert.
|
|
57
|
+
|
|
58
|
+
## Across instances
|
|
59
|
+
|
|
60
|
+
Without a propagator, a two-pod deployment delivers each event to whichever
|
|
61
|
+
fraction of users happens to be connected to the pod that emitted it. Events
|
|
62
|
+
carry the emitting instance's id, so an event that comes back from the
|
|
63
|
+
propagator is delivered locally exactly once rather than looping between pods.
|
|
64
|
+
|
|
65
|
+
Asking for `adapter: 'redis'` without supplying a propagator is refused —
|
|
66
|
+
accepting it would be a silent lie.
|
|
67
|
+
|
|
68
|
+
Connections per principal are bounded, because a client in a reconnect loop
|
|
69
|
+
otherwise accumulates sockets until the process runs out of file descriptors.
|
|
70
|
+
|
|
71
|
+
## Transport-independent
|
|
72
|
+
|
|
73
|
+
Which socket library carries the bytes is a binding; who may connect, who may
|
|
74
|
+
join what, and what happens on a second instance are decisions. The decisions
|
|
75
|
+
live here, where they are testable — testing them through a real socket server
|
|
76
|
+
would be testing Socket.IO.
|
|
77
|
+
|
|
78
|
+
With no `transport` supplied the gateway gets `MemoryTransport`, which records
|
|
79
|
+
every emission and delivers to nobody. That is the right default for a test and
|
|
80
|
+
the wrong one for a deployment: until the Socket.IO binding lands, a running
|
|
81
|
+
application needs a `RealtimeTransport` of its own or its events go nowhere.
|
|
82
|
+
|
|
83
|
+
## Not yet implemented
|
|
84
|
+
|
|
85
|
+
- The Socket.IO binding (§27.5) and the Redis propagator. `RealtimeTransport`
|
|
86
|
+
and `Propagator` are the seams.
|
|
87
|
+
- Per-connection rate limiting, and presence (who is in a room, across
|
|
88
|
+
instances).
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The connection registry and the authorization around it (PLAN.md §12).
|
|
3
|
+
*
|
|
4
|
+
* Transport-independent on purpose: which socket library carries the bytes is
|
|
5
|
+
* a binding, but who may connect, who may join which room, and what happens on
|
|
6
|
+
* a second instance are decisions, and they belong somewhere testable.
|
|
7
|
+
*/
|
|
8
|
+
import type { AuthUser } from '@nage-api/contracts';
|
|
9
|
+
import type { Clock, Connection, Handshake, Propagator, RealtimeTransport, RoomPolicy, SocketAuthenticator } from './ports.js';
|
|
10
|
+
export interface RealtimeGatewayOptions {
|
|
11
|
+
readonly transport: RealtimeTransport;
|
|
12
|
+
readonly authenticator: SocketAuthenticator;
|
|
13
|
+
/** Refuses every room by default; supply one to allow any. */
|
|
14
|
+
readonly roomPolicy?: RoomPolicy;
|
|
15
|
+
readonly propagator?: Propagator;
|
|
16
|
+
/** Connections one principal may hold at once. */
|
|
17
|
+
readonly maxConnectionsPerUser?: number;
|
|
18
|
+
readonly clock?: Clock;
|
|
19
|
+
}
|
|
20
|
+
/** Refuses everything. The default, so an unconfigured gateway is not open. */
|
|
21
|
+
export declare const DENY_ALL_ROOMS: RoomPolicy;
|
|
22
|
+
export declare class RealtimeGateway {
|
|
23
|
+
#private;
|
|
24
|
+
constructor(options: RealtimeGatewayOptions);
|
|
25
|
+
/**
|
|
26
|
+
* Authenticate a connection attempt.
|
|
27
|
+
*
|
|
28
|
+
* @throws AuthenticationError when there is no valid bearer token
|
|
29
|
+
*/
|
|
30
|
+
connect(handshake: Handshake): Promise<Connection>;
|
|
31
|
+
/**
|
|
32
|
+
* Admit a connection to a room.
|
|
33
|
+
*
|
|
34
|
+
* @throws AuthorizationError when the policy refuses
|
|
35
|
+
*/
|
|
36
|
+
join(connectionId: string, room: string): Promise<void>;
|
|
37
|
+
leave(connectionId: string, room: string): void;
|
|
38
|
+
disconnect(connectionId: string, reason?: string): void;
|
|
39
|
+
/**
|
|
40
|
+
* Emit to a room, locally and on every other instance.
|
|
41
|
+
*
|
|
42
|
+
* The event is stamped with this instance's id so it comes back from the
|
|
43
|
+
* propagator recognisable and is not delivered twice.
|
|
44
|
+
*/
|
|
45
|
+
emit(room: string, event: string, payload: unknown, requestId?: string): Promise<void>;
|
|
46
|
+
/** Emit to every connection a principal holds on this instance. */
|
|
47
|
+
emitToUser(userId: string, event: string, payload: unknown): number;
|
|
48
|
+
/** Connections in a room, on this instance. */
|
|
49
|
+
membersOf(room: string): readonly Connection[];
|
|
50
|
+
get connectionCount(): number;
|
|
51
|
+
connectionsFor(user: AuthUser): readonly string[];
|
|
52
|
+
close(): Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=gateway.d.ts.map
|
package/dist/gateway.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The connection registry and the authorization around it (PLAN.md §12).
|
|
4
|
+
*
|
|
5
|
+
* Transport-independent on purpose: which socket library carries the bytes is
|
|
6
|
+
* a binding, but who may connect, who may join which room, and what happens on
|
|
7
|
+
* a second instance are decisions, and they belong somewhere testable.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.RealtimeGateway = exports.DENY_ALL_ROOMS = void 0;
|
|
11
|
+
const core_1 = require("@nage-api/core");
|
|
12
|
+
const handshake_js_1 = require("./handshake.js");
|
|
13
|
+
const DEFAULT_MAX_CONNECTIONS_PER_USER = 10;
|
|
14
|
+
/** Refuses everything. The default, so an unconfigured gateway is not open. */
|
|
15
|
+
exports.DENY_ALL_ROOMS = { canJoin: () => false };
|
|
16
|
+
class RealtimeGateway {
|
|
17
|
+
#transport;
|
|
18
|
+
#authenticator;
|
|
19
|
+
#roomPolicy;
|
|
20
|
+
#propagator;
|
|
21
|
+
#maxPerUser;
|
|
22
|
+
#clock;
|
|
23
|
+
#connections = new Map();
|
|
24
|
+
#byUser = new Map();
|
|
25
|
+
#instanceId = (0, core_1.randomId)();
|
|
26
|
+
constructor(options) {
|
|
27
|
+
this.#transport = options.transport;
|
|
28
|
+
this.#authenticator = options.authenticator;
|
|
29
|
+
this.#roomPolicy = options.roomPolicy ?? exports.DENY_ALL_ROOMS;
|
|
30
|
+
this.#propagator = options.propagator;
|
|
31
|
+
this.#maxPerUser = options.maxConnectionsPerUser ?? DEFAULT_MAX_CONNECTIONS_PER_USER;
|
|
32
|
+
this.#clock = options.clock ?? { now: () => Date.now() };
|
|
33
|
+
// Events from other instances are delivered locally, but never re-published
|
|
34
|
+
// — that would be an infinite loop between two pods.
|
|
35
|
+
this.#propagator?.subscribe((event) => {
|
|
36
|
+
if (event.origin === this.#instanceId)
|
|
37
|
+
return;
|
|
38
|
+
this.#transport.emit(event.room, event.event, event.payload);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Authenticate a connection attempt.
|
|
43
|
+
*
|
|
44
|
+
* @throws AuthenticationError when there is no valid bearer token
|
|
45
|
+
*/
|
|
46
|
+
async connect(handshake) {
|
|
47
|
+
const token = (0, handshake_js_1.readHandshakeToken)(handshake);
|
|
48
|
+
const user = await this.#authenticator.authenticate(token);
|
|
49
|
+
const userId = String(user.id);
|
|
50
|
+
const existing = this.#byUser.get(userId) ?? new Set();
|
|
51
|
+
if (existing.size >= this.#maxPerUser) {
|
|
52
|
+
// A client in a reconnect loop otherwise accumulates sockets until the
|
|
53
|
+
// process runs out of file descriptors.
|
|
54
|
+
const oldest = existing.values().next();
|
|
55
|
+
if (!oldest.done)
|
|
56
|
+
this.disconnect(oldest.value, 'too many connections');
|
|
57
|
+
}
|
|
58
|
+
const connection = {
|
|
59
|
+
id: (0, core_1.randomId)(),
|
|
60
|
+
user,
|
|
61
|
+
rooms: new Set(),
|
|
62
|
+
connectedAt: this.#clock.now(),
|
|
63
|
+
};
|
|
64
|
+
const rooms = new Set();
|
|
65
|
+
this.#connections.set(connection.id, { connection: { ...connection, rooms }, rooms });
|
|
66
|
+
existing.add(connection.id);
|
|
67
|
+
this.#byUser.set(userId, existing);
|
|
68
|
+
return { ...connection, rooms };
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Admit a connection to a room.
|
|
72
|
+
*
|
|
73
|
+
* @throws AuthorizationError when the policy refuses
|
|
74
|
+
*/
|
|
75
|
+
async join(connectionId, room) {
|
|
76
|
+
const entry = this.#require(connectionId);
|
|
77
|
+
if (!(await this.#roomPolicy.canJoin(entry.connection.user, room))) {
|
|
78
|
+
// The client learns only that it was refused: which rooms exist is not
|
|
79
|
+
// something an unauthorised caller may enumerate.
|
|
80
|
+
throw new core_1.AuthorizationError('FORBIDDEN', {
|
|
81
|
+
message: 'You may not join that room.',
|
|
82
|
+
detail: `${String(entry.connection.user.id)} was refused room "${room}"`,
|
|
83
|
+
meta: { room },
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
entry.rooms.add(room);
|
|
87
|
+
}
|
|
88
|
+
leave(connectionId, room) {
|
|
89
|
+
this.#require(connectionId).rooms.delete(room);
|
|
90
|
+
}
|
|
91
|
+
disconnect(connectionId, reason = 'closed') {
|
|
92
|
+
const entry = this.#connections.get(connectionId);
|
|
93
|
+
if (entry === undefined)
|
|
94
|
+
return;
|
|
95
|
+
this.#connections.delete(connectionId);
|
|
96
|
+
const userId = String(entry.connection.user.id);
|
|
97
|
+
const held = this.#byUser.get(userId);
|
|
98
|
+
held?.delete(connectionId);
|
|
99
|
+
if (held?.size === 0)
|
|
100
|
+
this.#byUser.delete(userId);
|
|
101
|
+
this.#transport.disconnect(connectionId, reason);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Emit to a room, locally and on every other instance.
|
|
105
|
+
*
|
|
106
|
+
* The event is stamped with this instance's id so it comes back from the
|
|
107
|
+
* propagator recognisable and is not delivered twice.
|
|
108
|
+
*/
|
|
109
|
+
async emit(room, event, payload, requestId) {
|
|
110
|
+
this.#transport.emit(room, event, payload);
|
|
111
|
+
if (this.#propagator === undefined)
|
|
112
|
+
return;
|
|
113
|
+
const message = {
|
|
114
|
+
room,
|
|
115
|
+
event,
|
|
116
|
+
payload,
|
|
117
|
+
origin: this.#instanceId,
|
|
118
|
+
...(requestId === undefined ? {} : { requestId }),
|
|
119
|
+
};
|
|
120
|
+
await this.#propagator.publish(message);
|
|
121
|
+
}
|
|
122
|
+
/** Emit to every connection a principal holds on this instance. */
|
|
123
|
+
emitToUser(userId, event, payload) {
|
|
124
|
+
const held = this.#byUser.get(userId) ?? new Set();
|
|
125
|
+
for (const connectionId of held)
|
|
126
|
+
this.#transport.emitTo(connectionId, event, payload);
|
|
127
|
+
return held.size;
|
|
128
|
+
}
|
|
129
|
+
/** Connections in a room, on this instance. */
|
|
130
|
+
membersOf(room) {
|
|
131
|
+
return [...this.#connections.values()]
|
|
132
|
+
.filter((entry) => entry.rooms.has(room))
|
|
133
|
+
.map((entry) => entry.connection);
|
|
134
|
+
}
|
|
135
|
+
get connectionCount() {
|
|
136
|
+
return this.#connections.size;
|
|
137
|
+
}
|
|
138
|
+
connectionsFor(user) {
|
|
139
|
+
return [...(this.#byUser.get(String(user.id)) ?? [])];
|
|
140
|
+
}
|
|
141
|
+
async close() {
|
|
142
|
+
for (const id of [...this.#connections.keys()])
|
|
143
|
+
this.disconnect(id, 'shutting down');
|
|
144
|
+
await this.#propagator?.close();
|
|
145
|
+
}
|
|
146
|
+
#require(connectionId) {
|
|
147
|
+
const entry = this.#connections.get(connectionId);
|
|
148
|
+
if (entry === undefined) {
|
|
149
|
+
throw new core_1.AuthenticationError('AUTH_REQUIRED', {
|
|
150
|
+
detail: `Connection ${connectionId} is not registered`,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
return entry;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
exports.RealtimeGateway = RealtimeGateway;
|
|
157
|
+
//# sourceMappingURL=gateway.js.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading credentials off a connection attempt (PLAN.md §12).
|
|
3
|
+
*
|
|
4
|
+
* One rule: the token comes from the `Authorization` header and nowhere else.
|
|
5
|
+
*
|
|
6
|
+
* A token in a query string is not a lesser version of a token in a header —
|
|
7
|
+
* it is a token written into every access log, every proxy log, every
|
|
8
|
+
* `Referer` sent to a third-party asset, and the browser history. The legacy
|
|
9
|
+
* socket handshake accepted one, so this function refuses the connection
|
|
10
|
+
* outright when it sees one rather than quietly ignoring it: a client sending
|
|
11
|
+
* one has a token in its URLs and its author needs to know.
|
|
12
|
+
*/
|
|
13
|
+
import type { Handshake } from './ports.js';
|
|
14
|
+
/**
|
|
15
|
+
* Extract the bearer token.
|
|
16
|
+
*
|
|
17
|
+
* @throws AuthenticationError when a credential is in the query string, or when
|
|
18
|
+
* there is no usable header — there is no anonymous fallback.
|
|
19
|
+
*/
|
|
20
|
+
export declare function readHandshakeToken(handshake: Handshake): string;
|
|
21
|
+
//# sourceMappingURL=handshake.d.ts.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Reading credentials off a connection attempt (PLAN.md §12).
|
|
4
|
+
*
|
|
5
|
+
* One rule: the token comes from the `Authorization` header and nowhere else.
|
|
6
|
+
*
|
|
7
|
+
* A token in a query string is not a lesser version of a token in a header —
|
|
8
|
+
* it is a token written into every access log, every proxy log, every
|
|
9
|
+
* `Referer` sent to a third-party asset, and the browser history. The legacy
|
|
10
|
+
* socket handshake accepted one, so this function refuses the connection
|
|
11
|
+
* outright when it sees one rather than quietly ignoring it: a client sending
|
|
12
|
+
* one has a token in its URLs and its author needs to know.
|
|
13
|
+
*/
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.readHandshakeToken = readHandshakeToken;
|
|
16
|
+
const core_1 = require("@nage-api/core");
|
|
17
|
+
/** Query parameters that would carry a credential. */
|
|
18
|
+
const CREDENTIAL_PARAMETERS = [
|
|
19
|
+
'token',
|
|
20
|
+
'access_token',
|
|
21
|
+
'accesstoken',
|
|
22
|
+
'auth',
|
|
23
|
+
'authorization',
|
|
24
|
+
'jwt',
|
|
25
|
+
'apikey',
|
|
26
|
+
'api_key',
|
|
27
|
+
];
|
|
28
|
+
/**
|
|
29
|
+
* Extract the bearer token.
|
|
30
|
+
*
|
|
31
|
+
* @throws AuthenticationError when a credential is in the query string, or when
|
|
32
|
+
* there is no usable header — there is no anonymous fallback.
|
|
33
|
+
*/
|
|
34
|
+
function readHandshakeToken(handshake) {
|
|
35
|
+
const offending = Object.keys(handshake.query ?? {}).filter((key) => CREDENTIAL_PARAMETERS.includes(key.toLowerCase()));
|
|
36
|
+
if (offending.length > 0) {
|
|
37
|
+
throw new core_1.AuthenticationError('AUTH_TOKEN_INVALID', {
|
|
38
|
+
message: 'Send the token in the Authorization header, not the query string.',
|
|
39
|
+
detail: `Connection presented a credential in the query string (${offending.join(', ')}); it would be written to every access and proxy log`,
|
|
40
|
+
meta: { parameters: offending },
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
const header = handshake.authorization?.trim() ?? '';
|
|
44
|
+
const match = /^Bearer\s+(.+)$/i.exec(header);
|
|
45
|
+
if (match?.[1] === undefined) {
|
|
46
|
+
// No guest identity. The legacy gateway assigned one, which made every
|
|
47
|
+
// "authenticated" room reachable by anyone who opened a socket.
|
|
48
|
+
throw new core_1.AuthenticationError('AUTH_REQUIRED', {
|
|
49
|
+
detail: 'Connection had no Bearer token; anonymous sockets are not accepted',
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
return match[1];
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=handshake.js.map
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@nage-api/realtime` — authenticated sockets and a cross-instance propagator
|
|
3
|
+
* (PLAN.md §8, §12, §25 P2).
|
|
4
|
+
*
|
|
5
|
+
* The package's reason to exist is three named defects in the legacy socket
|
|
6
|
+
* layer: a token accepted from the query string, a default guest identity, and
|
|
7
|
+
* rooms joined without authorization. All three are refused here.
|
|
8
|
+
*/
|
|
9
|
+
export type * from '@nage-api/contracts';
|
|
10
|
+
export { NageRealtimeModule, type NageRealtimeModuleOptions } from './realtime.module.js';
|
|
11
|
+
export { RealtimeGateway, DENY_ALL_ROOMS, type RealtimeGatewayOptions } from './gateway.js';
|
|
12
|
+
export { readHandshakeToken } from './handshake.js';
|
|
13
|
+
export { MemoryPropagator, MemoryTransport, type EmittedEvent } from './memory.js';
|
|
14
|
+
export { NAGE_REALTIME, NAGE_REALTIME_PROPAGATOR, NAGE_REALTIME_TRANSPORT } from './tokens.js';
|
|
15
|
+
export { systemClock, type Clock, type Connection, type Handshake, type Propagator, type RealtimeEvent, type RealtimeTransport, type RoomPolicy, type SocketAuthenticator, } from './ports.js';
|
|
16
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `@nage-api/realtime` — authenticated sockets and a cross-instance propagator
|
|
4
|
+
* (PLAN.md §8, §12, §25 P2).
|
|
5
|
+
*
|
|
6
|
+
* The package's reason to exist is three named defects in the legacy socket
|
|
7
|
+
* layer: a token accepted from the query string, a default guest identity, and
|
|
8
|
+
* rooms joined without authorization. All three are refused here.
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.systemClock = exports.NAGE_REALTIME_TRANSPORT = exports.NAGE_REALTIME_PROPAGATOR = exports.NAGE_REALTIME = exports.MemoryTransport = exports.MemoryPropagator = exports.readHandshakeToken = exports.DENY_ALL_ROOMS = exports.RealtimeGateway = exports.NageRealtimeModule = void 0;
|
|
12
|
+
var realtime_module_js_1 = require("./realtime.module.js");
|
|
13
|
+
Object.defineProperty(exports, "NageRealtimeModule", { enumerable: true, get: function () { return realtime_module_js_1.NageRealtimeModule; } });
|
|
14
|
+
var gateway_js_1 = require("./gateway.js");
|
|
15
|
+
Object.defineProperty(exports, "RealtimeGateway", { enumerable: true, get: function () { return gateway_js_1.RealtimeGateway; } });
|
|
16
|
+
Object.defineProperty(exports, "DENY_ALL_ROOMS", { enumerable: true, get: function () { return gateway_js_1.DENY_ALL_ROOMS; } });
|
|
17
|
+
var handshake_js_1 = require("./handshake.js");
|
|
18
|
+
Object.defineProperty(exports, "readHandshakeToken", { enumerable: true, get: function () { return handshake_js_1.readHandshakeToken; } });
|
|
19
|
+
var memory_js_1 = require("./memory.js");
|
|
20
|
+
Object.defineProperty(exports, "MemoryPropagator", { enumerable: true, get: function () { return memory_js_1.MemoryPropagator; } });
|
|
21
|
+
Object.defineProperty(exports, "MemoryTransport", { enumerable: true, get: function () { return memory_js_1.MemoryTransport; } });
|
|
22
|
+
var tokens_js_1 = require("./tokens.js");
|
|
23
|
+
Object.defineProperty(exports, "NAGE_REALTIME", { enumerable: true, get: function () { return tokens_js_1.NAGE_REALTIME; } });
|
|
24
|
+
Object.defineProperty(exports, "NAGE_REALTIME_PROPAGATOR", { enumerable: true, get: function () { return tokens_js_1.NAGE_REALTIME_PROPAGATOR; } });
|
|
25
|
+
Object.defineProperty(exports, "NAGE_REALTIME_TRANSPORT", { enumerable: true, get: function () { return tokens_js_1.NAGE_REALTIME_TRANSPORT; } });
|
|
26
|
+
var ports_js_1 = require("./ports.js");
|
|
27
|
+
Object.defineProperty(exports, "systemClock", { enumerable: true, get: function () { return ports_js_1.systemClock; } });
|
|
28
|
+
//# sourceMappingURL=index.js.map
|
package/dist/memory.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory transport and propagator.
|
|
3
|
+
*
|
|
4
|
+
* The propagator is genuinely useful beyond tests: two gateways sharing one
|
|
5
|
+
* `MemoryPropagator` behave exactly like two pods sharing a Redis channel, so
|
|
6
|
+
* cross-instance delivery can be asserted without a broker.
|
|
7
|
+
*/
|
|
8
|
+
import type { Propagator, RealtimeEvent, RealtimeTransport } from './ports.js';
|
|
9
|
+
export interface EmittedEvent {
|
|
10
|
+
readonly target: string;
|
|
11
|
+
readonly event: string;
|
|
12
|
+
readonly payload: unknown;
|
|
13
|
+
}
|
|
14
|
+
export declare class MemoryTransport implements RealtimeTransport {
|
|
15
|
+
readonly name = "memory";
|
|
16
|
+
readonly emitted: EmittedEvent[];
|
|
17
|
+
readonly disconnected: {
|
|
18
|
+
id: string;
|
|
19
|
+
reason: string;
|
|
20
|
+
}[];
|
|
21
|
+
emit(room: string, event: string, payload: unknown): void;
|
|
22
|
+
emitTo(connectionId: string, event: string, payload: unknown): void;
|
|
23
|
+
disconnect(connectionId: string, reason: string): void;
|
|
24
|
+
/** Events sent to one room or connection. */
|
|
25
|
+
to(target: string): readonly EmittedEvent[];
|
|
26
|
+
}
|
|
27
|
+
/** A propagator every subscriber on the same instance shares. */
|
|
28
|
+
export declare class MemoryPropagator implements Propagator {
|
|
29
|
+
#private;
|
|
30
|
+
readonly published: RealtimeEvent[];
|
|
31
|
+
publish(event: RealtimeEvent): Promise<void>;
|
|
32
|
+
subscribe(handler: (event: RealtimeEvent) => void): void;
|
|
33
|
+
close(): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=memory.d.ts.map
|
package/dist/memory.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* In-memory transport and propagator.
|
|
4
|
+
*
|
|
5
|
+
* The propagator is genuinely useful beyond tests: two gateways sharing one
|
|
6
|
+
* `MemoryPropagator` behave exactly like two pods sharing a Redis channel, so
|
|
7
|
+
* cross-instance delivery can be asserted without a broker.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.MemoryPropagator = exports.MemoryTransport = void 0;
|
|
11
|
+
class MemoryTransport {
|
|
12
|
+
name = 'memory';
|
|
13
|
+
emitted = [];
|
|
14
|
+
disconnected = [];
|
|
15
|
+
emit(room, event, payload) {
|
|
16
|
+
this.emitted.push({ target: room, event, payload });
|
|
17
|
+
}
|
|
18
|
+
emitTo(connectionId, event, payload) {
|
|
19
|
+
this.emitted.push({ target: connectionId, event, payload });
|
|
20
|
+
}
|
|
21
|
+
disconnect(connectionId, reason) {
|
|
22
|
+
this.disconnected.push({ id: connectionId, reason });
|
|
23
|
+
}
|
|
24
|
+
/** Events sent to one room or connection. */
|
|
25
|
+
to(target) {
|
|
26
|
+
return this.emitted.filter((entry) => entry.target === target);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
exports.MemoryTransport = MemoryTransport;
|
|
30
|
+
/** A propagator every subscriber on the same instance shares. */
|
|
31
|
+
class MemoryPropagator {
|
|
32
|
+
published = [];
|
|
33
|
+
#handlers = [];
|
|
34
|
+
async publish(event) {
|
|
35
|
+
await Promise.resolve();
|
|
36
|
+
this.published.push(event);
|
|
37
|
+
for (const handler of this.#handlers)
|
|
38
|
+
handler(event);
|
|
39
|
+
}
|
|
40
|
+
subscribe(handler) {
|
|
41
|
+
this.#handlers.push(handler);
|
|
42
|
+
}
|
|
43
|
+
async close() {
|
|
44
|
+
await Promise.resolve();
|
|
45
|
+
this.#handlers.length = 0;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
exports.MemoryPropagator = MemoryPropagator;
|
|
49
|
+
//# sourceMappingURL=memory.js.map
|
package/dist/ports.d.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Realtime (PLAN.md §8, §12, §25 P2).
|
|
3
|
+
*
|
|
4
|
+
* §12 names three specific defects in the legacy socket layer, and this package
|
|
5
|
+
* exists to make them unrepresentable:
|
|
6
|
+
*
|
|
7
|
+
* 1. **no query-string token** — a token in a URL is written to every access
|
|
8
|
+
* log, proxy log and `Referer` header between the client and the server;
|
|
9
|
+
* 2. **no default guest** — an unauthenticated connection was silently given
|
|
10
|
+
* an identity, so every "authenticated" room was reachable by anyone;
|
|
11
|
+
* 3. **rooms are authorised** — joining a room named by the client is an
|
|
12
|
+
* authorization decision, not a subscription.
|
|
13
|
+
*
|
|
14
|
+
* The transport is a port. Socket.IO is the intended binding (§27.5), but the
|
|
15
|
+
* decisions above are transport-independent, and testing them against a real
|
|
16
|
+
* socket server would be testing Socket.IO.
|
|
17
|
+
*/
|
|
18
|
+
import type { AuthUser } from '@nage-api/contracts';
|
|
19
|
+
/** A connected client, after authentication. */
|
|
20
|
+
export interface Connection {
|
|
21
|
+
readonly id: string;
|
|
22
|
+
readonly user: AuthUser;
|
|
23
|
+
/** Rooms this connection has been admitted to. */
|
|
24
|
+
readonly rooms: ReadonlySet<string>;
|
|
25
|
+
readonly connectedAt: number;
|
|
26
|
+
}
|
|
27
|
+
/** Credentials as they arrive on a connection attempt. */
|
|
28
|
+
export interface Handshake {
|
|
29
|
+
/** `Authorization: Bearer …`, the only place a token is read from. */
|
|
30
|
+
readonly authorization?: string;
|
|
31
|
+
/** Parsed query parameters, inspected **only** to refuse tokens in them. */
|
|
32
|
+
readonly query?: Readonly<Record<string, string>>;
|
|
33
|
+
readonly ip?: string;
|
|
34
|
+
readonly userAgent?: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Verifies a bearer token and resolves the principal.
|
|
38
|
+
*
|
|
39
|
+
* Implemented by the application over `@nage-api/auth`; this package may not import
|
|
40
|
+
* a sibling feature package (§7.2).
|
|
41
|
+
*/
|
|
42
|
+
export interface SocketAuthenticator {
|
|
43
|
+
authenticate(token: string): Promise<AuthUser>;
|
|
44
|
+
}
|
|
45
|
+
/** Decides whether a principal may join a room. */
|
|
46
|
+
export interface RoomPolicy {
|
|
47
|
+
/** Return false to refuse; the client is told nothing beyond "refused". */
|
|
48
|
+
canJoin(user: AuthUser, room: string): boolean | Promise<boolean>;
|
|
49
|
+
}
|
|
50
|
+
/** An event on its way to clients. */
|
|
51
|
+
export interface RealtimeEvent<TPayload = unknown> {
|
|
52
|
+
readonly room: string;
|
|
53
|
+
readonly event: string;
|
|
54
|
+
readonly payload: TPayload;
|
|
55
|
+
/** Correlation id of the request that produced it. */
|
|
56
|
+
readonly requestId?: string;
|
|
57
|
+
/** Set when the emitting instance should not re-deliver it locally. */
|
|
58
|
+
readonly origin?: string;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Carries events between instances (§8: "Socket.IO + Redis propagator").
|
|
62
|
+
*
|
|
63
|
+
* Without one, a two-pod deployment delivers each event to whichever half of
|
|
64
|
+
* the users happen to be connected to the pod that emitted it.
|
|
65
|
+
*/
|
|
66
|
+
export interface Propagator {
|
|
67
|
+
publish(event: RealtimeEvent): Promise<void>;
|
|
68
|
+
subscribe(handler: (event: RealtimeEvent) => void): void;
|
|
69
|
+
close(): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
/** The transport a gateway drives. */
|
|
72
|
+
export interface RealtimeTransport {
|
|
73
|
+
readonly name: string;
|
|
74
|
+
/** Deliver to every local connection in a room. */
|
|
75
|
+
emit(room: string, event: string, payload: unknown): void;
|
|
76
|
+
/** Deliver to one local connection. */
|
|
77
|
+
emitTo(connectionId: string, event: string, payload: unknown): void;
|
|
78
|
+
disconnect(connectionId: string, reason: string): void;
|
|
79
|
+
}
|
|
80
|
+
export interface Clock {
|
|
81
|
+
now(): number;
|
|
82
|
+
}
|
|
83
|
+
export declare const systemClock: Clock;
|
|
84
|
+
//# sourceMappingURL=ports.d.ts.map
|
package/dist/ports.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Realtime (PLAN.md §8, §12, §25 P2).
|
|
4
|
+
*
|
|
5
|
+
* §12 names three specific defects in the legacy socket layer, and this package
|
|
6
|
+
* exists to make them unrepresentable:
|
|
7
|
+
*
|
|
8
|
+
* 1. **no query-string token** — a token in a URL is written to every access
|
|
9
|
+
* log, proxy log and `Referer` header between the client and the server;
|
|
10
|
+
* 2. **no default guest** — an unauthenticated connection was silently given
|
|
11
|
+
* an identity, so every "authenticated" room was reachable by anyone;
|
|
12
|
+
* 3. **rooms are authorised** — joining a room named by the client is an
|
|
13
|
+
* authorization decision, not a subscription.
|
|
14
|
+
*
|
|
15
|
+
* The transport is a port. Socket.IO is the intended binding (§27.5), but the
|
|
16
|
+
* decisions above are transport-independent, and testing them against a real
|
|
17
|
+
* socket server would be testing Socket.IO.
|
|
18
|
+
*/
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.systemClock = void 0;
|
|
21
|
+
exports.systemClock = { now: () => Date.now() };
|
|
22
|
+
//# sourceMappingURL=ports.js.map
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `NageRealtimeModule.forRoot(config)` (PLAN.md §11.1 item 6, §12).
|
|
3
|
+
*
|
|
4
|
+
* An authenticator is **required**. There is no default, because the only
|
|
5
|
+
* possible default would be "accept anyone", and that is the legacy defect
|
|
6
|
+
* this package exists to remove.
|
|
7
|
+
*
|
|
8
|
+
* A multi-instance deployment without a propagator is refused for the same
|
|
9
|
+
* reason: it appears to work, and delivers each event to whichever fraction of
|
|
10
|
+
* users happens to be connected to the pod that emitted it.
|
|
11
|
+
*/
|
|
12
|
+
import { type DynamicModule, type OnApplicationShutdown } from '@nestjs/common';
|
|
13
|
+
import type { RealtimeConfig } from '@nage-api/contracts';
|
|
14
|
+
import type { Clock, Propagator, RealtimeTransport, RoomPolicy, SocketAuthenticator } from './ports.js';
|
|
15
|
+
export interface NageRealtimeModuleOptions {
|
|
16
|
+
readonly realtime?: RealtimeConfig;
|
|
17
|
+
readonly environment?: string;
|
|
18
|
+
/** Required: verifies a bearer token and resolves the principal. */
|
|
19
|
+
readonly authenticator?: SocketAuthenticator;
|
|
20
|
+
/** Refuses every room unless supplied. */
|
|
21
|
+
readonly roomPolicy?: RoomPolicy;
|
|
22
|
+
/** Socket.IO or another binding; in-memory when omitted. */
|
|
23
|
+
readonly transport?: RealtimeTransport;
|
|
24
|
+
readonly propagator?: Propagator;
|
|
25
|
+
readonly clock?: Clock;
|
|
26
|
+
}
|
|
27
|
+
export declare class NageRealtimeModule implements OnApplicationShutdown {
|
|
28
|
+
static forRoot(options?: NageRealtimeModuleOptions): DynamicModule;
|
|
29
|
+
onApplicationShutdown(): Promise<void>;
|
|
30
|
+
private static buildPropagator;
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=realtime.module.d.ts.map
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `NageRealtimeModule.forRoot(config)` (PLAN.md §11.1 item 6, §12).
|
|
4
|
+
*
|
|
5
|
+
* An authenticator is **required**. There is no default, because the only
|
|
6
|
+
* possible default would be "accept anyone", and that is the legacy defect
|
|
7
|
+
* this package exists to remove.
|
|
8
|
+
*
|
|
9
|
+
* A multi-instance deployment without a propagator is refused for the same
|
|
10
|
+
* reason: it appears to work, and delivers each event to whichever fraction of
|
|
11
|
+
* users happens to be connected to the pod that emitted it.
|
|
12
|
+
*/
|
|
13
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
14
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
15
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
16
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
17
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
18
|
+
};
|
|
19
|
+
var NageRealtimeModule_1;
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
21
|
+
exports.NageRealtimeModule = void 0;
|
|
22
|
+
const common_1 = require("@nestjs/common");
|
|
23
|
+
const core_1 = require("@nage-api/core");
|
|
24
|
+
const gateway_js_1 = require("./gateway.js");
|
|
25
|
+
const memory_js_1 = require("./memory.js");
|
|
26
|
+
const tokens_js_1 = require("./tokens.js");
|
|
27
|
+
const gateways = [];
|
|
28
|
+
let NageRealtimeModule = NageRealtimeModule_1 = class NageRealtimeModule {
|
|
29
|
+
static forRoot(options = {}) {
|
|
30
|
+
const config = options.realtime ?? {};
|
|
31
|
+
if (config.enabled !== true) {
|
|
32
|
+
return { module: NageRealtimeModule_1, providers: [], exports: [] };
|
|
33
|
+
}
|
|
34
|
+
if (options.authenticator === undefined) {
|
|
35
|
+
throw new core_1.ConfigurationError({
|
|
36
|
+
detail: 'NageRealtimeModule needs an authenticator; there is no anonymous fallback, because a default guest identity makes every authenticated room public',
|
|
37
|
+
meta: { setting: 'realtime.authenticator' },
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
const transport = options.transport ?? new memory_js_1.MemoryTransport();
|
|
41
|
+
const propagator = options.propagator ?? NageRealtimeModule_1.buildPropagator(config, options);
|
|
42
|
+
const gateway = new gateway_js_1.RealtimeGateway({
|
|
43
|
+
transport,
|
|
44
|
+
authenticator: options.authenticator,
|
|
45
|
+
...(options.roomPolicy === undefined ? {} : { roomPolicy: options.roomPolicy }),
|
|
46
|
+
...(propagator === undefined ? {} : { propagator }),
|
|
47
|
+
...(options.clock === undefined ? {} : { clock: options.clock }),
|
|
48
|
+
});
|
|
49
|
+
gateways.push(gateway);
|
|
50
|
+
const providers = [
|
|
51
|
+
{ provide: tokens_js_1.NAGE_REALTIME_TRANSPORT, useValue: transport },
|
|
52
|
+
{ provide: tokens_js_1.NAGE_REALTIME, useValue: gateway },
|
|
53
|
+
{ provide: gateway_js_1.RealtimeGateway, useValue: gateway },
|
|
54
|
+
...(propagator === undefined
|
|
55
|
+
? []
|
|
56
|
+
: [{ provide: tokens_js_1.NAGE_REALTIME_PROPAGATOR, useValue: propagator }]),
|
|
57
|
+
];
|
|
58
|
+
return {
|
|
59
|
+
module: NageRealtimeModule_1,
|
|
60
|
+
providers,
|
|
61
|
+
exports: [
|
|
62
|
+
tokens_js_1.NAGE_REALTIME,
|
|
63
|
+
tokens_js_1.NAGE_REALTIME_TRANSPORT,
|
|
64
|
+
gateway_js_1.RealtimeGateway,
|
|
65
|
+
...(propagator === undefined ? [] : [tokens_js_1.NAGE_REALTIME_PROPAGATOR]),
|
|
66
|
+
],
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
async onApplicationShutdown() {
|
|
70
|
+
for (const gateway of gateways.splice(0))
|
|
71
|
+
await gateway.close();
|
|
72
|
+
}
|
|
73
|
+
static buildPropagator(config, options) {
|
|
74
|
+
if (config.adapter !== 'redis')
|
|
75
|
+
return new memory_js_1.MemoryPropagator();
|
|
76
|
+
// The in-memory propagator carries nothing between processes, so a
|
|
77
|
+
// deployment asking for `redis` and getting it would be a silent lie.
|
|
78
|
+
throw new core_1.ConfigurationError({
|
|
79
|
+
detail: 'realtime.adapter "redis" needs a propagator; pass one to NageRealtimeModule.forRoot({ propagator })',
|
|
80
|
+
meta: { setting: 'realtime.adapter', environment: options.environment },
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
exports.NageRealtimeModule = NageRealtimeModule;
|
|
85
|
+
exports.NageRealtimeModule = NageRealtimeModule = NageRealtimeModule_1 = __decorate([
|
|
86
|
+
(0, common_1.Module)({})
|
|
87
|
+
], NageRealtimeModule);
|
|
88
|
+
//# sourceMappingURL=realtime.module.js.map
|
package/dist/tokens.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** DI tokens for realtime (PLAN.md §7.3). */
|
|
2
|
+
import { type Token } from '@nage-api/core';
|
|
3
|
+
import type { RealtimeGateway } from './gateway.js';
|
|
4
|
+
import type { Propagator, RealtimeTransport } from './ports.js';
|
|
5
|
+
export declare const NAGE_REALTIME: Token<RealtimeGateway>;
|
|
6
|
+
export declare const NAGE_REALTIME_TRANSPORT: Token<RealtimeTransport>;
|
|
7
|
+
export declare const NAGE_REALTIME_PROPAGATOR: Token<Propagator>;
|
|
8
|
+
//# sourceMappingURL=tokens.d.ts.map
|
package/dist/tokens.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** DI tokens for realtime (PLAN.md §7.3). */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.NAGE_REALTIME_PROPAGATOR = exports.NAGE_REALTIME_TRANSPORT = exports.NAGE_REALTIME = void 0;
|
|
5
|
+
const core_1 = require("@nage-api/core");
|
|
6
|
+
exports.NAGE_REALTIME = (0, core_1.createToken)('NAGE_REALTIME');
|
|
7
|
+
exports.NAGE_REALTIME_TRANSPORT = (0, core_1.createToken)('NAGE_REALTIME_TRANSPORT');
|
|
8
|
+
exports.NAGE_REALTIME_PROPAGATOR = (0, core_1.createToken)('NAGE_REALTIME_PROPAGATOR');
|
|
9
|
+
//# sourceMappingURL=tokens.js.map
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@nage-api/realtime",
|
|
3
|
+
"version": "1.0.0-beta.2",
|
|
4
|
+
"description": "Realtime for @nage-api — authenticated sockets and a cross-instance propagator",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "commonjs",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"!dist/.tsbuildinfo",
|
|
20
|
+
"!dist/**/*.map",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@nage-api/contracts": "1.0.0-beta.2",
|
|
28
|
+
"@nage-api/core": "1.0.0-beta.2"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@nestjs/common": "^11.0.0",
|
|
32
|
+
"@nestjs/core": "^11.0.0",
|
|
33
|
+
"reflect-metadata": "^0.2.0"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@nestjs/common": "11.1.29",
|
|
37
|
+
"@nestjs/core": "11.1.29",
|
|
38
|
+
"@nestjs/testing": "11.1.29",
|
|
39
|
+
"@swc/core": "1.15.47",
|
|
40
|
+
"@types/node": "22.20.1",
|
|
41
|
+
"@vitest/coverage-v8": "4.1.10",
|
|
42
|
+
"reflect-metadata": "0.2.2",
|
|
43
|
+
"rimraf": "6.1.3",
|
|
44
|
+
"rxjs": "7.8.2",
|
|
45
|
+
"typescript": "5.9.3",
|
|
46
|
+
"unplugin-swc": "1.5.11",
|
|
47
|
+
"vitest": "4.1.10",
|
|
48
|
+
"@nage-api/testing": "1.0.0-beta.2"
|
|
49
|
+
},
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=22.0.0"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"build": "tsc -b tsconfig.build.json",
|
|
55
|
+
"clean": "rimraf dist .turbo",
|
|
56
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
57
|
+
"test": "vitest run"
|
|
58
|
+
}
|
|
59
|
+
}
|