@lincyaw/classroom-server 0.0.0-stage → 1.0.0-rc.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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @lincyaw/classroom-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Presmium's classroom sync server: the y-websocket rooms classroom sessions sync through.
4
+
5
+ Part of [Presmium](https://github.com/Lincyaw/presmium), which turns lectures written in MyST Markdown into web pages, slides, Jupyter notebooks and narrated lectures.
6
+
7
+ ## Usage
8
+
9
+ ```sh
10
+ pnpm exec presmium-classroom-server --port 1234
11
+ ```
12
+
13
+ Documents point to it in their headmatter: `presmium: { presmium.session: { server: ws://<host>:1234 } }`. `presmium dev` and `presmium serve` also run one on their own port. Options: `--port`, `--host`, `--deck` (where archived classrooms are written). Run it on the classroom's own network: anyone with a join link can join.
14
+
15
+ ## Documentation
16
+
17
+ - [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/lecture.en.md)
18
+
19
+ ## License
20
+
21
+ Apache-2.0
package/bin/server.mjs ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { createJiti } from 'jiti'
3
+
4
+ const jiti = createJiti(import.meta.url)
5
+ const { main } = await jiti.import('../src/cli.ts')
6
+ const code = await main(process.argv.slice(2))
7
+ if (code !== undefined) process.exitCode = code
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@lincyaw/classroom-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0-rc.0",
4
+ "description": "Presmium's classroom sync server: y-websocket rooms",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Lincyaw/presmium.git",
9
+ "directory": "packages/classroom-server"
10
+ },
11
+ "homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/classroom-server#readme",
12
+ "bugs": "https://github.com/Lincyaw/presmium/issues",
13
+ "keywords": [
14
+ "presmium",
15
+ "yjs",
16
+ "classroom"
17
+ ],
18
+ "type": "module",
19
+ "engines": {
20
+ "node": ">=22.19"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "bin": {
26
+ "presmium-classroom-server": "./bin/server.mjs"
27
+ },
28
+ "exports": {
29
+ ".": "./src/index.ts"
30
+ },
31
+ "files": [
32
+ "bin",
33
+ "src"
34
+ ],
35
+ "dependencies": {
36
+ "jiti": "^2.7.0",
37
+ "lib0": "^0.2.119",
38
+ "ws": "^8.22.0",
39
+ "y-protocols": "^1.0.7",
40
+ "yjs": "^13.6.33",
41
+ "@lincyaw/kernel": "1.0.0-rc.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/ws": "^8.18.2",
45
+ "y-websocket": "^3.1.0"
46
+ },
47
+ "scripts": {
48
+ "start": "node bin/server.mjs"
49
+ }
6
50
  }
