@gridspawn/core 0.0.0-stage → 0.2.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/CHANGELOG.md +12 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +18 -0
- package/README.md +86 -2
- package/bundle/THIRD-PARTY-NOTICES.txt +3 -0
- package/bundle/gridspawn-core.js +3 -0
- package/bundle/gridspawn-core.js.map +7 -0
- package/dist/auth.d.ts +25 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +261 -0
- package/dist/auth.js.map +1 -0
- package/dist/authorization.d.ts +47 -0
- package/dist/authorization.d.ts.map +1 -0
- package/dist/authorization.js +139 -0
- package/dist/authorization.js.map +1 -0
- package/dist/client.d.ts +19 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +135 -0
- package/dist/client.js.map +1 -0
- package/dist/crypto.d.ts +3 -0
- package/dist/crypto.d.ts.map +1 -0
- package/dist/crypto.js +24 -0
- package/dist/crypto.js.map +1 -0
- package/dist/errors.d.ts +14 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +18 -0
- package/dist/errors.js.map +1 -0
- package/dist/http.d.ts +7 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +50 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/module-host.d.ts +47 -0
- package/dist/module-host.d.ts.map +1 -0
- package/dist/module-host.js +13 -0
- package/dist/module-host.js.map +1 -0
- package/dist/sessions.d.ts +23 -0
- package/dist/sessions.d.ts.map +1 -0
- package/dist/sessions.js +222 -0
- package/dist/sessions.js.map +1 -0
- package/dist/storage.d.ts +8 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +22 -0
- package/dist/storage.js.map +1 -0
- package/dist/types.d.ts +124 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +44 -4
- package/src/auth.ts +328 -0
- package/src/authorization.ts +191 -0
- package/src/client.ts +163 -0
- package/src/crypto.ts +30 -0
- package/src/errors.ts +23 -0
- package/src/http.ts +74 -0
- package/src/index.ts +37 -0
- package/src/module-host.ts +65 -0
- package/src/sessions.ts +324 -0
- package/src/storage.ts +28 -0
- package/src/types.ts +141 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
- `ExternalAuthorizationDriver`: sign-in for apps that receive the OAuth callback outside the page, such as an Electron game. The app supplies `open(url)` (its main process calls `shell.openExternal` or loads a BrowserWindow) and passes the callback URL it receives (a reverse-domain scheme or a loopback URL) to `completeAuthorization(url)`; a callback of another sign-in is ignored. `cancelAuthorization()` ends a pending sign-in. New errors: `auth/authorization_cancelled`, `auth/authorization_superseded` (a newer sign-in replaced it), `auth/authorization_timeout`, `auth/authorization_open_failed`, `auth/authorization_opener_required`. PKCE, state and the redirect check are the ones every sign-in uses. No Node imports.
|
|
6
|
+
- The package is ready for npm: licence MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`), set to publish as a public scoped package (`publishConfig.access`); it ships `src/` so the source maps resolve, and `bundle/gridspawn-core.js`, the API in one minified ES module for pages without a bundler.
|
|
7
|
+
- Voice admission accepts named rooms (`^[a-z][a-z0-9_-]{0,31}$`, `voice/invalid_room` otherwise).
|
|
8
|
+
- Voice admission no longer compares the server's expiry times with the local clock; it returns `serverTime` (from `Date`) when the runtime can read it.
|
|
9
|
+
|
|
10
|
+
## 0.1.0
|
|
11
|
+
|
|
12
|
+
First version.
|
package/LICENSE-APACHE
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/LICENSE-MIT
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gridspawn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
|
6
|
+
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
|
7
|
+
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
|
9
|
+
following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial
|
|
12
|
+
portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
|
15
|
+
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
|
16
|
+
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
17
|
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
|
18
|
+
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,87 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@gridspawn/core`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Browser-safe Gridspawn bootstrap, OAuth/PKCE, player assertion, and participant-session attachment.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { Gridspawn } from '@gridspawn/core';
|
|
7
|
+
|
|
8
|
+
const gridspawn = await Gridspawn.create({
|
|
9
|
+
appId: 'your_app_id',
|
|
10
|
+
environment: 'production',
|
|
11
|
+
redirectUri: 'https://game.example/gridspawn/callback',
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
const user = await gridspawn.auth.signIn({
|
|
15
|
+
scopes: ['identity.basic', 'voice.join'],
|
|
16
|
+
});
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The registered callback page completes popup authorization without exposing tokens:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { completeAuthorizationPopup } from '@gridspawn/core';
|
|
23
|
+
|
|
24
|
+
completeAuthorizationPopup();
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
An app that receives the callback outside the page, such as an Electron game, opens the authorization page itself and hands the callback URL back. The callback arrives on a registered reverse-domain scheme (`com.studio.game:/oauth`) or a loopback URL (`http://127.0.0.1:<port>/callback`); the app's main process passes it to the page over the app's own IPC, so this works with `contextIsolation` on. Serve the Electron page from a scheme registered as standard and secure (`app://localhost`): sign-in needs Web Crypto, which exists only in a secure context. A callback whose `state` belongs to no pending sign-in is ignored (`completeAuthorization` returns `false`); `cancelAuthorization()` ends a pending one.
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { ExternalAuthorizationDriver, Gridspawn } from '@gridspawn/core';
|
|
31
|
+
|
|
32
|
+
const authorization = new ExternalAuthorizationDriver({
|
|
33
|
+
open: (url) => window.gridspawnAuth.open(url), // the app's own IPC
|
|
34
|
+
});
|
|
35
|
+
window.gridspawnAuth.onCallback((url) => authorization.completeAuthorization(url));
|
|
36
|
+
|
|
37
|
+
const gridspawn = await Gridspawn.create({
|
|
38
|
+
appId: 'your_app_id',
|
|
39
|
+
environment: 'production',
|
|
40
|
+
redirectUri: 'com.studio.game:/oauth',
|
|
41
|
+
authorizationDriver: authorization,
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
For a Gridspawn-authenticated player, request a one-use assertion and send only that assertion to the game's backend:
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
const playerAssertion = await gridspawn.auth.createPlayerAssertion({
|
|
49
|
+
audience: 'game_server',
|
|
50
|
+
challenge: gameLogin.gridspawnBindingChallenge,
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Authenticated users and server-verified guests attach the same restricted ticket shape. Guest attachment does not require OAuth:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
const attached = await gridspawn.sessions.attach({
|
|
58
|
+
participantTicket: gameLogin.gridspawnParticipantTicket,
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The package does not expose OAuth tokens or module grants through gameplay APIs. Optional modules use the internal module-host boundary, which renews short-lived grants against the active session/participant binding before calling the module gateway. The default OAuth token store is memory-only; production native shells should supply protected storage. Browser persistence requires an explicit security-reviewed adapter.
|
|
63
|
+
|
|
64
|
+
Current backend limit: Voice grant renewal and module consumption are implemented. Presence and Interakt package consumption, package publication, automatic detach on backend revocation, and native protected-storage adapters remain future work.
|
|
65
|
+
|
|
66
|
+
## Without a bundler
|
|
67
|
+
|
|
68
|
+
The package is ES modules with TypeScript declarations, for bundlers and runtimes that resolve npm packages. `bundle/gridspawn-core.js` is the same API in one minified ES module (with a source map) for a page that loads scripts directly. With `@gridspawn/voice`, map both Core specifiers to that one file, so Voice uses the Core client the page created:
|
|
69
|
+
|
|
70
|
+
```html
|
|
71
|
+
<script type="importmap">
|
|
72
|
+
{
|
|
73
|
+
"imports": {
|
|
74
|
+
"@gridspawn/core": "/vendor/gridspawn-core.js",
|
|
75
|
+
"@gridspawn/core/internal/module-host": "/vendor/gridspawn-core.js"
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
</script>
|
|
79
|
+
<script type="module">
|
|
80
|
+
import { Gridspawn } from '@gridspawn/core';
|
|
81
|
+
import { withVoice } from '/vendor/gridspawn-voice.js';
|
|
82
|
+
</script>
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Licence
|
|
86
|
+
|
|
87
|
+
MIT OR Apache-2.0, at your option (`LICENSE-MIT`, `LICENSE-APACHE`). Copyright 2026 Gridspawn.
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/*! @gridspawn/core 0.2.0 | MIT OR Apache-2.0 | Gridspawn */
|
|
2
|
+
var n=class extends Error{code;status;requestId;retryable;constructor(e,r,i={}){super(r,i.cause===void 0?void 0:{cause:i.cause}),this.name="GridspawnError",this.code=e,this.status=i.status,this.requestId=i.requestId,this.retryable=i.retryable??!1}};function p(t,e){return new n(t,e)}function T(t=32){let e=U(),r=new Uint8Array(t);return e.getRandomValues(r),S(r)}async function z(t){let e=await U().subtle.digest("SHA-256",new TextEncoder().encode(t));return S(new Uint8Array(e))}function S(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function U(){if(!globalThis.crypto?.getRandomValues||!globalThis.crypto.subtle)throw new n("platform/crypto_unavailable","A Web Crypto implementation is required by Gridspawn Core.");return globalThis.crypto}async function l(t,e,r,i={}){let s=i.retryIdempotent===!0?i.maxAttempts??3:1,a;for(let c=1;c<=s;c+=1){try{let o=await t(e,r),h=await o.json().catch(()=>null);if(o.ok&&h!==null)return h;if(o.ok)throw new n("protocol/invalid_response","Gridspawn returned an invalid response.",{status:o.status});let d=h,u=typeof d?.error=="object"?d.error:void 0,m=typeof d?.error=="string"?d.error:void 0,f=d?.requestId??o.headers.get("x-gridspawn-request-id"),w=new n(u?.code??d?.code??(m?`auth/${m}`:"request/failed"),u?.message??d?.error_description??`Gridspawn request failed with HTTP ${o.status}.`,{status:o.status,retryable:o.status===429||o.status>=500,...f==null?{}:{requestId:f}});if(!w.retryable||c===s)throw w;a=w}catch(o){if(o instanceof n){if(!o.retryable||c===s)throw o;a=o}else if(a=new n("network/request_failed","The Gridspawn request could not be completed.",{retryable:!0,cause:o}),c===s)throw a}await new Promise(o=>setTimeout(o,50*2**(c-1)))}throw a}async function G(t,e,r){await l(t,e,r)}var g=class{#e;#t;#r;#i;#n;#a;#c;#o=new Set;#s=null;constructor(e){this.#e=e.appId,this.#t=e.environment,this.#r=e.oauthBaseUrl.replace(/\/$/u,""),this.#i=e.fetcher,this.#n=e.storage,this.#a=e.authorizationDriver,this.#c=e.redirectUri}get currentUser(){return this.#s?.user??null}async signIn(e){let r=this.#a,i=e.redirectUri??this.#c;if(r===void 0||i===void 0)throw p("auth/authorization_driver_required","Sign-in requires a registered redirect URI and an authorization driver.");let s=E(e.scopes),a=T(64),c=await z(a),o=T(),h=T(),d=new URL(`${this.#r}/authorize`);d.search=new URLSearchParams({response_type:"code",client_id:this.#e,environment:this.#t,redirect_uri:i,scope:s.join(" "),state:o,nonce:h,code_challenge:c,code_challenge_method:"S256"}).toString();let u=new URL(await r.authorize({authorizationUrl:d.toString(),redirectUri:i,state:o}));if(!M(u,new URL(i)))throw new n("auth/redirect_mismatch","The authorization callback does not match the registered redirect URI.");if(u.searchParams.get("state")!==o)throw new n("auth/state_mismatch","The authorization callback state is invalid.");let m=u.searchParams.get("error");if(m!==null)throw new n(`auth/${m}`,"Gridspawn authorization was not approved.");let f=u.searchParams.get("code");if(f===null||f.length===0)throw new n("auth/invalid_callback","The authorization callback has no code.");let w=await this.#h(new URLSearchParams({grant_type:"authorization_code",client_id:this.#e,code:f,redirect_uri:i,code_verifier:a})),b=P(w);return await this.#n.save(b),this.#s=b,this.#d({type:"signed_in",user:b.user}),b.user}async restoreSession(){let e=await this.#n.load();if(e===null)return this.#s=null,{status:"signed_out"};if(!R(e))return await this.#n.clear(),this.#s=null,{status:"interaction_required",reason:"stored_session_invalid"};if(this.#s=e,e.accessExpiresAt>Date.now()+3e4)return{status:"signed_in",user:e.user};try{return{status:"signed_in",user:(await this.#u(e.refreshToken)).user}}catch(r){if(r instanceof n&&!r.retryable)return await this.#n.clear(),this.#s=null,this.#d({type:"revoked"}),{status:"interaction_required",reason:r.code};throw r}}async requestScopes(e){let r=this.#s?.scopes??[];return this.signIn({scopes:[...r,...e]})}async signOut(e={}){if(e.everywhere===!0)throw new n("feature/not_available","Account-wide SDK sign-out is not available in the current backend contract.");let r=this.#s??await this.#n.load();if(this.#s=null,await this.#n.clear(),this.#d({type:"signed_out"}),r===null)return;let i=new URL(`${this.#r}/revoke`);i.search=new URLSearchParams({client_id:this.#e,environment:this.#t}).toString(),await G(this.#i,i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({token:r.refreshToken,client_id:this.#e})})}onSessionChanged(e){return this.#o.add(e),()=>this.#o.delete(e)}async createPlayerAssertion(e){if(!j(e.challenge))throw p("auth/invalid_binding_challenge","A 32\u2013256 character transport-safe binding challenge is required.");let r=await this.#p(),i=new URL(`${this.#r.replace(/\/oauth$/u,"")}/v1/auth/player-assertions`);i.search=new URLSearchParams({client_id:this.#e,environment:this.#t}).toString();let s=await l(this.#i,i,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(typeof s.playerAssertion!="string"||s.playerAssertion.length===0)throw new n("protocol/invalid_response","Gridspawn returned an invalid assertion.");return s.playerAssertion}async#p(){let e=this.#s??await this.#n.load();if(e===null||!R(e))throw new n("auth/sign_in_required","A Gridspawn account sign-in is required.");return this.#s=e,e.accessExpiresAt>Date.now()+3e4?e.accessToken:(await this.#u(e.refreshToken)).accessToken}async#u(e){let r=await this.#h(new URLSearchParams({grant_type:"refresh_token",client_id:this.#e,refresh_token:e})),i=P(r);return await this.#n.save(i),this.#s=i,this.#d({type:"refreshed",user:i.user}),i}async#h(e){let r=new URL(`${this.#r}/token`);return r.search=new URLSearchParams({client_id:this.#e,environment:this.#t}).toString(),l(this.#i,r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e})}#d(e){for(let r of this.#o)try{r(e)}catch{}}};function P(t){if(t.token_type!=="Bearer"||typeof t.access_token!="string"||typeof t.refresh_token!="string"||!Number.isFinite(t.expires_in)||t.expires_in<=0||typeof t.user?.subject!="string"||typeof t.user.displayName!="string")throw new n("protocol/invalid_response","Gridspawn returned an invalid token response.");let e={subject:t.user.subject,displayName:t.user.displayName,...t.user.avatarObjectPath===void 0?{}:{avatarObjectPath:t.user.avatarObjectPath}};return{accessToken:t.access_token,refreshToken:t.refresh_token,accessExpiresAt:Date.now()+t.expires_in*1e3,scopes:E(t.scope.split(" ")),user:e}}function E(t){let e=[...new Set(t.map(r=>r.trim()).filter(Boolean))].sort();if(e.length===0||e.length>32||e.some(r=>r.length>128||!/^[A-Za-z0-9.\-_:]+$/u.test(r)))throw p("auth/invalid_scope","One or more requested Gridspawn scopes are invalid.");return e}function j(t){return t.length>=32&&t.length<=256&&/^[A-Za-z0-9._~-]+$/u.test(t)}function R(t){return typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&Number.isFinite(t.accessExpiresAt)&&Array.isArray(t.scopes)&&typeof t.user?.subject=="string"&&typeof t.user.displayName=="string"}function M(t,e){if(t.origin!==e.origin||t.pathname!==e.pathname)return!1;for(let[r,i]of e.searchParams)if(t.searchParams.get(r)!==i)return!1;return t.hash===e.hash}var $="gridspawn.oauth.callback",y=class{#e;#t;constructor(e={}){this.#e=e.timeoutMs??600*1e3,this.#t=e.windowFeatures??"popup=yes,width=540,height=760"}authorize(e){if(typeof window>"u")throw new n("platform/browser_required","Browser popup authorization requires a browser window.");if(new URL(e.redirectUri).origin!==window.location.origin)throw new n("auth/popup_redirect_origin_invalid","Popup authorization requires a callback on the game page origin.");let r=window.open(e.authorizationUrl,"gridspawn_authorize",this.#t);if(r===null)throw new n("auth/popup_blocked","The Gridspawn authorization popup was blocked.");let i=new URL(e.redirectUri).origin;return new Promise((s,a)=>{let c=window.setTimeout(()=>h(()=>a(new n("auth/authorization_timeout","Gridspawn authorization did not finish before the timeout."))),this.#e),o=d=>{let u=d.data;d.origin!==i||d.source!==r||!V(u)||h(()=>s(u.url))},h=d=>{window.clearTimeout(c),window.removeEventListener("message",o),r.closed||r.close(),d()};window.addEventListener("message",o)})}};function O(t=globalThis.location?.href){return typeof window>"u"||window.opener===null||t===void 0?!1:(window.opener.postMessage({type:$,url:t},window.location.origin),window.close(),!0)}var k=class{#e;#t;#r=null;constructor(e){if(typeof e?.open!="function")throw p("auth/authorization_opener_required","External authorization requires an open(url) function.");this.#e=e.open,this.#t=e.timeoutMs??600*1e3}get pending(){return this.#r!==null}authorize(e){this.#i(null,new n("auth/authorization_superseded","A newer Gridspawn sign-in replaced this one."));let r=new Promise((s,a)=>{let c=setTimeout(()=>this.#i(null,new n("auth/authorization_timeout","Gridspawn authorization did not finish before the timeout.")),this.#t);this.#r={state:e.state,resolve:s,reject:a,timeout:c}}),i=this.#r;return Promise.resolve().then(()=>this.#e(e.authorizationUrl)).catch(s=>{this.#r===i&&this.#i(null,new n("auth/authorization_open_failed","The Gridspawn authorization page could not be opened.",{cause:s}))}),r}completeAuthorization(e){let r=this.#r;if(r===null)return!1;let i;try{i=new URL(String(e))}catch{return!1}return i.searchParams.get("state")!==r.state?!1:(this.#i(i.href,null),!0)}cancelAuthorization(){return this.#r===null?!1:(this.#i(null,new n("auth/authorization_cancelled","Gridspawn authorization was cancelled.")),!0)}#i(e,r){let i=this.#r;i!==null&&(this.#r=null,clearTimeout(i.timeout),e!==null?i.resolve(e):r!==null&&i.reject(r))}};function V(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.type===$&&typeof e.url=="string"}var q=new WeakMap;function L(t,e){q.set(t,e)}function D(t){let e=q.get(t);if(e===void 0)throw new n("core/module_host_unavailable","This Gridspawn client cannot host optional SDK modules.");return e}var _=class{#e;#t;#r;#i;#n=new Map;#a=new Map;constructor(e){this.#e=e.appId,this.#t=e.environment,this.#r=e.apiBaseUrl.replace(/\/$/u,""),this.#i=e.fetcher}get attached(){return[...this.#n.values()].map(e=>e.session)}async attach(e){if(!/^gpt1\.[A-Za-z0-9_-]{43}$/u.test(e.participantTicket))throw new n("session/invalid_request","A valid Gridspawn participant ticket is required.");let r=new URL(`${this.#r}/sessions/attach`);r.search=new URLSearchParams({appId:this.#e,environment:this.#t}).toString();let i=await l(this.#i,r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({participantTicket:e.participantTicket})}),s=K(i);return this.#n.set(s.session.id,s),s.session}async detach(e){this.#n.delete(e.id)}async admitVoice(e,r,i){let s=this.#n.get(r.id);if(s===void 0||s.session.participant.id!==r.participant.id||!s.session.capabilities.includes("voice"))throw new n("session/not_attached","Attach a session with the Voice capability before joining Voice.");if(!/^[a-z][a-z0-9_-]{0,31}$/u.test(i.room))throw new n("voice/invalid_room","Voice room names are a-z first, then a-z 0-9 _ -.");let a=await this.#c(s,"voice"),c=null,h=await l(async(m,f)=>{let w=await this.#i(m,f);return c=w.headers.get("date"),w},`${e.replace(/\/$/u,"")}/admissions`,{method:"POST",headers:{Authorization:`Bearer ${a.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({room:i.room,...i.endpointId===void 0?{}:{endpointId:i.endpointId}})}),d=F(h,s.session,i.room),u=c===null?Number.NaN:Date.parse(c)/1e3;return Number.isFinite(u)?{...d,serverTime:u}:d}clear(){this.#n.clear(),this.#a.clear()}async#c(e,r){let i=e.grants.get(r);if(i===void 0)throw new n("session/capability_unavailable",`The attached session does not grant ${r}.`);if(i.expiresAt>Date.now()+6e4)return i;let s=`${e.session.id}:${r}`,a=this.#a.get(s);if(a!==void 0)return a;let c=this.#o(e,r,i).finally(()=>{this.#a.delete(s)});return this.#a.set(s,c),c}async#o(e,r,i){let s=new URL(`${this.#r}/sessions/${encodeURIComponent(e.session.id)}/grants/${r}/renew`);s.search=new URLSearchParams({appId:this.#e,environment:this.#t}).toString();let a=await l(this.#i,s,{method:"POST",headers:{Authorization:`Bearer ${i.accessToken}`}}),c=N(a);return e.grants.set(r,c),c}};function K(t){if(typeof t.sessionId!="string"||typeof t.participant?.participantId!="string"||typeof t.participant.subject!="string"||!H(t.participant.identityKind)||t.participant.displayName!==void 0&&typeof t.participant.displayName!="string"||t.participant.identityKind==="server_verified_guest"&&(t.participant.displayName===void 0||t.participant.displayName.length===0)||!Array.isArray(t.modules))throw new n("protocol/invalid_response","Gridspawn returned an invalid session.");let e=new Map;for(let i of t.modules){if(!Z(i))throw new n("protocol/invalid_response","Gridspawn returned an unknown module.");let s=t.grants?.[i];if(s===void 0||s.tokenType!=="Bearer"||typeof s.accessToken!="string"||!Number.isFinite(s.expiresIn)||s.expiresIn<=0)throw new n("protocol/invalid_response","Gridspawn returned an invalid module grant.");e.set(i,N(s))}if(e.size===0)throw new n("protocol/invalid_response","Gridspawn returned no session capabilities.");return{session:Object.freeze({id:t.sessionId,participant:Object.freeze({id:t.participant.participantId,subject:t.participant.subject,identityKind:t.participant.identityKind,...t.participant.displayName===void 0?{}:{displayName:t.participant.displayName}}),capabilities:Object.freeze([...e.keys()]),get grantExpiresAt(){return new Date(Math.min(...[...e.values()].map(i=>i.expiresAt)))}}),grants:e}}function N(t){if(t.tokenType!=="Bearer"||typeof t.accessToken!="string"||!Number.isFinite(t.expiresIn)||t.expiresIn<=0||typeof t.scope!="string")throw new n("protocol/invalid_response","Gridspawn returned an invalid module grant.");return{accessToken:t.accessToken,tokenType:"Bearer",expiresIn:t.expiresIn,scope:t.scope,expiresAt:Date.now()+t.expiresIn*1e3}}function F(t,e,r){if(t.sessionId!==e.id||t.participant?.participantId!==e.participant.id||t.participant.identityKind!==e.participant.identityKind||t.participant.displayName!==void 0&&typeof t.participant.displayName!="string"||!/^gve1\.[a-f0-9]{32}$/u.test(t.endpointId)||t.room?.name!==r||typeof t.room.roomId!="string"||t.room.roomId.length===0||!I(t.admissionExpiresAt)||!J(t.sfu?.url)||!/^[A-Za-z0-9_-]{3,128}$/u.test(t.sfu.nodeId)||t.sfu.roomId!==t.room.roomId||typeof t.sfu.token!="string"||t.sfu.token.length===0||!I(t.sfu.expiresAt)||!I(t.sfu.limits?.audioMaxBps)||!I(t.sfu.limits?.maxIncomingBps))throw new n("protocol/invalid_response","Gridspawn returned an invalid Voice admission.");return t}function I(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function J(t){if(typeof t!="string")return!1;try{let e=new URL(t),r=e.hostname==="localhost"||e.hostname==="127.0.0.1";return e.protocol==="https:"||r&&e.protocol==="http:"}catch{return!1}}function H(t){return t==="gridspawn_user"||t==="server_verified_guest"}function Z(t){return t==="presence"||t==="voice"||t==="interakt"}var v=class{#e=null;async load(){return this.#e===null?null:B(this.#e)}async save(e){this.#e=B(e)}async clear(){this.#e=null}};function B(t){return{accessToken:t.accessToken,refreshToken:t.refreshToken,accessExpiresAt:t.accessExpiresAt,scopes:[...t.scopes],user:{...t.user}}}var W="0.2.0",C=1,A=class{appId;environment;configuration;auth;sessions;#e=new Set;#t="ready";constructor(e,r,i){this.appId=e.appId,this.environment=e.environment,this.configuration=r;let s=e.authorizationDriver??(e.redirectUri!==void 0&&typeof window<"u"?new y:void 0);this.auth=new g({appId:e.appId,environment:e.environment,oauthBaseUrl:r.endpoints.oauth,fetcher:i,storage:e.tokenStorage??new v,...s===void 0?{}:{authorizationDriver:s},...e.redirectUri===void 0?{}:{redirectUri:e.redirectUri}}),this.sessions=new _({appId:e.appId,environment:e.environment,apiBaseUrl:r.endpoints.api,fetcher:i}),L(this,{admitVoice:a=>this.sessions.admitVoice(r.endpoints.voice,a.session,{room:a.room,...a.endpointId===void 0?{}:{endpointId:a.endpointId}}),onShutdown:a=>(this.#e.add(a),()=>this.#e.delete(a))})}get lifecycleState(){return this.#t}hasModule(e){return this.configuration.modules.includes(e)}async shutdown(){this.#t!=="stopped"&&(this.#t="shutting_down",await Promise.all([...this.#e].map(e=>e())),this.#e.clear(),this.sessions.clear(),this.#t="stopped")}},x=class{static async create(e){Q(e);let r=e.fetch??globalThis.fetch;if(r===void 0)throw p("platform/fetch_unavailable","A Fetch API implementation is required.");let i=(e.baseUrl??"https://sdk.gridspawn.net").replace(/\/$/u,""),s=new URL(`${i}/v1/bootstrap`);s.search=new URLSearchParams({appId:e.appId,environment:e.environment,protocolVersion:String(C),sdkVersion:W}).toString();try{let a=await l(r,s,{method:"GET",headers:{Accept:"application/json"}},{retryIdempotent:!0});return X(a,e),new A(e,a,r)}catch(a){throw ee(e,{level:"error",code:a instanceof n?a.code:"core/bootstrap_failed",message:"Gridspawn Core bootstrap failed.",...a instanceof n&&a.requestId!==void 0?{requestId:a.requestId}:{}}),a}}};function Q(t){if(!/^[A-Za-z0-9_-]{3,128}$/u.test(t.appId))throw p("config/invalid_app_id","A valid Gridspawn appId is required.");if(!Y(t.environment))throw p("config/invalid_environment","A valid Gridspawn environment is required.")}function X(t,e){if(t.ok!==!0||t.application?.appId!==e.appId||t.environment!==e.environment||t.protocol?.selected!==C||!Array.isArray(t.modules)||typeof t.endpoints?.api!="string"||typeof t.endpoints.oauth!="string"||typeof t.endpoints.voice!="string")throw new n("protocol/invalid_bootstrap","Gridspawn returned invalid bootstrap data.")}function Y(t){return t==="development"||t==="staging"||t==="production"}function ee(t,e){if(t.sdk?.logLevel!=="silent")try{t.sdk?.diagnostics?.(e)}catch{}}export{g as AuthClient,y as BrowserPopupAuthorizationDriver,k as ExternalAuthorizationDriver,x as Gridspawn,A as GridspawnClient,n as GridspawnError,v as MemoryTokenStorage,_ as SessionsClient,O as completeAuthorizationPopup,D as getModuleHost};
|
|
3
|
+
//# sourceMappingURL=gridspawn-core.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/errors.ts", "../src/crypto.ts", "../src/http.ts", "../src/auth.ts", "../src/authorization.ts", "../src/module-host.ts", "../src/sessions.ts", "../src/storage.ts", "../src/client.ts"],
|
|
4
|
+
"sourcesContent": ["export class GridspawnError extends Error {\n readonly code: string;\n readonly status: number | undefined;\n readonly requestId: string | undefined;\n readonly retryable: boolean;\n\n constructor(\n code: string,\n message: string,\n options: { status?: number; requestId?: string; retryable?: boolean; cause?: unknown } = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'GridspawnError';\n this.code = code;\n this.status = options.status;\n this.requestId = options.requestId;\n this.retryable = options.retryable ?? false;\n }\n}\n\nexport function configurationError(code: string, message: string): GridspawnError {\n return new GridspawnError(code, message);\n}\n", "import { GridspawnError } from './errors.js';\n\nexport function randomBase64Url(byteLength = 32): string {\n const crypto = requireCrypto();\n const bytes = new Uint8Array(byteLength);\n crypto.getRandomValues(bytes);\n return bytesToBase64Url(bytes);\n}\n\nexport async function pkceChallenge(verifier: string): Promise<string> {\n const digest = await requireCrypto().subtle.digest('SHA-256', new TextEncoder().encode(verifier));\n return bytesToBase64Url(new Uint8Array(digest));\n}\n\nfunction bytesToBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');\n}\n\nfunction requireCrypto(): Crypto {\n if (!globalThis.crypto?.getRandomValues || !globalThis.crypto.subtle) {\n throw new GridspawnError(\n 'platform/crypto_unavailable',\n 'A Web Crypto implementation is required by Gridspawn Core.',\n );\n }\n return globalThis.crypto;\n}\n\n", "import { GridspawnError } from './errors.js';\n\ninterface ErrorPayload {\n readonly error?: string | { readonly code?: string; readonly message?: string };\n readonly error_description?: string;\n readonly code?: string;\n readonly requestId?: string;\n}\n\nexport interface RequestPolicy {\n readonly retryIdempotent?: boolean;\n readonly maxAttempts?: number;\n}\n\nexport async function requestJson<T>(\n fetcher: typeof globalThis.fetch,\n input: string | URL,\n init: RequestInit,\n policy: RequestPolicy = {},\n): Promise<T> {\n const maximum = policy.retryIdempotent === true ? (policy.maxAttempts ?? 3) : 1;\n let lastError: unknown;\n for (let attempt = 1; attempt <= maximum; attempt += 1) {\n try {\n const response = await fetcher(input, init);\n const payload = await response.json().catch(() => null) as T | ErrorPayload | null;\n if (response.ok && payload !== null) return payload as T;\n if (response.ok) {\n throw new GridspawnError('protocol/invalid_response', 'Gridspawn returned an invalid response.', {\n status: response.status,\n });\n }\n const errorPayload = payload as ErrorPayload | null;\n const nested = typeof errorPayload?.error === 'object' ? errorPayload.error : undefined;\n const oauthCode = typeof errorPayload?.error === 'string' ? errorPayload.error : undefined;\n const requestId = errorPayload?.requestId ?? response.headers.get('x-gridspawn-request-id');\n const error = new GridspawnError(\n nested?.code ?? errorPayload?.code ?? (oauthCode ? `auth/${oauthCode}` : 'request/failed'),\n nested?.message\n ?? errorPayload?.error_description\n ?? `Gridspawn request failed with HTTP ${response.status}.`,\n {\n status: response.status,\n retryable: response.status === 429 || response.status >= 500,\n ...(requestId === null || requestId === undefined ? {} : { requestId }),\n },\n );\n if (!error.retryable || attempt === maximum) throw error;\n lastError = error;\n } catch (error) {\n if (error instanceof GridspawnError) {\n if (!error.retryable || attempt === maximum) throw error;\n lastError = error;\n } else {\n lastError = new GridspawnError(\n 'network/request_failed',\n 'The Gridspawn request could not be completed.',\n { retryable: true, cause: error },\n );\n if (attempt === maximum) throw lastError;\n }\n }\n await new Promise((resolve) => setTimeout(resolve, 50 * 2 ** (attempt - 1)));\n }\n throw lastError;\n}\n\nexport async function requestVoid(\n fetcher: typeof globalThis.fetch,\n input: string | URL,\n init: RequestInit,\n): Promise<void> {\n await requestJson<unknown>(fetcher, input, init);\n}\n", "import { pkceChallenge, randomBase64Url } from './crypto.js';\nimport { GridspawnError, configurationError } from './errors.js';\nimport { requestJson, requestVoid } from './http.js';\nimport type {\n AuthSessionEvent,\n AuthorizationDriver,\n GridspawnEnvironment,\n GridspawnUser,\n PlayerAssertionOptions,\n RestoreSessionResult,\n SignInOptions,\n TokenStorage,\n TokenStorageRecord,\n} from './types.js';\n\ninterface AuthClientOptions {\n readonly appId: string;\n readonly environment: GridspawnEnvironment;\n readonly oauthBaseUrl: string;\n readonly fetcher: typeof globalThis.fetch;\n readonly storage: TokenStorage;\n readonly authorizationDriver?: AuthorizationDriver;\n readonly redirectUri?: string;\n}\n\ninterface TokenResponse {\n readonly access_token: string;\n readonly token_type: 'Bearer';\n readonly expires_in: number;\n readonly refresh_token: string;\n readonly scope: string;\n readonly user: {\n readonly subject: string;\n readonly displayName: string;\n readonly avatarObjectPath?: string;\n };\n}\n\ninterface AssertionResponse {\n readonly playerAssertion: string;\n readonly tokenType: string;\n readonly expiresIn: number;\n}\n\nexport class AuthClient {\n readonly #appId: string;\n readonly #environment: GridspawnEnvironment;\n readonly #oauthBaseUrl: string;\n readonly #fetcher: typeof globalThis.fetch;\n readonly #storage: TokenStorage;\n readonly #authorizationDriver: AuthorizationDriver | undefined;\n readonly #redirectUri: string | undefined;\n readonly #listeners = new Set<(event: AuthSessionEvent) => void>();\n #session: TokenStorageRecord | null = null;\n\n constructor(options: AuthClientOptions) {\n this.#appId = options.appId;\n this.#environment = options.environment;\n this.#oauthBaseUrl = options.oauthBaseUrl.replace(/\\/$/u, '');\n this.#fetcher = options.fetcher;\n this.#storage = options.storage;\n this.#authorizationDriver = options.authorizationDriver;\n this.#redirectUri = options.redirectUri;\n }\n\n get currentUser(): GridspawnUser | null {\n return this.#session?.user ?? null;\n }\n\n async signIn(options: SignInOptions): Promise<GridspawnUser> {\n const driver = this.#authorizationDriver;\n const redirectUri = options.redirectUri ?? this.#redirectUri;\n if (driver === undefined || redirectUri === undefined) {\n throw configurationError(\n 'auth/authorization_driver_required',\n 'Sign-in requires a registered redirect URI and an authorization driver.',\n );\n }\n const scopes = normalizeScopes(options.scopes);\n const verifier = randomBase64Url(64);\n const challenge = await pkceChallenge(verifier);\n const state = randomBase64Url();\n const nonce = randomBase64Url();\n const authorizationUrl = new URL(`${this.#oauthBaseUrl}/authorize`);\n authorizationUrl.search = new URLSearchParams({\n response_type: 'code',\n client_id: this.#appId,\n environment: this.#environment,\n redirect_uri: redirectUri,\n scope: scopes.join(' '),\n state,\n nonce,\n code_challenge: challenge,\n code_challenge_method: 'S256',\n }).toString();\n const callback = new URL(await driver.authorize({\n authorizationUrl: authorizationUrl.toString(),\n redirectUri,\n state,\n }));\n if (!callbackMatchesRedirect(callback, new URL(redirectUri))) {\n throw new GridspawnError(\n 'auth/redirect_mismatch',\n 'The authorization callback does not match the registered redirect URI.',\n );\n }\n if (callback.searchParams.get('state') !== state) {\n throw new GridspawnError('auth/state_mismatch', 'The authorization callback state is invalid.');\n }\n const oauthError = callback.searchParams.get('error');\n if (oauthError !== null) {\n throw new GridspawnError(`auth/${oauthError}`, 'Gridspawn authorization was not approved.');\n }\n const code = callback.searchParams.get('code');\n if (code === null || code.length === 0) {\n throw new GridspawnError('auth/invalid_callback', 'The authorization callback has no code.');\n }\n const token = await this.#tokenRequest(new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: this.#appId,\n code,\n redirect_uri: redirectUri,\n code_verifier: verifier,\n }));\n const session = tokenRecord(token);\n await this.#storage.save(session);\n this.#session = session;\n this.#emit({ type: 'signed_in', user: session.user });\n return session.user;\n }\n\n async restoreSession(): Promise<RestoreSessionResult> {\n const stored = await this.#storage.load();\n if (stored === null) {\n this.#session = null;\n return { status: 'signed_out' };\n }\n if (!validStorageRecord(stored)) {\n await this.#storage.clear();\n this.#session = null;\n return { status: 'interaction_required', reason: 'stored_session_invalid' };\n }\n this.#session = stored;\n if (stored.accessExpiresAt > Date.now() + 30_000) {\n return { status: 'signed_in', user: stored.user };\n }\n try {\n const refreshed = await this.#refresh(stored.refreshToken);\n return { status: 'signed_in', user: refreshed.user };\n } catch (error) {\n if (error instanceof GridspawnError && !error.retryable) {\n await this.#storage.clear();\n this.#session = null;\n this.#emit({ type: 'revoked' });\n return { status: 'interaction_required', reason: error.code };\n }\n throw error;\n }\n }\n\n async requestScopes(scopes: readonly string[]): Promise<GridspawnUser> {\n const current = this.#session?.scopes ?? [];\n return this.signIn({ scopes: [...current, ...scopes] });\n }\n\n async signOut(options: { readonly everywhere?: boolean } = {}): Promise<void> {\n if (options.everywhere === true) {\n throw new GridspawnError(\n 'feature/not_available',\n 'Account-wide SDK sign-out is not available in the current backend contract.',\n );\n }\n const session = this.#session ?? await this.#storage.load();\n this.#session = null;\n await this.#storage.clear();\n this.#emit({ type: 'signed_out' });\n if (session === null) return;\n const endpoint = new URL(`${this.#oauthBaseUrl}/revoke`);\n endpoint.search = new URLSearchParams({\n client_id: this.#appId,\n environment: this.#environment,\n }).toString();\n await requestVoid(this.#fetcher, endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ token: session.refreshToken, client_id: this.#appId }),\n });\n }\n\n onSessionChanged(listener: (event: AuthSessionEvent) => void): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n async createPlayerAssertion(options: PlayerAssertionOptions): Promise<string> {\n if (!validBindingChallenge(options.challenge)) {\n throw configurationError(\n 'auth/invalid_binding_challenge',\n 'A 32\u2013256 character transport-safe binding challenge is required.',\n );\n }\n const accessToken = await this.#validAccessToken();\n const endpoint = new URL(`${this.#oauthBaseUrl.replace(/\\/oauth$/u, '')}/v1/auth/player-assertions`);\n endpoint.search = new URLSearchParams({\n client_id: this.#appId,\n environment: this.#environment,\n }).toString();\n const response = await requestJson<AssertionResponse>(this.#fetcher, endpoint, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(options),\n });\n if (typeof response.playerAssertion !== 'string' || response.playerAssertion.length === 0) {\n throw new GridspawnError('protocol/invalid_response', 'Gridspawn returned an invalid assertion.');\n }\n return response.playerAssertion;\n }\n\n async #validAccessToken(): Promise<string> {\n const session = this.#session ?? await this.#storage.load();\n if (session === null || !validStorageRecord(session)) {\n throw new GridspawnError('auth/sign_in_required', 'A Gridspawn account sign-in is required.');\n }\n this.#session = session;\n if (session.accessExpiresAt > Date.now() + 30_000) return session.accessToken;\n return (await this.#refresh(session.refreshToken)).accessToken;\n }\n\n async #refresh(refreshToken: string): Promise<TokenStorageRecord> {\n const token = await this.#tokenRequest(new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: this.#appId,\n refresh_token: refreshToken,\n }));\n const session = tokenRecord(token);\n await this.#storage.save(session);\n this.#session = session;\n this.#emit({ type: 'refreshed', user: session.user });\n return session;\n }\n\n async #tokenRequest(body: URLSearchParams): Promise<TokenResponse> {\n const endpoint = new URL(`${this.#oauthBaseUrl}/token`);\n endpoint.search = new URLSearchParams({\n client_id: this.#appId,\n environment: this.#environment,\n }).toString();\n return requestJson<TokenResponse>(this.#fetcher, endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body,\n });\n }\n\n #emit(event: AuthSessionEvent): void {\n for (const listener of this.#listeners) {\n try {\n listener(event);\n } catch {}\n }\n }\n}\n\nfunction tokenRecord(token: TokenResponse): TokenStorageRecord {\n if (\n token.token_type !== 'Bearer'\n || typeof token.access_token !== 'string'\n || typeof token.refresh_token !== 'string'\n || !Number.isFinite(token.expires_in)\n || token.expires_in <= 0\n || typeof token.user?.subject !== 'string'\n || typeof token.user.displayName !== 'string'\n ) {\n throw new GridspawnError('protocol/invalid_response', 'Gridspawn returned an invalid token response.');\n }\n const user: GridspawnUser = {\n subject: token.user.subject,\n displayName: token.user.displayName,\n ...(token.user.avatarObjectPath === undefined\n ? {}\n : { avatarObjectPath: token.user.avatarObjectPath }),\n };\n return {\n accessToken: token.access_token,\n refreshToken: token.refresh_token,\n accessExpiresAt: Date.now() + token.expires_in * 1000,\n scopes: normalizeScopes(token.scope.split(' ')),\n user,\n };\n}\n\nfunction normalizeScopes(scopes: readonly string[]): string[] {\n const result = [...new Set(scopes.map((scope) => scope.trim()).filter(Boolean))].sort();\n if (\n result.length === 0\n || result.length > 32\n || result.some((scope) => scope.length > 128 || !/^[A-Za-z0-9.\\-_:]+$/u.test(scope))\n ) {\n throw configurationError('auth/invalid_scope', 'One or more requested Gridspawn scopes are invalid.');\n }\n return result;\n}\n\nfunction validBindingChallenge(value: string): boolean {\n return value.length >= 32 && value.length <= 256 && /^[A-Za-z0-9._~-]+$/u.test(value);\n}\n\nfunction validStorageRecord(value: TokenStorageRecord): boolean {\n return typeof value.accessToken === 'string'\n && value.accessToken.length > 0\n && typeof value.refreshToken === 'string'\n && value.refreshToken.length > 0\n && Number.isFinite(value.accessExpiresAt)\n && Array.isArray(value.scopes)\n && typeof value.user?.subject === 'string'\n && typeof value.user.displayName === 'string';\n}\n\nfunction callbackMatchesRedirect(callback: URL, redirect: URL): boolean {\n if (callback.origin !== redirect.origin || callback.pathname !== redirect.pathname) return false;\n for (const [key, value] of redirect.searchParams) {\n if (callback.searchParams.get(key) !== value) return false;\n }\n return callback.hash === redirect.hash;\n}\n", "import { GridspawnError, configurationError } from './errors.js';\nimport type { AuthorizationDriver, AuthorizationRequest } from './types.js';\n\nconst CALLBACK_MESSAGE = 'gridspawn.oauth.callback';\n\nexport interface BrowserPopupAuthorizationOptions {\n readonly timeoutMs?: number;\n readonly windowFeatures?: string;\n}\n\nexport class BrowserPopupAuthorizationDriver implements AuthorizationDriver {\n readonly #timeoutMs: number;\n readonly #windowFeatures: string;\n\n constructor(options: BrowserPopupAuthorizationOptions = {}) {\n this.#timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;\n this.#windowFeatures = options.windowFeatures ?? 'popup=yes,width=540,height=760';\n }\n\n authorize(request: AuthorizationRequest): Promise<string> {\n if (typeof window === 'undefined') {\n throw new GridspawnError(\n 'platform/browser_required',\n 'Browser popup authorization requires a browser window.',\n );\n }\n if (new URL(request.redirectUri).origin !== window.location.origin) {\n throw new GridspawnError(\n 'auth/popup_redirect_origin_invalid',\n 'Popup authorization requires a callback on the game page origin.',\n );\n }\n const popup = window.open(request.authorizationUrl, 'gridspawn_authorize', this.#windowFeatures);\n if (popup === null) {\n throw new GridspawnError('auth/popup_blocked', 'The Gridspawn authorization popup was blocked.');\n }\n const callbackOrigin = new URL(request.redirectUri).origin;\n return new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => finish(() => reject(new GridspawnError(\n 'auth/authorization_timeout',\n 'Gridspawn authorization did not finish before the timeout.',\n ))), this.#timeoutMs);\n const onMessage = (event: MessageEvent<unknown>) => {\n const data = event.data;\n if (event.origin !== callbackOrigin || event.source !== popup || !isCallbackMessage(data)) {\n return;\n }\n finish(() => resolve(data.url));\n };\n const finish = (complete: () => void) => {\n window.clearTimeout(timeout);\n window.removeEventListener('message', onMessage);\n if (!popup.closed) popup.close();\n complete();\n };\n window.addEventListener('message', onMessage);\n });\n }\n}\n\nexport function completeAuthorizationPopup(callbackUrl = globalThis.location?.href): boolean {\n if (typeof window === 'undefined' || window.opener === null || callbackUrl === undefined) {\n return false;\n }\n window.opener.postMessage({ type: CALLBACK_MESSAGE, url: callbackUrl }, window.location.origin);\n window.close();\n return true;\n}\n\nexport interface ExternalAuthorizationOptions {\n /**\n * Opens the Gridspawn authorization page outside this page. In Electron the\n * renderer asks its main process over the app's own IPC, which calls\n * `shell.openExternal(url)` or loads the URL in a BrowserWindow.\n */\n readonly open: (authorizationUrl: string) => void | Promise<void>;\n /** How long a sign-in waits for its callback. Default: 10 minutes. */\n readonly timeoutMs?: number;\n}\n\ninterface PendingAuthorization {\n readonly state: string;\n readonly resolve: (callbackUrl: string) => void;\n readonly reject: (error: GridspawnError) => void;\n readonly timeout: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Sign-in for an app that receives the OAuth callback outside the page, such\n * as an Electron game. `open` shows the authorization page; when the app gets\n * the callback URL (a reverse-domain scheme such as `com.studio.game:/oauth`\n * caught by the operating system or a BrowserWindow redirect, or a loopback\n * URL), it passes it to `completeAuthorization`. PKCE, state and the redirect\n * check are the ones every sign-in uses (`AuthClient.signIn`). One sign-in is\n * pending at a time: a new one replaces one that never finished.\n */\nexport class ExternalAuthorizationDriver implements AuthorizationDriver {\n readonly #open: (authorizationUrl: string) => void | Promise<void>;\n readonly #timeoutMs: number;\n #pending: PendingAuthorization | null = null;\n\n constructor(options: ExternalAuthorizationOptions) {\n if (typeof options?.open !== 'function') {\n throw configurationError(\n 'auth/authorization_opener_required',\n 'External authorization requires an open(url) function.',\n );\n }\n this.#open = options.open;\n this.#timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;\n }\n\n /** Whether a sign-in is waiting for its callback. */\n get pending(): boolean {\n return this.#pending !== null;\n }\n\n authorize(request: AuthorizationRequest): Promise<string> {\n this.#settle(null, new GridspawnError(\n 'auth/authorization_superseded',\n 'A newer Gridspawn sign-in replaced this one.',\n ));\n const result = new Promise<string>((resolve, reject) => {\n const timeout = setTimeout(() => this.#settle(null, new GridspawnError(\n 'auth/authorization_timeout',\n 'Gridspawn authorization did not finish before the timeout.',\n )), this.#timeoutMs);\n this.#pending = { state: request.state, resolve, reject, timeout };\n });\n const pending = this.#pending;\n Promise.resolve()\n .then(() => this.#open(request.authorizationUrl))\n .catch((cause: unknown) => {\n if (this.#pending !== pending) return;\n this.#settle(null, new GridspawnError(\n 'auth/authorization_open_failed',\n 'The Gridspawn authorization page could not be opened.',\n { cause },\n ));\n });\n return result;\n }\n\n /**\n * Hands over the callback URL the app received. True when it belonged to\n * the pending sign-in (its `state` matches), which then continues; false\n * for no pending sign-in, an unreadable URL or another sign-in's callback,\n * which is ignored.\n */\n completeAuthorization(callbackUrl: string | URL): boolean {\n const pending = this.#pending;\n if (pending === null) return false;\n let callback: URL;\n try {\n callback = new URL(String(callbackUrl));\n } catch {\n return false;\n }\n if (callback.searchParams.get('state') !== pending.state) return false;\n this.#settle(callback.href, null);\n return true;\n }\n\n /** Ends the pending sign-in, for example when the user closed its window. */\n cancelAuthorization(): boolean {\n if (this.#pending === null) return false;\n this.#settle(null, new GridspawnError(\n 'auth/authorization_cancelled',\n 'Gridspawn authorization was cancelled.',\n ));\n return true;\n }\n\n #settle(callbackUrl: string | null, error: GridspawnError | null): void {\n const pending = this.#pending;\n if (pending === null) return;\n this.#pending = null;\n clearTimeout(pending.timeout);\n if (callbackUrl !== null) {\n pending.resolve(callbackUrl);\n } else if (error !== null) {\n pending.reject(error);\n }\n }\n}\n\nfunction isCallbackMessage(value: unknown): value is { readonly type: string; readonly url: string } {\n if (typeof value !== 'object' || value === null) return false;\n const record = value as Record<string, unknown>;\n return record.type === CALLBACK_MESSAGE && typeof record.url === 'string';\n}\n", "import { GridspawnError } from './errors.js';\nimport type { AttachedGameSession } from './types.js';\n\nexport interface VoiceAdmissionRequest {\n readonly session: AttachedGameSession;\n /** `match`, or a room the game server configured (`^[a-z][a-z0-9_-]{0,31}$`). */\n readonly room: string;\n readonly endpointId?: string;\n}\n\nexport interface VoiceAdmission {\n readonly sessionId: string;\n readonly participant: {\n readonly participantId: string;\n readonly identityKind: 'gridspawn_user' | 'server_verified_guest';\n readonly displayName?: string;\n };\n readonly endpointId: string;\n readonly room: {\n readonly name: string;\n readonly roomId: string;\n };\n /**\n * The server's time when it answered (Unix seconds, from the `Date`\n * header), when this runtime can read it. Browsers cannot across origins.\n * With it, `sfu.expiresAt - serverTime` is the token's lifetime measured on\n * the server's clock; the local clock is never compared with server times.\n */\n readonly serverTime?: number;\n readonly admissionExpiresAt: number;\n readonly sfu: {\n readonly url: string;\n readonly nodeId: string;\n readonly roomId: string;\n readonly token: string;\n readonly expiresAt: number;\n readonly limits: {\n readonly audioMaxBps: number;\n readonly videoMaxBps: number | null;\n readonly maxIncomingBps: number;\n };\n };\n}\n\nexport interface GridspawnModuleHost {\n admitVoice(request: VoiceAdmissionRequest): Promise<VoiceAdmission>;\n onShutdown(callback: () => Promise<void>): () => void;\n}\n\nconst hosts = new WeakMap<object, GridspawnModuleHost>();\n\nexport function registerModuleHost(client: object, host: GridspawnModuleHost): void {\n hosts.set(client, host);\n}\n\nexport function getModuleHost(client: object): GridspawnModuleHost {\n const host = hosts.get(client);\n if (host === undefined) {\n throw new GridspawnError(\n 'core/module_host_unavailable',\n 'This Gridspawn client cannot host optional SDK modules.',\n );\n }\n return host;\n}\n", "import { GridspawnError } from './errors.js';\nimport { requestJson } from './http.js';\nimport type {\n AttachSessionOptions,\n AttachedGameSession,\n GridspawnEnvironment,\n GridspawnModule,\n IdentityKind,\n ModuleGrant,\n} from './types.js';\nimport type { VoiceAdmission } from './module-host.js';\n\ninterface SessionsClientOptions {\n readonly appId: string;\n readonly environment: GridspawnEnvironment;\n readonly apiBaseUrl: string;\n readonly fetcher: typeof globalThis.fetch;\n}\n\ninterface AttachResponse {\n readonly sessionId: string;\n readonly participant: {\n readonly participantId: string;\n readonly identityKind: string;\n readonly subject: string;\n readonly displayName?: string;\n };\n readonly modules: string[];\n readonly grants: Record<string, {\n readonly accessToken: string;\n readonly tokenType: string;\n readonly expiresIn: number;\n readonly scope: string;\n }>;\n}\n\ninterface AttachedState {\n readonly session: AttachedGameSession;\n readonly grants: Map<GridspawnModule, StoredModuleGrant>;\n}\n\ninterface StoredModuleGrant extends ModuleGrant {\n readonly expiresAt: number;\n}\n\ninterface VoiceAdmissionRequest {\n readonly room: string;\n readonly endpointId?: string;\n}\n\nexport class SessionsClient {\n readonly #appId: string;\n readonly #environment: GridspawnEnvironment;\n readonly #apiBaseUrl: string;\n readonly #fetcher: typeof globalThis.fetch;\n readonly #attached = new Map<string, AttachedState>();\n readonly #renewals = new Map<string, Promise<StoredModuleGrant>>();\n\n constructor(options: SessionsClientOptions) {\n this.#appId = options.appId;\n this.#environment = options.environment;\n this.#apiBaseUrl = options.apiBaseUrl.replace(/\\/$/u, '');\n this.#fetcher = options.fetcher;\n }\n\n get attached(): readonly AttachedGameSession[] {\n return [...this.#attached.values()].map((state) => state.session);\n }\n\n async attach(options: AttachSessionOptions): Promise<AttachedGameSession> {\n if (!/^gpt1\\.[A-Za-z0-9_-]{43}$/u.test(options.participantTicket)) {\n throw new GridspawnError(\n 'session/invalid_request',\n 'A valid Gridspawn participant ticket is required.',\n );\n }\n const endpoint = new URL(`${this.#apiBaseUrl}/sessions/attach`);\n endpoint.search = new URLSearchParams({\n appId: this.#appId,\n environment: this.#environment,\n }).toString();\n const response = await requestJson<AttachResponse>(this.#fetcher, endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ participantTicket: options.participantTicket }),\n });\n const state = parseAttachedState(response);\n this.#attached.set(state.session.id, state);\n return state.session;\n }\n\n async detach(session: AttachedGameSession): Promise<void> {\n this.#attached.delete(session.id);\n }\n\n async admitVoice(\n voiceBaseUrl: string,\n session: AttachedGameSession,\n request: VoiceAdmissionRequest,\n ): Promise<VoiceAdmission> {\n const state = this.#attached.get(session.id);\n if (\n state === undefined\n || state.session.participant.id !== session.participant.id\n || !state.session.capabilities.includes('voice')\n ) {\n throw new GridspawnError(\n 'session/not_attached',\n 'Attach a session with the Voice capability before joining Voice.',\n );\n }\n if (!/^[a-z][a-z0-9_-]{0,31}$/u.test(request.room)) {\n throw new GridspawnError('voice/invalid_room', 'Voice room names are a-z first, then a-z 0-9 _ -.');\n }\n const grant = await this.#usableGrant(state, 'voice');\n // The answer's Date, when readable: the server's own clock for the token's lifetime.\n let date: string | null = null;\n const fetcher: typeof globalThis.fetch = async (input, init) => {\n const answer = await this.#fetcher(input, init);\n date = answer.headers.get('date');\n return answer;\n };\n const response = await requestJson<VoiceAdmission>(\n fetcher,\n `${voiceBaseUrl.replace(/\\/$/u, '')}/admissions`,\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${grant.accessToken}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n room: request.room,\n ...(request.endpointId === undefined ? {} : { endpointId: request.endpointId }),\n }),\n },\n );\n const admission = parseVoiceAdmission(response, state.session, request.room);\n const serverTime = date === null ? Number.NaN : Date.parse(date) / 1000;\n return Number.isFinite(serverTime) ? { ...admission, serverTime } : admission;\n }\n\n clear(): void {\n this.#attached.clear();\n this.#renewals.clear();\n }\n\n async #usableGrant(state: AttachedState, module: GridspawnModule): Promise<StoredModuleGrant> {\n const grant = state.grants.get(module);\n if (grant === undefined) {\n throw new GridspawnError(\n 'session/capability_unavailable',\n `The attached session does not grant ${module}.`,\n );\n }\n if (grant.expiresAt > Date.now() + 60_000) return grant;\n const renewalKey = `${state.session.id}:${module}`;\n const active = this.#renewals.get(renewalKey);\n if (active !== undefined) return active;\n const renewal = this.#renewGrant(state, module, grant).finally(() => {\n this.#renewals.delete(renewalKey);\n });\n this.#renewals.set(renewalKey, renewal);\n return renewal;\n }\n\n async #renewGrant(\n state: AttachedState,\n module: GridspawnModule,\n current: StoredModuleGrant,\n ): Promise<StoredModuleGrant> {\n const endpoint = new URL(\n `${this.#apiBaseUrl}/sessions/${encodeURIComponent(state.session.id)}/grants/${module}/renew`,\n );\n endpoint.search = new URLSearchParams({\n appId: this.#appId,\n environment: this.#environment,\n }).toString();\n const response = await requestJson<AttachResponse['grants'][string]>(\n this.#fetcher,\n endpoint,\n {\n method: 'POST',\n headers: { Authorization: `Bearer ${current.accessToken}` },\n },\n );\n const renewed = parseModuleGrant(response);\n state.grants.set(module, renewed);\n return renewed;\n }\n}\n\nfunction parseAttachedState(response: AttachResponse): AttachedState {\n if (\n typeof response.sessionId !== 'string'\n || typeof response.participant?.participantId !== 'string'\n || typeof response.participant.subject !== 'string'\n || !isIdentityKind(response.participant.identityKind)\n || (response.participant.displayName !== undefined\n && typeof response.participant.displayName !== 'string')\n || (response.participant.identityKind === 'server_verified_guest'\n && (response.participant.displayName === undefined\n || response.participant.displayName.length === 0))\n || !Array.isArray(response.modules)\n ) {\n throw new GridspawnError('protocol/invalid_response', 'Gridspawn returned an invalid session.');\n }\n const grants = new Map<GridspawnModule, StoredModuleGrant>();\n for (const module of response.modules) {\n if (!isModule(module)) {\n throw new GridspawnError('protocol/invalid_response', 'Gridspawn returned an unknown module.');\n }\n const grant = response.grants?.[module];\n if (\n grant === undefined\n || grant.tokenType !== 'Bearer'\n || typeof grant.accessToken !== 'string'\n || !Number.isFinite(grant.expiresIn)\n || grant.expiresIn <= 0\n ) {\n throw new GridspawnError('protocol/invalid_response', 'Gridspawn returned an invalid module grant.');\n }\n grants.set(module, parseModuleGrant(grant));\n }\n if (grants.size === 0) {\n throw new GridspawnError('protocol/invalid_response', 'Gridspawn returned no session capabilities.');\n }\n const session: AttachedGameSession = Object.freeze({\n id: response.sessionId,\n participant: Object.freeze({\n id: response.participant.participantId,\n subject: response.participant.subject,\n identityKind: response.participant.identityKind,\n ...(response.participant.displayName === undefined\n ? {}\n : { displayName: response.participant.displayName }),\n }),\n capabilities: Object.freeze([...grants.keys()]),\n get grantExpiresAt() {\n return new Date(Math.min(...[...grants.values()].map((grant) => grant.expiresAt)));\n },\n });\n return { session, grants };\n}\n\nfunction parseModuleGrant(grant: AttachResponse['grants'][string]): StoredModuleGrant {\n if (\n grant.tokenType !== 'Bearer'\n || typeof grant.accessToken !== 'string'\n || !Number.isFinite(grant.expiresIn)\n || grant.expiresIn <= 0\n || typeof grant.scope !== 'string'\n ) {\n throw new GridspawnError('protocol/invalid_response', 'Gridspawn returned an invalid module grant.');\n }\n return {\n accessToken: grant.accessToken,\n tokenType: 'Bearer',\n expiresIn: grant.expiresIn,\n scope: grant.scope,\n expiresAt: Date.now() + grant.expiresIn * 1000,\n };\n}\n\n/**\n * Checks an admission answer. Its absolute times are the server's and are not\n * compared with this machine's clock (which may be off): only their shape is\n * checked here.\n */\nfunction parseVoiceAdmission(\n response: VoiceAdmission,\n session: AttachedGameSession,\n room: string,\n): VoiceAdmission {\n if (\n response.sessionId !== session.id\n || response.participant?.participantId !== session.participant.id\n || response.participant.identityKind !== session.participant.identityKind\n || (response.participant.displayName !== undefined\n && typeof response.participant.displayName !== 'string')\n || !/^gve1\\.[a-f0-9]{32}$/u.test(response.endpointId)\n || response.room?.name !== room\n || typeof response.room.roomId !== 'string'\n || response.room.roomId.length === 0\n || !positiveNumber(response.admissionExpiresAt)\n || !validServiceUrl(response.sfu?.url)\n || !/^[A-Za-z0-9_-]{3,128}$/u.test(response.sfu.nodeId)\n || response.sfu.roomId !== response.room.roomId\n || typeof response.sfu.token !== 'string'\n || response.sfu.token.length === 0\n || !positiveNumber(response.sfu.expiresAt)\n || !positiveNumber(response.sfu.limits?.audioMaxBps)\n || !positiveNumber(response.sfu.limits?.maxIncomingBps)\n ) {\n throw new GridspawnError(\n 'protocol/invalid_response',\n 'Gridspawn returned an invalid Voice admission.',\n );\n }\n return response;\n}\n\nfunction positiveNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value) && value > 0;\n}\n\nfunction validServiceUrl(value: unknown): value is string {\n if (typeof value !== 'string') return false;\n try {\n const url = new URL(value);\n const local = url.hostname === 'localhost' || url.hostname === '127.0.0.1';\n return url.protocol === 'https:' || (local && url.protocol === 'http:');\n } catch {\n return false;\n }\n}\n\nfunction isIdentityKind(value: string): value is IdentityKind {\n return value === 'gridspawn_user' || value === 'server_verified_guest';\n}\n\nfunction isModule(value: string): value is GridspawnModule {\n return value === 'presence' || value === 'voice' || value === 'interakt';\n}\n", "import type { TokenStorage, TokenStorageRecord } from './types.js';\n\nexport class MemoryTokenStorage implements TokenStorage {\n #record: TokenStorageRecord | null = null;\n\n async load(): Promise<TokenStorageRecord | null> {\n return this.#record === null ? null : cloneRecord(this.#record);\n }\n\n async save(record: TokenStorageRecord): Promise<void> {\n this.#record = cloneRecord(record);\n }\n\n async clear(): Promise<void> {\n this.#record = null;\n }\n}\n\nfunction cloneRecord(record: TokenStorageRecord): TokenStorageRecord {\n return {\n accessToken: record.accessToken,\n refreshToken: record.refreshToken,\n accessExpiresAt: record.accessExpiresAt,\n scopes: [...record.scopes],\n user: { ...record.user },\n };\n}\n\n", "import { AuthClient } from './auth.js';\nimport { BrowserPopupAuthorizationDriver } from './authorization.js';\nimport { GridspawnError, configurationError } from './errors.js';\nimport { requestJson } from './http.js';\nimport { registerModuleHost } from './module-host.js';\nimport { SessionsClient } from './sessions.js';\nimport { MemoryTokenStorage } from './storage.js';\nimport type {\n BootstrapConfiguration,\n CoreLifecycleState,\n DiagnosticEvent,\n GridspawnCoreOptions,\n GridspawnEnvironment,\n GridspawnModule,\n} from './types.js';\n\nconst SDK_VERSION = '0.2.0';\nconst PROTOCOL_VERSION = 1;\n\ninterface BootstrapResponse extends BootstrapConfiguration {\n readonly ok: boolean;\n}\n\nexport class GridspawnClient {\n readonly appId: string;\n readonly environment: GridspawnEnvironment;\n readonly configuration: BootstrapConfiguration;\n readonly auth: AuthClient;\n readonly sessions: SessionsClient;\n readonly #moduleShutdown = new Set<() => Promise<void>>();\n #lifecycle: CoreLifecycleState = 'ready';\n\n constructor(\n options: GridspawnCoreOptions,\n configuration: BootstrapConfiguration,\n fetcher: typeof globalThis.fetch,\n ) {\n this.appId = options.appId;\n this.environment = options.environment;\n this.configuration = configuration;\n const authorizationDriver = options.authorizationDriver\n ?? (options.redirectUri !== undefined && typeof window !== 'undefined'\n ? new BrowserPopupAuthorizationDriver()\n : undefined);\n this.auth = new AuthClient({\n appId: options.appId,\n environment: options.environment,\n oauthBaseUrl: configuration.endpoints.oauth,\n fetcher,\n storage: options.tokenStorage ?? new MemoryTokenStorage(),\n ...(authorizationDriver === undefined ? {} : { authorizationDriver }),\n ...(options.redirectUri === undefined ? {} : { redirectUri: options.redirectUri }),\n });\n this.sessions = new SessionsClient({\n appId: options.appId,\n environment: options.environment,\n apiBaseUrl: configuration.endpoints.api,\n fetcher,\n });\n registerModuleHost(this, {\n admitVoice: (request) => this.sessions.admitVoice(\n configuration.endpoints.voice,\n request.session,\n {\n room: request.room,\n ...(request.endpointId === undefined ? {} : { endpointId: request.endpointId }),\n },\n ),\n onShutdown: (callback) => {\n this.#moduleShutdown.add(callback);\n return () => this.#moduleShutdown.delete(callback);\n },\n });\n }\n\n get lifecycleState(): CoreLifecycleState {\n return this.#lifecycle;\n }\n\n hasModule(module: GridspawnModule): boolean {\n return this.configuration.modules.includes(module);\n }\n\n async shutdown(): Promise<void> {\n if (this.#lifecycle === 'stopped') return;\n this.#lifecycle = 'shutting_down';\n await Promise.all([...this.#moduleShutdown].map((shutdown) => shutdown()));\n this.#moduleShutdown.clear();\n this.sessions.clear();\n this.#lifecycle = 'stopped';\n }\n}\n\nexport class Gridspawn {\n static async create(options: GridspawnCoreOptions): Promise<GridspawnClient> {\n validateConfiguration(options);\n const fetcher = options.fetch ?? globalThis.fetch;\n if (fetcher === undefined) {\n throw configurationError('platform/fetch_unavailable', 'A Fetch API implementation is required.');\n }\n const baseUrl = (options.baseUrl ?? 'https://sdk.gridspawn.net').replace(/\\/$/u, '');\n const endpoint = new URL(`${baseUrl}/v1/bootstrap`);\n endpoint.search = new URLSearchParams({\n appId: options.appId,\n environment: options.environment,\n protocolVersion: String(PROTOCOL_VERSION),\n sdkVersion: SDK_VERSION,\n }).toString();\n try {\n const response = await requestJson<BootstrapResponse>(fetcher, endpoint, {\n method: 'GET',\n headers: { Accept: 'application/json' },\n }, { retryIdempotent: true });\n validateBootstrap(response, options);\n return new GridspawnClient(options, response, fetcher);\n } catch (error) {\n report(options, {\n level: 'error',\n code: error instanceof GridspawnError ? error.code : 'core/bootstrap_failed',\n message: 'Gridspawn Core bootstrap failed.',\n ...(error instanceof GridspawnError && error.requestId !== undefined\n ? { requestId: error.requestId }\n : {}),\n });\n throw error;\n }\n }\n}\n\nfunction validateConfiguration(options: GridspawnCoreOptions): void {\n if (!/^[A-Za-z0-9_-]{3,128}$/u.test(options.appId)) {\n throw configurationError('config/invalid_app_id', 'A valid Gridspawn appId is required.');\n }\n if (!isEnvironment(options.environment)) {\n throw configurationError('config/invalid_environment', 'A valid Gridspawn environment is required.');\n }\n}\n\nfunction validateBootstrap(response: BootstrapResponse, options: GridspawnCoreOptions): void {\n if (\n response.ok !== true\n || response.application?.appId !== options.appId\n || response.environment !== options.environment\n || response.protocol?.selected !== PROTOCOL_VERSION\n || !Array.isArray(response.modules)\n || typeof response.endpoints?.api !== 'string'\n || typeof response.endpoints.oauth !== 'string'\n || typeof response.endpoints.voice !== 'string'\n ) {\n throw new GridspawnError('protocol/invalid_bootstrap', 'Gridspawn returned invalid bootstrap data.');\n }\n}\n\nfunction isEnvironment(value: string): value is GridspawnEnvironment {\n return value === 'development' || value === 'staging' || value === 'production';\n}\n\nfunction report(options: GridspawnCoreOptions, event: DiagnosticEvent): void {\n if (options.sdk?.logLevel === 'silent') return;\n try {\n options.sdk?.diagnostics?.(event);\n } catch {}\n}\n"],
|
|
5
|
+
"mappings": ";AAAM,IAAOA,EAAP,cAA8B,KAAK,CAC9B,KACA,OACA,UACA,UAET,YACEC,EACAC,EACAC,EAAyF,CAAA,EAAE,CAE3F,MAAMD,EAASC,EAAQ,QAAU,OAAY,OAAY,CAAE,MAAOA,EAAQ,KAAK,CAAE,EACjF,KAAK,KAAO,iBACZ,KAAK,KAAOF,EACZ,KAAK,OAASE,EAAQ,OACtB,KAAK,UAAYA,EAAQ,UACzB,KAAK,UAAYA,EAAQ,WAAa,EACxC,GAGI,SAAUC,EAAmBH,EAAcC,EAAe,CAC9D,OAAO,IAAIF,EAAeC,EAAMC,CAAO,CACzC,CCpBM,SAAUG,EAAgBC,EAAa,GAAE,CAC7C,IAAMC,EAASC,EAAa,EACtBC,EAAQ,IAAI,WAAWH,CAAU,EACvC,OAAAC,EAAO,gBAAgBE,CAAK,EACrBC,EAAiBD,CAAK,CAC/B,CAEA,eAAsBE,EAAcC,EAAgB,CAClD,IAAMC,EAAS,MAAML,EAAa,EAAG,OAAO,OAAO,UAAW,IAAI,YAAW,EAAG,OAAOI,CAAQ,CAAC,EAChG,OAAOF,EAAiB,IAAI,WAAWG,CAAM,CAAC,CAChD,CAEA,SAASH,EAAiBD,EAAiB,CACzC,IAAIK,EAAS,GACb,QAAWC,KAAQN,EAAOK,GAAU,OAAO,aAAaC,CAAI,EAC5D,OAAO,KAAKD,CAAM,EAAE,WAAW,IAAK,GAAG,EAAE,WAAW,IAAK,GAAG,EAAE,QAAQ,OAAQ,EAAE,CAClF,CAEA,SAASN,GAAa,CACpB,GAAI,CAAC,WAAW,QAAQ,iBAAmB,CAAC,WAAW,OAAO,OAC5D,MAAM,IAAIQ,EACR,8BACA,4DAA4D,EAGhE,OAAO,WAAW,MACpB,CCdA,eAAsBC,EACpBC,EACAC,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ACF,GAGF,SAASP,EAAsBd,EAA6B,CAC1D,GAAI,CAAC,0BAA0B,KAAKA,EAAQ,KAAK,EAC/C,MAAMe,EAAmB,wBAAyB,sCAAsC,EAE1F,GAAI,CAACS,EAAcxB,EAAQ,WAAW,EACpC,MAAMe,EAAmB,6BAA8B,4CAA4C,CAEvG,CAEA,SAASK,EAAkBF,EAA6BlB,EAA6B,CACnF,GACEkB,EAAS,KAAO,IACbA,EAAS,aAAa,QAAUlB,EAAQ,OACxCkB,EAAS,cAAgBlB,EAAQ,aACjCkB,EAAS,UAAU,WAAatB,GAChC,CAAC,MAAM,QAAQsB,EAAS,OAAO,GAC/B,OAAOA,EAAS,WAAW,KAAQ,UACnC,OAAOA,EAAS,UAAU,OAAU,UACpC,OAAOA,EAAS,UAAU,OAAU,SAEvC,MAAM,IAAIK,EAAe,6BAA8B,4CAA4C,CAEvG,CAEA,SAASC,EAAcC,EAAa,CAClC,OAAOA,IAAU,eAAiBA,IAAU,WAAaA,IAAU,YACrE,CAEA,SAASH,GAAOtB,EAA+B0B,EAAsB,CACnE,GAAI1B,EAAQ,KAAK,WAAa,SAC9B,GAAI,CACFA,EAAQ,KAAK,cAAc0B,CAAK,CAClC,MAAQ,CAAC,CACX",
|
|
6
|
+
"names": ["GridspawnError", "code", "message", "options", "configurationError", "randomBase64Url", "byteLength", "crypto", "requireCrypto", "bytes", "bytesToBase64Url", "pkceChallenge", "verifier", "digest", "binary", "byte", "GridspawnError", "requestJson", "fetcher", "input", "init", "policy", "maximum", "lastError", "attempt", "response", "payload", "GridspawnError", "errorPayload", "nested", "oauthCode", "requestId", "error", "resolve", "requestVoid", "AuthClient", "#appId", "#environment", "#oauthBaseUrl", "#fetcher", "#storage", "#authorizationDriver", "#redirectUri", "#listeners", "#session", "options", "driver", "redirectUri", "configurationError", "scopes", "normalizeScopes", "verifier", "randomBase64Url", "challenge", "pkceChallenge", "state", "nonce", "authorizationUrl", "callback", "callbackMatchesRedirect", "GridspawnError", "oauthError", "code", "token", "#tokenRequest", "session", "tokenRecord", "#emit", "stored", "validStorageRecord", "#refresh", "error", "current", "endpoint", "requestVoid", "listener", "validBindingChallenge", "accessToken", "#validAccessToken", "response", "requestJson", "refreshToken", "body", "event", "user", "result", "scope", "value", "redirect", "key", "CALLBACK_MESSAGE", "BrowserPopupAuthorizationDriver", "#timeoutMs", "#windowFeatures", "options", "request", "GridspawnError", "popup", "callbackOrigin", "resolve", "reject", "timeout", "finish", "onMessage", "event", "data", "isCallbackMessage", "complete", "completeAuthorizationPopup", "callbackUrl", "ExternalAuthorizationDriver", "#open", "#pending", "configurationError", "#settle", "result", "pending", "cause", "callback", "error", "value", "record", "hosts", "registerModuleHost", "client", "host", "getModuleHost", "GridspawnError", "SessionsClient", "#appId", "#environment", "#apiBaseUrl", "#fetcher", "#attached", "#renewals", "options", "state", "GridspawnError", "endpoint", "response", "requestJson", "parseAttachedState", "session", "voiceBaseUrl", "request", "grant", "#usableGrant", "date", "input", "init", "answer", "admission", "parseVoiceAdmission", "serverTime", "module", "renewalKey", "active", "renewal", "#renewGrant", "current", "renewed", "parseModuleGrant", "isIdentityKind", "grants", "isModule", "room", "positiveNumber", "validServiceUrl", "value", "url", "local", "MemoryTokenStorage", "#record", "cloneRecord", "record", "SDK_VERSION", "PROTOCOL_VERSION", "GridspawnClient", "#moduleShutdown", "#lifecycle", "options", "configuration", "fetcher", "authorizationDriver", "BrowserPopupAuthorizationDriver", "AuthClient", "MemoryTokenStorage", "SessionsClient", "registerModuleHost", "request", "callback", "module", "shutdown", "Gridspawn", "validateConfiguration", "configurationError", "baseUrl", "endpoint", "response", "requestJson", "validateBootstrap", "error", "report", "GridspawnError", "isEnvironment", "value", "event"]
|
|
7
|
+
}
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AuthSessionEvent, AuthorizationDriver, GridspawnEnvironment, GridspawnUser, PlayerAssertionOptions, RestoreSessionResult, SignInOptions, TokenStorage } from './types.js';
|
|
2
|
+
interface AuthClientOptions {
|
|
3
|
+
readonly appId: string;
|
|
4
|
+
readonly environment: GridspawnEnvironment;
|
|
5
|
+
readonly oauthBaseUrl: string;
|
|
6
|
+
readonly fetcher: typeof globalThis.fetch;
|
|
7
|
+
readonly storage: TokenStorage;
|
|
8
|
+
readonly authorizationDriver?: AuthorizationDriver;
|
|
9
|
+
readonly redirectUri?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare class AuthClient {
|
|
12
|
+
#private;
|
|
13
|
+
constructor(options: AuthClientOptions);
|
|
14
|
+
get currentUser(): GridspawnUser | null;
|
|
15
|
+
signIn(options: SignInOptions): Promise<GridspawnUser>;
|
|
16
|
+
restoreSession(): Promise<RestoreSessionResult>;
|
|
17
|
+
requestScopes(scopes: readonly string[]): Promise<GridspawnUser>;
|
|
18
|
+
signOut(options?: {
|
|
19
|
+
readonly everywhere?: boolean;
|
|
20
|
+
}): Promise<void>;
|
|
21
|
+
onSessionChanged(listener: (event: AuthSessionEvent) => void): () => void;
|
|
22
|
+
createPlayerAssertion(options: PlayerAssertionOptions): Promise<string>;
|
|
23
|
+
}
|
|
24
|
+
export {};
|
|
25
|
+
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,oBAAoB,EACpB,aAAa,EACb,sBAAsB,EACtB,oBAAoB,EACpB,aAAa,EACb,YAAY,EAEb,MAAM,YAAY,CAAC;AAEpB,UAAU,iBAAiB;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,WAAW,EAAE,oBAAoB,CAAC;IAC3C,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,OAAO,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAC1C,QAAQ,CAAC,OAAO,EA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