@vgai/p2p-colyseus 0.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.
- package/LICENSE +202 -0
- package/README.md +125 -0
- package/package.json +51 -0
- package/src/access-token.ts +74 -0
- package/src/browser.ts +202 -0
- package/src/callbacks.ts +7 -0
- package/src/channels.ts +12 -0
- package/src/client.ts +480 -0
- package/src/cloudflare/coordinator.ts +383 -0
- package/src/cloudflare/durable-room.ts +377 -0
- package/src/cloudflare/limits.ts +22 -0
- package/src/cloudflare/protocol.ts +75 -0
- package/src/cloudflare/worker.ts +110 -0
- package/src/codec.ts +78 -0
- package/src/diagnostics.ts +55 -0
- package/src/engine.ts +680 -0
- package/src/events.ts +58 -0
- package/src/index.ts +196 -0
- package/src/loopback.ts +65 -0
- package/src/node-websocket.ts +77 -0
- package/src/platform.ts +866 -0
- package/src/protocol.ts +56 -0
- package/src/relay.ts +60 -0
- package/src/replication.ts +164 -0
- package/src/room.ts +282 -0
- package/src/runtime.ts +371 -0
- package/src/schema.ts +287 -0
- package/src/webrtc.ts +78 -0
- package/src/websocket.ts +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 2026 Volter AI, Inc.
|
|
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,125 @@
|
|
|
1
|
+
# @vgai/p2p-colyseus
|
|
2
|
+
|
|
3
|
+
Colyseus-compatible runtime pieces for running the same multiplayer room/client source in real Colyseus, loopback tests, universal Node WebSocket mode, browser-hosted P2P over WebRTC, and Cloudflare relay fallback.
|
|
4
|
+
|
|
5
|
+
The core contract is strict: gameplay code should be authored like normal Colyseus code. Runtime selection belongs in config, build aliases, launch URLs, or test harnesses.
|
|
6
|
+
|
|
7
|
+
## Authoring Contract
|
|
8
|
+
|
|
9
|
+
Game code may use ordinary Colyseus-style imports:
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { Client, Callbacks } from '@colyseus/sdk';
|
|
13
|
+
import { Schema, MapSchema, type } from '@colyseus/schema';
|
|
14
|
+
import { Room } from 'colyseus';
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Game code should not import WebRTC, Cloudflare signaling, relay fallback, `@vgai/p2p-colyseus`, or engine transport selection APIs. If the source has to branch for real Colyseus vs P2P, the compatibility package or launch layer is incomplete.
|
|
18
|
+
|
|
19
|
+
## Runtime Modes
|
|
20
|
+
|
|
21
|
+
- Real Colyseus: normal Colyseus packages and a real Colyseus server.
|
|
22
|
+
- Loopback: `loopback://` client plus registered room classes for tests.
|
|
23
|
+
- Universal Node WebSocket: no Colyseus server dependency, but WebSocket transport.
|
|
24
|
+
- P2P host: browser creates the authoritative room and accepts clients.
|
|
25
|
+
- P2P join: browser joins a host-created room by `roomId`.
|
|
26
|
+
- Relay fallback: Cloudflare signaling/relay carries packets when direct WebRTC is unavailable or forced.
|
|
27
|
+
|
|
28
|
+
## Browser Client Configuration
|
|
29
|
+
|
|
30
|
+
Configure P2P outside gameplay code:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { configureP2PColyseusClient } from '@vgai/p2p-colyseus/browser';
|
|
34
|
+
import { TankRoom } from './server/rooms/tank-room';
|
|
35
|
+
|
|
36
|
+
configureP2PColyseusClient({
|
|
37
|
+
mode: {
|
|
38
|
+
kind: 'p2p-host',
|
|
39
|
+
signalingUrl: 'https://vgai-p2p-colyseus.example.workers.dev',
|
|
40
|
+
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
|
|
41
|
+
},
|
|
42
|
+
rooms: {
|
|
43
|
+
tank_room: TankRoom,
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Joining an existing host:
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
configureP2PColyseusClient({
|
|
52
|
+
mode: {
|
|
53
|
+
kind: 'p2p-join',
|
|
54
|
+
signalingUrl: 'https://vgai-p2p-colyseus.example.workers.dev',
|
|
55
|
+
roomId,
|
|
56
|
+
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
For proofing relay mode:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
configureP2PColyseusClient({
|
|
65
|
+
mode: {
|
|
66
|
+
kind: 'p2p-join',
|
|
67
|
+
signalingUrl,
|
|
68
|
+
roomId,
|
|
69
|
+
iceServers: [],
|
|
70
|
+
forceRelay: true,
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Cloudflare Worker
|
|
76
|
+
|
|
77
|
+
The Worker entrypoint is exported at:
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
@vgai/p2p-colyseus/cloudflare/worker
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Local commands:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
npm --workspace @vgai/p2p-colyseus run typecheck
|
|
87
|
+
npm --workspace @vgai/p2p-colyseus run test
|
|
88
|
+
npm --workspace @vgai/p2p-colyseus run wrangler:dry-run
|
|
89
|
+
npm --workspace @vgai/p2p-colyseus run wrangler:dev
|
|
90
|
+
npm --workspace @vgai/p2p-colyseus run wrangler:deploy
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Deployment config lives in `wrangler.toml`.
|
|
94
|
+
|
|
95
|
+
## Cloudflare Env Vars
|
|
96
|
+
|
|
97
|
+
- `P2P_COLYSEUS_RELAY_DISABLED`: set to `true` to reject relay service traffic.
|
|
98
|
+
- `P2P_COLYSEUS_RELAY_DAILY_BUDGET_USD`: budget input used to derive the global relay byte cap.
|
|
99
|
+
- `P2P_COLYSEUS_RELAY_ESTIMATED_USD_PER_GIB`: egress estimate used with the budget.
|
|
100
|
+
- `P2P_COLYSEUS_RELAY_MAX_GLOBAL_BYTES_PER_DAY`: explicit byte cap override.
|
|
101
|
+
- `P2P_COLYSEUS_MAX_REQUEST_BODY_BYTES`: maximum HTTP POST body size.
|
|
102
|
+
- `P2P_COLYSEUS_MAX_GLOBAL_REQUESTS_PER_DAY`: global daily Worker request cap.
|
|
103
|
+
- `P2P_COLYSEUS_MAX_GLOBAL_WEBSOCKET_MESSAGES_PER_DAY`: global daily WebSocket relay message cap.
|
|
104
|
+
- `P2P_COLYSEUS_MAX_ACTIVE_RELAY_SOCKETS`: active relay WebSocket cap.
|
|
105
|
+
- `P2P_COLYSEUS_ALLOWED_ORIGINS`: optional comma-separated CORS/origin allowlist. Unset means all origins are allowed.
|
|
106
|
+
|
|
107
|
+
## Proof Command
|
|
108
|
+
|
|
109
|
+
From the repo root:
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
npm run typecheck && npm run test:p2p-colyseus-proof
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
The proof deploys the Worker, runs package tests, executes live relay checks, records browser gameplay videos, summarizes artifacts, and validates all required proof rows. Artifact details are documented in `docs/P2P-COLYSEUS-PROOF-ARTIFACTS.md`.
|
|
116
|
+
|
|
117
|
+
## Known Scope Boundaries
|
|
118
|
+
|
|
119
|
+
- The workspace package is ESM-only (`"type": "module"`). CJS package output is not currently produced.
|
|
120
|
+
- This is not a full Colyseus Cloud replacement.
|
|
121
|
+
- Redis-backed presence/driver behavior is represented by local compatibility shims unless a proof explicitly covers distributed behavior.
|
|
122
|
+
- Host migration is not implemented.
|
|
123
|
+
- Direct WebRTC is proven in Chromium proof contexts; wider browser/NAT coverage is tracked in `docs/P2P-COLYSEUS-REMAINING-CHECKLIST.md`.
|
|
124
|
+
|
|
125
|
+
Current product/security decisions are tracked in `docs/P2P-COLYSEUS-DECISIONS.md`.
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vgai/p2p-colyseus",
|
|
3
|
+
"author": "Volter AI, Inc.",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"version": "0.1.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"description": "Colyseus-compatible transport for vgai — real Colyseus, loopback, WebRTC, or relay, chosen at runtime.",
|
|
8
|
+
"homepage": "https://github.com/volter-ai/vgai-engine#readme",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/volter-ai/vgai-engine.git",
|
|
12
|
+
"directory": "packages/p2p-colyseus"
|
|
13
|
+
},
|
|
14
|
+
"publishConfig": {
|
|
15
|
+
"access": "public"
|
|
16
|
+
},
|
|
17
|
+
"files": ["src"],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/index.ts",
|
|
20
|
+
"./engine": "./src/engine.ts",
|
|
21
|
+
"./schema": "./src/schema.ts",
|
|
22
|
+
"./codec": "./src/codec.ts",
|
|
23
|
+
"./client": "./src/client.ts",
|
|
24
|
+
"./browser": "./src/browser.ts",
|
|
25
|
+
"./server": "./src/room.ts",
|
|
26
|
+
"./platform": "./src/platform.ts",
|
|
27
|
+
"./cloudflare/worker": "./src/cloudflare/worker.ts"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "cd ../.. && npx tsx scripts/check-p2p-package-build.ts",
|
|
31
|
+
"typecheck": "tsc --noEmit",
|
|
32
|
+
"test": "vitest run test/**/*.test.ts",
|
|
33
|
+
"wrangler:dry-run": "wrangler deploy --dry-run --config wrangler.toml",
|
|
34
|
+
"wrangler:dev": "wrangler dev --config wrangler.toml",
|
|
35
|
+
"wrangler:deploy": "wrangler deploy --config wrangler.toml"
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"ws": "^8.19.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@colyseus/sdk": "^0.17.34",
|
|
42
|
+
"@colyseus/schema": "^4.0.14",
|
|
43
|
+
"@colyseus/ws-transport": "^0.17.9",
|
|
44
|
+
"@types/node": "^25.3.0",
|
|
45
|
+
"@types/ws": "^8.5.13",
|
|
46
|
+
"colyseus": "^0.17.8",
|
|
47
|
+
"typescript": "^5.6.0",
|
|
48
|
+
"vitest": "^3.2.6",
|
|
49
|
+
"wrangler": "^4.106.0"
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
export interface P2PAccessTokenClaims {
|
|
2
|
+
readonly roomName: string;
|
|
3
|
+
readonly peerId?: string | undefined;
|
|
4
|
+
readonly expiresAt: number;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export async function createP2PAccessToken(
|
|
8
|
+
secret: string,
|
|
9
|
+
claims: P2PAccessTokenClaims,
|
|
10
|
+
): Promise<string> {
|
|
11
|
+
const payload = encodeBase64Url(JSON.stringify(claims));
|
|
12
|
+
const signature = await sign(secret, payload);
|
|
13
|
+
return `${payload}.${signature}`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function verifyP2PAccessToken(
|
|
17
|
+
secret: string,
|
|
18
|
+
token: string,
|
|
19
|
+
expected: { roomName: string; peerId?: string | undefined },
|
|
20
|
+
now = Date.now(),
|
|
21
|
+
): Promise<boolean> {
|
|
22
|
+
const [payload, signature, extra] = token.split('.');
|
|
23
|
+
if (!payload || !signature || extra !== undefined) return false;
|
|
24
|
+
const expectedSignature = await sign(secret, payload);
|
|
25
|
+
if (!constantTimeEqual(signature, expectedSignature)) return false;
|
|
26
|
+
|
|
27
|
+
let claims: P2PAccessTokenClaims;
|
|
28
|
+
try {
|
|
29
|
+
claims = JSON.parse(decodeBase64Url(payload)) as P2PAccessTokenClaims;
|
|
30
|
+
} catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (claims.roomName !== expected.roomName) return false;
|
|
35
|
+
if (expected.peerId && claims.peerId && claims.peerId !== expected.peerId) return false;
|
|
36
|
+
return Number.isFinite(claims.expiresAt) && claims.expiresAt > now;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function sign(secret: string, payload: string): Promise<string> {
|
|
40
|
+
const key = await crypto.subtle.importKey(
|
|
41
|
+
'raw',
|
|
42
|
+
new TextEncoder().encode(secret),
|
|
43
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
44
|
+
false,
|
|
45
|
+
['sign'],
|
|
46
|
+
);
|
|
47
|
+
const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(payload));
|
|
48
|
+
return encodeBase64Url(new Uint8Array(signature));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function encodeBase64Url(value: string | Uint8Array): string {
|
|
52
|
+
const bytes = typeof value === 'string' ? new TextEncoder().encode(value) : value;
|
|
53
|
+
let binary = '';
|
|
54
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
55
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function decodeBase64Url(value: string): string {
|
|
59
|
+
const padded = value
|
|
60
|
+
.replaceAll('-', '+')
|
|
61
|
+
.replaceAll('_', '/')
|
|
62
|
+
.padEnd(Math.ceil(value.length / 4) * 4, '=');
|
|
63
|
+
const binary = atob(padded);
|
|
64
|
+
const bytes = new Uint8Array(binary.length);
|
|
65
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
66
|
+
return new TextDecoder().decode(bytes);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function constantTimeEqual(a: string, b: string): boolean {
|
|
70
|
+
if (a.length !== b.length) return false;
|
|
71
|
+
let result = 0;
|
|
72
|
+
for (let i = 0; i < a.length; i++) result |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
73
|
+
return result === 0;
|
|
74
|
+
}
|
package/src/browser.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
export type { P2PAccessTokenClaims } from './access-token';
|
|
2
|
+
export { createP2PAccessToken, verifyP2PAccessToken } from './access-token';
|
|
3
|
+
export { Callbacks } from './callbacks';
|
|
4
|
+
export type { PacketChannel, PacketChannelMode } from './channels';
|
|
5
|
+
export {
|
|
6
|
+
AbortError,
|
|
7
|
+
Auth,
|
|
8
|
+
Client,
|
|
9
|
+
ColyseusSDK,
|
|
10
|
+
CompatRoom,
|
|
11
|
+
configureP2PColyseusClient,
|
|
12
|
+
connectRoomOverChannel,
|
|
13
|
+
getStateCallbacks,
|
|
14
|
+
MatchMakeError,
|
|
15
|
+
registerLoopbackRoom,
|
|
16
|
+
registerSerializer,
|
|
17
|
+
resetP2PColyseusClient,
|
|
18
|
+
} from './client';
|
|
19
|
+
export { SignalingRelayCoordinator } from './cloudflare/coordinator';
|
|
20
|
+
export type { RelayLimits } from './cloudflare/limits';
|
|
21
|
+
export { DEFAULT_RELAY_LIMITS } from './cloudflare/limits';
|
|
22
|
+
export { applyStatePatch, clone, createStatePatch, encodeSnapshot } from './codec';
|
|
23
|
+
export type {
|
|
24
|
+
NetDiagnostics,
|
|
25
|
+
RelayProofDiagnostics,
|
|
26
|
+
RelayQuota,
|
|
27
|
+
TransportName,
|
|
28
|
+
} from './diagnostics';
|
|
29
|
+
export type {
|
|
30
|
+
EngineNetBackend,
|
|
31
|
+
EngineNetConnectOptions,
|
|
32
|
+
EngineNetTransport,
|
|
33
|
+
EngineStateReplication,
|
|
34
|
+
P2PColyseusBackendOptions,
|
|
35
|
+
P2PColyseusMode,
|
|
36
|
+
} from './engine';
|
|
37
|
+
export { createP2PColyseusBackend } from './engine';
|
|
38
|
+
export { createLoopbackPair } from './loopback';
|
|
39
|
+
export type { RoomCache, SeatReservation, ServerOptions, Type } from './platform';
|
|
40
|
+
export {
|
|
41
|
+
__globalEndpoints,
|
|
42
|
+
accept,
|
|
43
|
+
addRoomType,
|
|
44
|
+
auth,
|
|
45
|
+
buildSeatReservation,
|
|
46
|
+
ClientArray,
|
|
47
|
+
ClientState,
|
|
48
|
+
Clock,
|
|
49
|
+
CloseCode,
|
|
50
|
+
connectClientToRoom,
|
|
51
|
+
controller,
|
|
52
|
+
create,
|
|
53
|
+
createEndpoint,
|
|
54
|
+
createInternalContext,
|
|
55
|
+
createMiddleware,
|
|
56
|
+
createRoom,
|
|
57
|
+
createRouter,
|
|
58
|
+
Deferred,
|
|
59
|
+
Delayed,
|
|
60
|
+
debugAndPrintError,
|
|
61
|
+
debugConnection,
|
|
62
|
+
debugDriver,
|
|
63
|
+
debugError,
|
|
64
|
+
debugMatchMaking,
|
|
65
|
+
debugMessage,
|
|
66
|
+
debugPatch,
|
|
67
|
+
debugPresence,
|
|
68
|
+
defineRoom,
|
|
69
|
+
defineRoomType,
|
|
70
|
+
defineServer,
|
|
71
|
+
disconnectAll,
|
|
72
|
+
driver,
|
|
73
|
+
dynamicImport,
|
|
74
|
+
ErrorCode,
|
|
75
|
+
findOneRoomAvailable,
|
|
76
|
+
generateId,
|
|
77
|
+
getAllHandlers,
|
|
78
|
+
getBearerToken,
|
|
79
|
+
getHandler,
|
|
80
|
+
getLocalRoomById,
|
|
81
|
+
getMessageBytes,
|
|
82
|
+
getRoomById,
|
|
83
|
+
getRoomClass,
|
|
84
|
+
getTransport,
|
|
85
|
+
gracefullyShutdown,
|
|
86
|
+
Hash,
|
|
87
|
+
handleCreateRoom,
|
|
88
|
+
healthCheckAllProcesses,
|
|
89
|
+
healthCheckProcessId,
|
|
90
|
+
initializeRoomCache,
|
|
91
|
+
isDevMode,
|
|
92
|
+
JWT,
|
|
93
|
+
join,
|
|
94
|
+
joinById,
|
|
95
|
+
joinOrCreate,
|
|
96
|
+
LobbyRoom,
|
|
97
|
+
LocalDriver,
|
|
98
|
+
LocalPresence,
|
|
99
|
+
listen,
|
|
100
|
+
logger,
|
|
101
|
+
matchMaker,
|
|
102
|
+
monitor,
|
|
103
|
+
NoopTransport,
|
|
104
|
+
OnAuthException,
|
|
105
|
+
OnCreateException,
|
|
106
|
+
OnDisposeException,
|
|
107
|
+
OnJoinException,
|
|
108
|
+
OnLeaveException,
|
|
109
|
+
OnMessageException,
|
|
110
|
+
onReady,
|
|
111
|
+
Protocol,
|
|
112
|
+
playground,
|
|
113
|
+
presence,
|
|
114
|
+
processId,
|
|
115
|
+
publicAddress,
|
|
116
|
+
QueueRoom,
|
|
117
|
+
query,
|
|
118
|
+
RedisDriver,
|
|
119
|
+
RedisPresence,
|
|
120
|
+
RegisteredHandler,
|
|
121
|
+
RelayRoom,
|
|
122
|
+
RoomInternalState,
|
|
123
|
+
reconnect,
|
|
124
|
+
remoteRoomCall,
|
|
125
|
+
removeRoomType,
|
|
126
|
+
requestFromIPC,
|
|
127
|
+
reserveMultipleSeatsFor,
|
|
128
|
+
reserveSeatFor,
|
|
129
|
+
room,
|
|
130
|
+
SchemaSerializer,
|
|
131
|
+
Server,
|
|
132
|
+
ServerError,
|
|
133
|
+
SimulationIntervalException,
|
|
134
|
+
setHealthChecksEnabled,
|
|
135
|
+
setup,
|
|
136
|
+
spliceOne,
|
|
137
|
+
state,
|
|
138
|
+
stats,
|
|
139
|
+
subscribeIPC,
|
|
140
|
+
subscribeLobby,
|
|
141
|
+
TimedEventException,
|
|
142
|
+
Transport,
|
|
143
|
+
toNodeHandler,
|
|
144
|
+
updateLobby,
|
|
145
|
+
validate,
|
|
146
|
+
WebSocketClient,
|
|
147
|
+
WebSocketTransport,
|
|
148
|
+
} from './platform';
|
|
149
|
+
export type { Envelope, Snapshot, StatePatch, StatePatchOperation } from './protocol';
|
|
150
|
+
export { isEnvelope, P2P_CLOSE_CODES } from './protocol';
|
|
151
|
+
export { CloudflareRelayPacketChannel } from './relay';
|
|
152
|
+
export type { CompatClient } from './room';
|
|
153
|
+
export { Room } from './room';
|
|
154
|
+
export type { RoomClass } from './runtime';
|
|
155
|
+
export { UniversalRoomRuntime } from './runtime';
|
|
156
|
+
export {
|
|
157
|
+
$changes,
|
|
158
|
+
$childType,
|
|
159
|
+
$decoder,
|
|
160
|
+
$deleteByIndex,
|
|
161
|
+
$encoder,
|
|
162
|
+
$filter,
|
|
163
|
+
$getByIndex,
|
|
164
|
+
$refId,
|
|
165
|
+
$track,
|
|
166
|
+
ArraySchema,
|
|
167
|
+
Callbacks as SchemaCallbacks,
|
|
168
|
+
ChangeTree,
|
|
169
|
+
CollectionSchema,
|
|
170
|
+
Decoder,
|
|
171
|
+
decode,
|
|
172
|
+
decodeKeyValueOperation,
|
|
173
|
+
decodeSchemaOperation,
|
|
174
|
+
defineCustomTypes,
|
|
175
|
+
defineTypes,
|
|
176
|
+
deprecated,
|
|
177
|
+
dumpChanges,
|
|
178
|
+
Encoder,
|
|
179
|
+
encode,
|
|
180
|
+
encodeArray,
|
|
181
|
+
encodeKeyValueOperation,
|
|
182
|
+
encodeSchemaOperation,
|
|
183
|
+
entity,
|
|
184
|
+
getDecoderStateCallbacks,
|
|
185
|
+
getRawChangesCallback,
|
|
186
|
+
MapSchema,
|
|
187
|
+
Metadata,
|
|
188
|
+
OPERATION,
|
|
189
|
+
Reflection,
|
|
190
|
+
ReflectionField,
|
|
191
|
+
ReflectionType,
|
|
192
|
+
registerType,
|
|
193
|
+
Schema,
|
|
194
|
+
SetSchema,
|
|
195
|
+
StateCallbackStrategy,
|
|
196
|
+
StateView,
|
|
197
|
+
schema,
|
|
198
|
+
TypeContext,
|
|
199
|
+
type,
|
|
200
|
+
view,
|
|
201
|
+
} from './schema';
|
|
202
|
+
export { createWebRTCDataChannelPacketChannel, WebRTCDataChannelPacketChannel } from './webrtc';
|
package/src/callbacks.ts
ADDED
package/src/channels.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Envelope } from './protocol';
|
|
2
|
+
|
|
3
|
+
export type PacketChannelMode = 'loopback' | 'websocket' | 'webrtc' | 'relay' | 'colyseus';
|
|
4
|
+
|
|
5
|
+
export interface PacketChannel {
|
|
6
|
+
readonly peerId: string;
|
|
7
|
+
readonly mode: PacketChannelMode;
|
|
8
|
+
send(envelope: Envelope): void;
|
|
9
|
+
onEnvelope(handler: (envelope: Envelope) => void): () => void;
|
|
10
|
+
onClose(handler: (reason?: string) => void): () => void;
|
|
11
|
+
close(reason?: string): void;
|
|
12
|
+
}
|