package/src/cli.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { networkInterfaces } from 'node:os'
2
+ import { parseArgs } from 'node:util'
3
+ import { errorMessage } from '@lincyaw/kernel'
4
+ import { startClassroomServer } from './index.ts'
5
+
6
+ const USAGE = `Usage: presmium-classroom-server [--port <n>] [--host <address>] [--deck <dir>]
7
+
8
+ Starts the room server that classroom sessions sync through. Decks point to it
9
+ in their frontmatter: presmium: { presmium.session: { server: ws://<host>:<port> } }
10
+ Listening on every interface, it also prints its addresses on the local network:
11
+ learners' devices reach it there, not at localhost.
12
+
13
+ --port <n> port to listen on; 0 picks a free one (default: 1234)
14
+ --host <address> address to listen on (default: every interface)
15
+ --deck <dir> deck directory: archived classrooms are written to
16
+ <dir>/.presmium/classroom/<room>.json (default: the working directory)
17
+ -h, --help show this help
18
+
19
+ Run it on the classroom's own network: anyone with a join link can join. Only
20
+ the window that created a classroom can end or archive it, open and close its
21
+ quizzes or move its learners; the others write only their own answers,
22
+ questions, votes and submissions.`
23
+
24
+ export async function main(argv: string[]): Promise<number | undefined> {
25
+ let port: number
26
+ let host: string | undefined
27
+ let deck: string | undefined
28
+ try {
29
+ const { values } = parseArgs({
30
+ args: argv,
31
+ options: { port: { type: 'string' }, host: { type: 'string' }, deck: { type: 'string' }, help: { type: 'boolean', short: 'h' } },
32
+ })
33
+ if (values.help) {
34
+ process.stdout.write(`${USAGE}\n`)
35
+ return 0
36
+ }
37
+ port = Number(values.port ?? 1234)
38
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`invalid port "${values.port}"`)
39
+ host = values.host
40
+ deck = values.deck
41
+ } catch (error) {
42
+ process.stderr.write(`presmium-classroom-server: ${errorMessage(error)}\n\n${USAGE}\n`)
43
+ return 2
44
+ }
45
+ const server = await startClassroomServer({ port, host, deck })
46
+ const network = !host || host === '0.0.0.0' || host === '::' ? lanAddresses().map(address => `network ws://${address}:${server.port}\n`) : []
47
+ process.stdout.write(`classroom server ${server.url}\n${network.join('')}archives ${server.archiveDir}\n`)
48
+ const stop = () => void server.close().then(() => process.exit(0))
49
+ process.once('SIGINT', stop)
50
+ process.once('SIGTERM', stop)
51
+ return undefined
52
+ }
53
+
54
+ function lanAddresses(): string[] {
55
+ return Object.values(networkInterfaces()).flatMap(entries => entries ?? []).filter(entry => entry.family === 'IPv4' && !entry.internal).map(entry => entry.address)
56
+ }
package/src/index.ts ADDED
@@ -0,0 +1,447 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto'
2
+ import { mkdir, writeFile } from 'node:fs/promises'
3
+ import { createServer } from 'node:http'
4
+ import type { IncomingMessage, ServerResponse } from 'node:http'
5
+ import type { AddressInfo } from 'node:net'
6
+ import { join, resolve } from 'node:path'
7
+ import { errorMessage } from '@lincyaw/kernel'
8
+ import * as decoding from 'lib0/decoding'
9
+ import * as encoding from 'lib0/encoding'
10
+ import { WebSocket, WebSocketServer } from 'ws'
11
+ import * as awarenessProtocol from 'y-protocols/awareness'
12
+ import * as syncProtocol from 'y-protocols/sync'
13
+ import * as Y from 'yjs'
14
+
15
+ const MESSAGE_SYNC = 0
16
+ const MESSAGE_AWARENESS = 1
17
+ const PING_INTERVAL = 30_000
18
+ const ROOM = /^[\w.-]{1,128}$/
19
+ export const ARCHIVED_CLOSE_CODE = 4410
20
+ export const REFUSED_CLOSE_CODE = 4403
21
+ export const ARCHIVE_DIR = '.presmium/classroom'
22
+ const MAX_MESSAGE = 1 << 20
23
+ const MAX_ENTRY = 16 << 10
24
+
25
+ class Room extends Y.Doc {
26
+ readonly conns = new Map<WebSocket, Set<number>>()
27
+ readonly writers = new Map<WebSocket, string>()
28
+ readonly authors = new Map<number, string>()
29
+ readonly awareness?: awarenessProtocol.Awareness
30
+ archived = false
31
+ claim?: Buffer
32
+ readonly participants = new Map<string, Buffer>()
33
+ readonly personal: boolean
34
+
35
+ constructor(name: string) {
36
+ super({ gc: true })
37
+ this.authors.set(this.clientID, '')
38
+ this.personal = name.includes('.')
39
+ this.on('update', (update: Uint8Array) => {
40
+ const encoder = encoding.createEncoder()
41
+ encoding.writeVarUint(encoder, MESSAGE_SYNC)
42
+ syncProtocol.writeUpdate(encoder, update)
43
+ this.broadcast(encoding.toUint8Array(encoder))
44
+ })
45
+ if (this.personal) return
46
+ const awareness = this.awareness = new awarenessProtocol.Awareness(this)
47
+ awareness.setLocalState(null)
48
+ awareness.on('update', ({ added, updated, removed }: Record<'added' | 'updated' | 'removed', number[]>, conn: WebSocket | null) => {
49
+ const changed = [...added, ...updated, ...removed]
50
+ const controlled = conn && this.conns.get(conn)
51
+ if (controlled) {
52
+ added.forEach(id => controlled.add(id))
53
+ removed.forEach(id => controlled.delete(id))
54
+ const writer = this.writers.get(conn)!
55
+ for (const id of added) if (!this.authors.has(id)) this.authors.set(id, writer)
56
+ }
57
+ this.broadcast(awarenessMessage(awareness, changed))
58
+ })
59
+ }
60
+
61
+ get session(): Y.Map<unknown> {
62
+ return this.getMap('session')
63
+ }
64
+
65
+ get ended(): boolean {
66
+ return this.session.get('status') === 'ended'
67
+ }
68
+
69
+ broadcast(message: Uint8Array): void {
70
+ for (const conn of this.conns.keys()) send(conn, message)
71
+ }
72
+
73
+ content(): Record<string, unknown> {
74
+ return Object.fromEntries([...this.share.keys()].map(key => [key, this.getMap(key).toJSON()]))
75
+ }
76
+
77
+ override destroy(): void {
78
+ this.awareness?.destroy()
79
+ super.destroy()
80
+ }
81
+ }
82
+
83
+ function awarenessMessage(awareness: awarenessProtocol.Awareness, clients: number[]): Uint8Array {
84
+ const encoder = encoding.createEncoder()
85
+ encoding.writeVarUint(encoder, MESSAGE_AWARENESS)
86
+ encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(awareness, clients))
87
+ return encoding.toUint8Array(encoder)
88
+ }
89
+
90
+ function send(conn: WebSocket, message: Uint8Array): void {
91
+ if (conn.readyState !== WebSocket.OPEN) return
92
+ conn.send(message, error => error && conn.close())
93
+ }
94
+
95
+ function roomName(url = '/'): string | undefined {
96
+ const name = url.slice(1).split('?')[0]!
97
+ return ROOM.test(name) ? name : undefined
98
+ }
99
+
100
+ function paramsOf(url = '/'): URLSearchParams {
101
+ return new URL(url, 'http://classroom').searchParams
102
+ }
103
+
104
+ function digest(key: string): Buffer {
105
+ return createHash('sha256').update(key).digest()
106
+ }
107
+
108
+ function sameKey(known: Buffer | undefined, key: string | null): boolean {
109
+ return Boolean(known && key && timingSafeEqual(known, digest(key)))
110
+ }
111
+
112
+ function readBody(request: IncomingMessage, limit = 1024): Promise<string> {
113
+ return new Promise((resolve, reject) => {
114
+ let text = ''
115
+ request.setEncoding('utf8')
116
+ request.on('data', (chunk: string) => {
117
+ text += chunk
118
+ if (text.length > limit) request.destroy(new Error('request too large'))
119
+ })
120
+ request.on('end', () => resolve(text))
121
+ request.on('error', reject)
122
+ })
123
+ }
124
+
125
+ export interface ClassroomWriter {
126
+ presenter: boolean
127
+ participant?: string
128
+ }
129
+
130
+ function writerKey(writer: ClassroomWriter): string {
131
+ return writer.presenter ? 'presenter' : `participant:${writer.participant ?? ''}`
132
+ }
133
+
134
+ function structClients(update: Uint8Array): number[] {
135
+ return [...Y.parseUpdateMeta(update).from.keys()]
136
+ }
137
+
138
+ const PARTICIPANT_FIRST = new Set(['store:questions'])
139
+
140
+ function ownKey(name: string, key: string, participant: string): boolean {
141
+ return PARTICIPANT_FIRST.has(name) ? key.slice(0, key.indexOf(':')) === participant : key.slice(key.lastIndexOf(':') + 1) === participant
142
+ }
143
+
144
+ function names(value: unknown, participant: string): boolean {
145
+ const entry = value as { participant?: unknown, author?: unknown } | null
146
+ return typeof entry === 'object' && entry !== null && !(entry instanceof Y.AbstractType) && (entry.participant === participant || entry.author === participant)
147
+ }
148
+
149
+ function entryRefusal(name: string, key: string | null, before: unknown, value: unknown, participant: string | undefined): string | undefined {
150
+ if (!participant) return 'a write from a connection that proved no participant'
151
+ if (key === null || !name.startsWith('store:') || name === 'store:quizzes') return `a write to ${name}, which is the presenter's`
152
+ if (!key.includes(':') || !ownKey(name, key, participant)) return `a write to ${name} under another participant's key`
153
+ if (before !== undefined && !names(before, participant)) return `a change to another participant's entry in ${name}`
154
+ if (value === undefined) return undefined
155
+ if (!names(value, participant)) return `a value in ${name} that does not name its participant`
156
+ return JSON.stringify(value).length > MAX_ENTRY ? `a value in ${name} over ${MAX_ENTRY} bytes` : undefined
157
+ }
158
+
159
+ function entryBefore(room: Y.Doc, name: string, key: string | null): unknown {
160
+ if (key === null || !room.share.has(name)) return undefined
161
+ try {
162
+ return room.getMap(name).get(key)
163
+ } catch {
164
+ return undefined
165
+ }
166
+ }
167
+
168
+ function pending(doc: Y.Doc): [structs: Uint8Array, deletions: Uint8Array] {
169
+ return [doc.store.pendingStructs?.update ?? new Uint8Array(), doc.store.pendingDs ?? new Uint8Array()]
170
+ }
171
+
172
+ function refusal(room: Room, update: Uint8Array, writer: ClassroomWriter): string | undefined {
173
+ const own = writerKey(writer)
174
+ if (structClients(update).some(client => (room.authors.get(client) ?? own) !== own)) return 'an update in the name of another writer\'s client'
175
+ const probe = new Y.Doc()
176
+ Y.applyUpdate(probe, Y.encodeStateAsUpdate(room))
177
+ const before = pending(probe)
178
+ const changes: [type: unknown, keys: Set<string | null>][] = []
179
+ probe.on('afterTransaction', (transaction: Y.Transaction) => changes.push(...transaction.changed))
180
+ Y.applyUpdate(probe, update)
181
+ const after = pending(probe)
182
+ let refused = before.every((bytes, i) => Buffer.compare(bytes, after[i]!) === 0) ? undefined : 'an update that does not integrate into the room'
183
+ for (const [type, keys] of changes) {
184
+ const name = [...probe.share].find(([, shared]) => shared === type)?.[0]
185
+ for (const key of keys) {
186
+ refused ??= name === undefined ? 'a change inside a nested type' : entryRefusal(name, key, entryBefore(room, name, key), key === null ? undefined : probe.getMap(name).get(key), writer.participant)
187
+ }
188
+ }
189
+ probe.destroy()
190
+ return refused
191
+ }
192
+
193
+ function changes(update: Uint8Array): boolean {
194
+ const { structs, ds } = Y.decodeUpdate(update)
195
+ return structs.length > 0 || ds.clients.size > 0
196
+ }
197
+
198
+ function ownAwareness(room: Room, awareness: awarenessProtocol.Awareness, conn: WebSocket, update: Uint8Array, writer: ClassroomWriter): { update: Uint8Array, dropped: number } {
199
+ const decoder = decoding.createDecoder(update)
200
+ const kept: [client: number, clock: number, state: string][] = []
201
+ let dropped = 0
202
+ const count = decoding.readVarUint(decoder)
203
+ for (let i = 0; i < count; i++) {
204
+ const entry: [number, number, string] = [decoding.readVarUint(decoder), decoding.readVarUint(decoder), decoding.readVarString(decoder)]
205
+ const [client, clock, state] = entry
206
+ const known = awareness.meta.get(client)?.clock ?? -1
207
+ if (clock < known || (clock === known && !(state === 'null' && awareness.getStates().has(client)))) continue
208
+ if (ownClient(room, conn, client, writer) && ownState(state, writer)) kept.push(entry)
209
+ else dropped++
210
+ }
211
+ const encoder = encoding.createEncoder()
212
+ encoding.writeVarUint(encoder, kept.length)
213
+ for (const [client, clock, state] of kept) {
214
+ encoding.writeVarUint(encoder, client)
215
+ encoding.writeVarUint(encoder, clock)
216
+ encoding.writeVarString(encoder, state)
217
+ }
218
+ return { update: encoding.toUint8Array(encoder), dropped }
219
+ }
220
+
221
+ function ownClient(room: Room, conn: WebSocket, client: number, writer: ClassroomWriter): boolean {
222
+ const own = writerKey(writer)
223
+ return (room.authors.get(client) ?? own) === own && ![...room.conns].some(([other, clients]) => other !== conn && clients.has(client))
224
+ }
225
+
226
+ function ownState(json: string, writer: ClassroomWriter): boolean {
227
+ if (writer.presenter) return true
228
+ try {
229
+ const participant = (JSON.parse(json) as { participant?: { id?: unknown, role?: unknown } | null } | null)?.participant
230
+ return participant == null || (writer.participant !== undefined && participant.id === writer.participant && participant.role === 'learner')
231
+ } catch {
232
+ return false
233
+ }
234
+ }
235
+
236
+ function handle(room: Room, conn: WebSocket, data: Uint8Array, writer: ClassroomWriter, drop: (reason: string) => void): void {
237
+ const decoder = decoding.createDecoder(data)
238
+ const type = decoding.readVarUint(decoder)
239
+ if (type === MESSAGE_SYNC) {
240
+ if (decoding.peekVarUint(decoder) !== syncProtocol.messageYjsSyncStep1) {
241
+ const message = decoding.clone(decoder)
242
+ decoding.readVarUint(message)
243
+ const update = decoding.readVarUint8Array(message)
244
+ if (room.ended) {
245
+ if (changes(update)) drop('an update after the classroom ended')
246
+ return
247
+ }
248
+ const refused = writer.presenter || room.personal ? undefined : refusal(room, update, writer)
249
+ if (refused) {
250
+ drop(refused)
251
+ conn.close(REFUSED_CLOSE_CODE, 'update refused')
252
+ return
253
+ }
254
+ const key = writerKey(writer)
255
+ for (const client of structClients(update)) if (!room.authors.has(client)) room.authors.set(client, key)
256
+ }
257
+ const encoder = encoding.createEncoder()
258
+ encoding.writeVarUint(encoder, MESSAGE_SYNC)
259
+ syncProtocol.readSyncMessage(decoder, encoder, room, conn)
260
+ if (encoding.length(encoder) > 1) send(conn, encoding.toUint8Array(encoder))
261
+ } else if (type === MESSAGE_AWARENESS && room.awareness) {
262
+ const own = ownAwareness(room, room.awareness, conn, decoding.readVarUint8Array(decoder), writer)
263
+ if (own.dropped > 0) drop(`${own.dropped} awareness state(s) of other clients or participants`)
264
+ awarenessProtocol.applyAwarenessUpdate(room.awareness, own.update, conn)
265
+ }
266
+ }
267
+
268
+ function reply(response: ServerResponse, status: number, body: Record<string, unknown>): void {
269
+ response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' })
270
+ response.end(`${JSON.stringify(body)}\n`)
271
+ }
272
+
273
+ export interface ClassroomServerOptions {
274
+ port?: number
275
+ host?: string
276
+ deck?: string
277
+ onDropped?(room: string, writer: ClassroomWriter, reason: string): void
278
+ }
279
+
280
+ export interface ClassroomServer {
281
+ readonly port: number
282
+ readonly url: string
283
+ readonly archiveDir: string
284
+ close(): Promise<void>
285
+ }
286
+
287
+ function warnDropped(room: string, writer: ClassroomWriter, reason: string): void {
288
+ const who = writer.presenter ? 'the presenter' : writer.participant ? `participant ${writer.participant}` : 'an unidentified participant'
289
+ console.warn(`[classroom] room ${room}: dropped ${reason} from ${who}`)
290
+ }
291
+
292
+ export async function startClassroomServer(options: ClassroomServerOptions = {}): Promise<ClassroomServer> {
293
+ const rooms = new Map<string, Room>()
294
+ const archivedNames = new Set<string>()
295
+ const archiveDir = resolve(options.deck ?? '.', ARCHIVE_DIR)
296
+ const isArchived = (name: string) => [...archivedNames].some(archived => name === archived || name.startsWith(`${archived}.`))
297
+ const onDropped = options.onDropped ?? warnDropped
298
+
299
+ async function archive(name: string, key: string): Promise<{ status: number, body: Record<string, unknown> }> {
300
+ if (archivedNames.has(name)) return { status: 410, body: { error: `课堂 ${name} 已归档` } }
301
+ const room = rooms.get(name)
302
+ if (!room) return { status: 404, body: { error: `没有课堂 ${name}` } }
303
+ if (!sameKey(room.claim, key)) return { status: 403, body: { error: '只有创建课堂的主讲可以归档' } }
304
+ const now = Date.now()
305
+ room.transact(() => {
306
+ if (!room.ended) {
307
+ room.session.set('status', 'ended')
308
+ room.session.set('endedAt', now)
309
+ }
310
+ })
311
+ const file = join(ARCHIVE_DIR, `${name}.json`)
312
+ await mkdir(archiveDir, { recursive: true })
313
+ await writeFile(join(archiveDir, `${name}.json`), `${JSON.stringify({ room: name, archivedAt: new Date(now).toISOString(), document: room.content() }, null, 2)}\n`)
314
+ room.transact(() => {
315
+ room.session.set('archivedAt', now)
316
+ room.session.set('archive', file)
317
+ })
318
+ archivedNames.add(name)
319
+ for (const [key, freed] of rooms) {
320
+ if (!isArchived(key)) continue
321
+ rooms.delete(key)
322
+ freed.archived = true
323
+ if (freed.conns.size === 0) freed.destroy()
324
+ for (const conn of freed.conns.keys()) conn.close(ARCHIVED_CLOSE_CODE, 'classroom archived')
325
+ }
326
+ console.log(`[classroom] room ${name} archived to ${join(archiveDir, `${name}.json`)}`)
327
+ return { status: 200, body: { file } }
328
+ }
329
+
330
+ const http = createServer((request, response) => {
331
+ response.setHeader('Access-Control-Allow-Origin', '*')
332
+ const target = /^\/archive\/([^/?]+)(?:\?|$)/.exec(request.url ?? '')
333
+ if (request.method === 'OPTIONS') {
334
+ response.writeHead(204, { 'Access-Control-Allow-Methods': 'POST' })
335
+ response.end()
336
+ } else if (request.method === 'POST' && target && ROOM.test(target[1]!)) {
337
+ readBody(request).then(key => archive(target[1]!, key.trim())).then(
338
+ ({ status, body }) => reply(response, status, body),
339
+ (error: unknown) => {
340
+ console.error(`[classroom] room ${target[1]}: archive failed`, error)
341
+ reply(response, 500, { error: errorMessage(error) })
342
+ },
343
+ )
344
+ } else {
345
+ response.writeHead(200, { 'Content-Type': 'text/plain' })
346
+ response.end('presmium classroom server\n')
347
+ }
348
+ })
349
+ const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE })
350
+
351
+ function connect(conn: WebSocket, request: IncomingMessage): void {
352
+ conn.on('error', error => console.error('[classroom] connection error:', error.message))
353
+ const name = roomName(request.url)
354
+ if (!name) {
355
+ conn.close(1008, 'invalid room name')
356
+ return
357
+ }
358
+ if (isArchived(name)) {
359
+ conn.close(ARCHIVED_CLOSE_CODE, 'classroom archived')
360
+ return
361
+ }
362
+ let room = rooms.get(name)
363
+ if (!room) rooms.set(name, room = new Room(name))
364
+ const current = room
365
+ const params = paramsOf(request.url)
366
+ const claim = params.get('claim')
367
+ if (claim && !current.claim) current.claim = digest(claim)
368
+ const writer: ClassroomWriter = { presenter: sameKey(current.claim, claim) }
369
+ const participant = params.get('participant')
370
+ const key = params.get('key')
371
+ if (participant && key && ROOM.test(participant)) {
372
+ if (!current.participants.has(participant)) current.participants.set(participant, digest(key))
373
+ if (sameKey(current.participants.get(participant), key)) writer.participant = participant
374
+ }
375
+ current.conns.set(conn, new Set())
376
+ current.writers.set(conn, writerKey(writer))
377
+ conn.binaryType = 'arraybuffer'
378
+ conn.on('message', (data: ArrayBuffer) => {
379
+ try {
380
+ handle(current, conn, new Uint8Array(data), writer, reason => onDropped(name, writer, reason))
381
+ } catch (error) {
382
+ console.error(`[classroom] room ${name}: bad message`, error)
383
+ }
384
+ })
385
+ let alive = true
386
+ conn.on('pong', () => alive = true)
387
+ const ping = setInterval(() => {
388
+ if (!alive || conn.readyState !== WebSocket.OPEN) {
389
+ conn.terminate()
390
+ return
391
+ }
392
+ alive = false
393
+ conn.ping()
394
+ }, PING_INTERVAL)
395
+ conn.on('close', () => {
396
+ clearInterval(ping)
397
+ const controlled = current.conns.get(conn)
398
+ current.conns.delete(conn)
399
+ current.writers.delete(conn)
400
+ if (current.archived) {
401
+ if (current.conns.size === 0) current.destroy()
402
+ return
403
+ }
404
+ if (controlled?.size && current.awareness) awarenessProtocol.removeAwarenessStates(current.awareness, [...controlled], null)
405
+ if (current.conns.size === 0 && current.store.clients.size === 0 && rooms.get(name) === current) {
406
+ rooms.delete(name)
407
+ current.destroy()
408
+ }
409
+ })
410
+ const encoder = encoding.createEncoder()
411
+ encoding.writeVarUint(encoder, MESSAGE_SYNC)
412
+ syncProtocol.writeSyncStep1(encoder, current)
413
+ send(conn, encoding.toUint8Array(encoder))
414
+ const states = current.awareness ? [...current.awareness.getStates().keys()] : []
415
+ if (current.awareness && states.length > 0) send(conn, awarenessMessage(current.awareness, states))
416
+ }
417
+
418
+ wss.on('connection', (conn: WebSocket, request: IncomingMessage) => {
419
+ try {
420
+ connect(conn, request)
421
+ } catch (error) {
422
+ console.error('[classroom] connection failed', error)
423
+ conn.terminate()
424
+ }
425
+ })
426
+ http.on('upgrade', (request, socket, head) => {
427
+ wss.handleUpgrade(request, socket, head, conn => wss.emit('connection', conn, request))
428
+ })
429
+ await new Promise<void>((resolve, reject) => {
430
+ http.once('error', reject)
431
+ http.listen(options.port ?? 1234, options.host ?? '0.0.0.0', () => resolve())
432
+ })
433
+ const { port } = http.address() as AddressInfo
434
+ const shown = !options.host || options.host === '0.0.0.0' || options.host === '::' ? 'localhost' : options.host
435
+ return {
436
+ port,
437
+ url: `ws://${shown.includes(':') ? `[${shown}]` : shown}:${port}`,
438
+ archiveDir,
439
+ async close() {
440
+ for (const client of wss.clients) client.terminate()
441
+ await new Promise<void>(resolve => wss.close(() => resolve()))
442
+ await new Promise<void>(resolve => http.close(() => resolve()))
443
+ for (const room of rooms.values()) room.destroy()
444
+ rooms.clear()
445
+ },
446
+ }
447
+ }