@lincyaw/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,18 @@
1
- # Temporary Holding Version
1
+ # @lincyaw/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
+ The server of `presmium dev` and `presmium serve`: plugin routes and proxies under `/__presmium/`, approvals, the control channel and the MCP endpoint. It listens on this machine only unless `presmium serve --host` is given.
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
+ ## Install
8
+
9
+ It comes with `@lincyaw/cli`; you do not install it yourself. Its programming interface serves Presmium's own packages and is internal; plugins add routes through `PresmiumNodePlugin.server`.
10
+
11
+ ## Documentation
12
+
13
+ - [Plugin guide](https://github.com/Lincyaw/presmium/blob/main/site/plugins/lecture.en.md): server routes
14
+ - [Security and the trust model](https://github.com/Lincyaw/presmium/blob/main/SECURITY.md)
15
+
16
+ ## License
17
+
18
+ Apache-2.0
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@lincyaw/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": "The server of presmium dev and presmium serve: plugin routes and proxies, approvals, the control channel and MCP",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Lincyaw/presmium.git",
9
+ "directory": "packages/server"
10
+ },
11
+ "homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/server#readme",
12
+ "bugs": "https://github.com/Lincyaw/presmium/issues",
13
+ "keywords": [
14
+ "presmium",
15
+ "server"
16
+ ],
17
+ "type": "module",
18
+ "engines": {
19
+ "node": ">=22.19"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "exports": {
25
+ ".": "./src/index.ts"
26
+ },
27
+ "files": [
28
+ "src"
29
+ ],
30
+ "dependencies": {
31
+ "@hono/node-server": "2.1.3",
32
+ "hono": "4.13.13",
33
+ "http-proxy-3": "2.0.1",
34
+ "@lincyaw/compiler": "1.0.0-rc.0",
35
+ "@lincyaw/kernel": "1.0.0-rc.0",
36
+ "@lincyaw/mcp": "1.0.0-rc.0"
37
+ },
38
+ "devDependencies": {
39
+ "@modelcontextprotocol/client": "2.3.1"
40
+ }
6
41
  }
package/src/auth.ts ADDED
@@ -0,0 +1,40 @@
1
+ import type { IncomingMessage } from 'node:http'
2
+ import { hostname as machineName, networkInterfaces } from 'node:os'
3
+ import type { Member } from '@lincyaw/kernel'
4
+ import { header, hostname, isLoopback, originHost } from './http.ts'
5
+
6
+ export const LOCAL_AUTHOR: Member = { id: 'local', name: 'local author', roles: ['owner'] }
7
+
8
+ export interface Refusal {
9
+ status: number
10
+ message: string
11
+ }
12
+
13
+ export type MachineHosts = (host: string) => boolean
14
+
15
+ export function anyAddress(host: string): boolean {
16
+ return ['0.0.0.0', '[::]'].includes(hostname(host))
17
+ }
18
+
19
+ export function networkAddresses(): string[] {
20
+ return Object.values(networkInterfaces()).flatMap(entries => entries ?? []).filter(entry => entry.family === 'IPv4' && !entry.internal).map(entry => entry.address)
21
+ }
22
+
23
+ export function machineHosts(listen: string): MachineHosts {
24
+ const own = hostname(listen)
25
+ if (isLoopback(own)) return isLoopback
26
+ const addresses = anyAddress(own)
27
+ ? Object.values(networkInterfaces()).flatMap(entries => entries ?? []).map(entry => hostname(entry.address.replace(/%.*$/, '')))
28
+ : [own]
29
+ const name = machineName().toLowerCase()
30
+ const names = new Set([...addresses, name, `${name}.local`])
31
+ return host => isLoopback(host) || names.has(host)
32
+ }
33
+
34
+ export function authenticate(req: IncomingMessage, local: MachineHosts = isLoopback): Member | Refusal {
35
+ const host = header(req.headers, 'host')
36
+ const origin = originHost(header(req.headers, 'origin'))
37
+ if (!local(hostname(host))) return { status: 403, message: `Host ${host ?? '(none)'} is not this machine` }
38
+ if (origin !== undefined && !local(origin)) return { status: 403, message: `Origin ${header(req.headers, 'origin')} is not this machine` }
39
+ return LOCAL_AUTHOR
40
+ }
package/src/control.ts ADDED
@@ -0,0 +1,205 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import type { ApprovalKind, ApprovalRequest, Approvals, Member, MemberRole } from '@lincyaw/kernel'
3
+
4
+ export type ApprovalPolicy = 'off' | 'ask' | 'allow'
5
+
6
+ export const APPROVAL_TIMEOUT_MS = 50_000
7
+
8
+ export interface WindowPosition {
9
+ slide: number
10
+ step: number
11
+ view?: string
12
+ section?: string
13
+ trail?: string[]
14
+ }
15
+
16
+ export interface WindowReport {
17
+ position?: WindowPosition
18
+ role?: string
19
+ status?: Record<string, unknown>
20
+ at: number
21
+ }
22
+
23
+ interface Window {
24
+ id: string
25
+ member: Member
26
+ document: string
27
+ report?: WindowReport
28
+ send(event: string, data: unknown): void
29
+ close(): void
30
+ }
31
+
32
+ interface Pending {
33
+ id: string
34
+ request: ApprovalRequest
35
+ document: string
36
+ settle(allow: boolean): void
37
+ }
38
+
39
+ function presents(window: { report?: WindowReport }): boolean {
40
+ return window.report?.role === 'presenter' || window.report?.role === 'audience'
41
+ }
42
+
43
+ export function hasRole(member: Member, role: MemberRole): boolean {
44
+ const rank: Record<MemberRole, number> = { reader: 0, editor: 1, owner: 2 }
45
+ return member.roles.some(own => rank[own] >= rank[role])
46
+ }
47
+
48
+ export interface ControlOptions {
49
+ policy: Partial<Record<ApprovalKind, ApprovalPolicy>>
50
+ timeoutMs?: number
51
+ }
52
+
53
+ export class Control {
54
+ readonly #windows = new Map<string, Window>()
55
+ readonly #pending = new Map<string, Pending>()
56
+ readonly #watchers = new Set<() => void>()
57
+ readonly #options: ControlOptions
58
+
59
+ constructor(options: ControlOptions) {
60
+ this.#options = options
61
+ }
62
+
63
+ readonly approvals: Approvals = {
64
+ request: (request, signal) => this.#request(request, signal),
65
+ }
66
+
67
+ open(id: string, member: Member, document: string): AsyncIterable<{ event: string, data: unknown }> & { close(): void } {
68
+ this.#windows.get(id)?.close()
69
+ const queue: { event: string, data: unknown }[] = []
70
+ let wake: (() => void) | undefined
71
+ let closed = false
72
+ const window: Window = {
73
+ id,
74
+ member,
75
+ document,
76
+ send(event, data) {
77
+ if (closed) return
78
+ queue.push({ event, data })
79
+ wake?.()
80
+ },
81
+ close: () => {
82
+ closed = true
83
+ if (this.#windows.get(id) === window) this.#windows.delete(id)
84
+ wake?.()
85
+ },
86
+ }
87
+ this.#windows.set(id, window)
88
+ window.send('ready', { window: id })
89
+ for (const pending of this.#pending.values()) {
90
+ if (this.#eligible(member, pending.request)) window.send('approval', { id: pending.id, request: pending.request })
91
+ }
92
+ const stream = {
93
+ close: window.close,
94
+ async* [Symbol.asyncIterator]() {
95
+ try {
96
+ while (!closed) {
97
+ while (queue.length > 0) yield queue.shift()!
98
+ if (closed) break
99
+ await new Promise<void>(resolve => wake = resolve)
100
+ wake = undefined
101
+ }
102
+ } finally {
103
+ window.close()
104
+ }
105
+ },
106
+ }
107
+ return stream
108
+ }
109
+
110
+ report(id: string, member: Member, report: Omit<WindowReport, 'at'>): boolean {
111
+ const window = this.#windows.get(id)
112
+ if (!window || window.member.id !== member.id) return false
113
+ const moved = JSON.stringify(report.position) !== JSON.stringify(window.report?.position)
114
+ window.report = { ...report, at: Date.now() }
115
+ if (moved) for (const listener of [...this.#watchers]) listener()
116
+ return true
117
+ }
118
+
119
+ watch(listener: () => void): () => void {
120
+ this.#watchers.add(listener)
121
+ return () => void this.#watchers.delete(listener)
122
+ }
123
+
124
+ policy(kind: ApprovalKind): ApprovalPolicy {
125
+ return this.#options.policy[kind] ?? 'ask'
126
+ }
127
+
128
+ answer(id: string, allow: boolean, member: Member): 200 | 403 | 404 {
129
+ const pending = this.#pending.get(id)
130
+ if (!pending) return 404
131
+ if (!this.#eligible(member, pending.request)) return 403
132
+ pending.settle(allow)
133
+ return 200
134
+ }
135
+
136
+ positions(member?: Member, document?: string, viewer?: Member): { window: string, member: string, roles: MemberRole[], document: string, report: WindowReport }[] {
137
+ const all = [...this.#windows.values()].filter(w => w.report?.position && (!member || w.member.id === member.id) && (document === undefined || w.document === document))
138
+ const trusted = (w: Window) => hasRole(w.member, 'editor') || w.member.id === viewer?.id
139
+ const rank = (w: Window) => (!trusted(w) ? 2 : presents(w) ? 0 : 1)
140
+ return all.sort((a, b) => rank(a) - rank(b) || b.report!.at - a.report!.at)
141
+ .map(w => ({ window: w.id, member: w.member.id, roles: w.member.roles, document: w.document, report: w.report! }))
142
+ }
143
+
144
+ go(position: WindowPosition, member?: Member, document?: string): number {
145
+ const windows = [...this.#windows.values()].filter(w => (!member || w.member.id === member.id) && (document === undefined || w.document === document))
146
+ const presenting = windows.filter(w => w.report?.role === 'presenter' || w.report?.role === 'audience')
147
+ const targets = presenting.length > 0 ? presenting : windows
148
+ for (const window of targets) window.send('go', position)
149
+ return targets.length
150
+ }
151
+
152
+ session(action: 'start' | 'end', name?: string, document?: string, member?: Member): number {
153
+ const windows = [...this.#windows.values()].filter(w => (!member || w.member.id === member.id) && (document === undefined || w.document === document) && (w.report?.role === 'presenter' || w.report?.role === 'audience'))
154
+ for (const window of windows) window.send('session', { action, name })
155
+ return windows.length
156
+ }
157
+
158
+ status(document?: string): Record<string, unknown> {
159
+ const out: Record<string, unknown> = {}
160
+ const rank = (w: Window) => (w.report?.role === 'presenter' ? 1 : 0)
161
+ const windows = [...this.#windows.values()]
162
+ .filter(w => w.report?.status && hasRole(w.member, 'editor') && (document === undefined || w.document === document))
163
+ .sort((a, b) => rank(a) - rank(b) || a.report!.at - b.report!.at)
164
+ for (const window of windows) Object.assign(out, window.report!.status)
165
+ return out
166
+ }
167
+
168
+ close(): void {
169
+ for (const pending of [...this.#pending.values()]) pending.settle(false)
170
+ for (const window of [...this.#windows.values()]) window.close()
171
+ }
172
+
173
+ #request(request: ApprovalRequest, signal?: AbortSignal): Promise<boolean> {
174
+ const policy = this.#options.policy[request.kind] ?? 'ask'
175
+ if (policy === 'allow') return Promise.resolve(true)
176
+ if (policy === 'off' || signal?.aborted) return Promise.resolve(false)
177
+ return new Promise<boolean>((resolve) => {
178
+ const id = randomUUID()
179
+ const timer = setTimeout(() => pending.settle(false), this.#options.timeoutMs ?? APPROVAL_TIMEOUT_MS)
180
+ const onAbort = () => pending.settle(false)
181
+ const pending: Pending = {
182
+ id,
183
+ request: { ...request, scope: request.scope ?? 'workspace' },
184
+ document: '',
185
+ settle: (allow) => {
186
+ if (!this.#pending.delete(id)) return
187
+ clearTimeout(timer)
188
+ signal?.removeEventListener('abort', onAbort)
189
+ for (const window of this.#windows.values()) window.send('settled', { id, allow })
190
+ resolve(allow)
191
+ },
192
+ }
193
+ signal?.addEventListener('abort', onAbort, { once: true })
194
+ this.#pending.set(id, pending)
195
+ for (const window of this.#windows.values()) {
196
+ if (this.#eligible(window.member, pending.request)) window.send('approval', { id, request: pending.request })
197
+ }
198
+ })
199
+ }
200
+
201
+ #eligible(member: Member, request: ApprovalRequest): boolean {
202
+ if ((request.scope ?? 'workspace') === 'workspace') return hasRole(member, 'owner')
203
+ return request.member ? member.id === request.member : hasRole(member, 'editor')
204
+ }
205
+ }
package/src/focus.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { focusReport, resolveFocus } from '@lincyaw/mcp'
2
+ import type { McpFocus } from '@lincyaw/mcp'
3
+ import type { FocusReport, IRDocument } from '@lincyaw/kernel'
4
+
5
+ const MAX_FOCUS = 50
6
+
7
+ export class FocusStore {
8
+ readonly #latest = new Map<string, McpFocus>()
9
+ readonly #watchers = new Set<() => void>()
10
+
11
+ get(document?: string): McpFocus | undefined {
12
+ if (document !== undefined) return this.#latest.get(document)
13
+ let newest: McpFocus | undefined
14
+ for (const found of this.#latest.values()) if (!newest || found.at >= newest.at) newest = found
15
+ return newest
16
+ }
17
+
18
+ report(document: string, doc: IRDocument, reports: FocusReport[]): McpFocus {
19
+ const record = { document, focus: reports.map(report => resolveFocus(doc, document, report)), at: Date.now() }
20
+ this.#latest.set(document, record)
21
+ for (const watcher of this.#watchers) watcher()
22
+ return record
23
+ }
24
+
25
+ forget(document: string): void {
26
+ if (this.#latest.delete(document)) for (const watcher of this.#watchers) watcher()
27
+ }
28
+
29
+ watch(listener: () => void): () => void {
30
+ this.#watchers.add(listener)
31
+ return () => this.#watchers.delete(listener)
32
+ }
33
+ }
34
+
35
+ export function focusBody(body: unknown): { document: string, focus: FocusReport[] } | string {
36
+ if (!body || typeof body !== 'object') return 'a JSON object { document, focus: [...] }'
37
+ const { document, focus } = body as { document?: unknown, focus?: unknown }
38
+ if (typeof document !== 'string') return 'the document directory (relative to the workspace root) as `document`'
39
+ if (!Array.isArray(focus) || focus.length > MAX_FOCUS) return `focus is a list of at most ${MAX_FOCUS}`
40
+ const reports: FocusReport[] = []
41
+ for (const item of focus) {
42
+ const report = focusReport(item)
43
+ if (typeof report === 'string') return report
44
+ reports.push(report)
45
+ }
46
+ return { document, focus: reports }
47
+ }
package/src/host.ts ADDED
@@ -0,0 +1,52 @@
1
+ import type { Compilation } from '@lincyaw/compiler'
2
+ import { pluginId } from '@lincyaw/compiler'
3
+ import type { Finding, IRDocument, PresmiumNodePlugin, RunResult, ServiceToken } from '@lincyaw/kernel'
4
+
5
+ export interface ServedPlugin {
6
+ id: string
7
+ plugin: PresmiumNodePlugin
8
+ config: Record<string, unknown>
9
+ }
10
+
11
+ export interface ServedDocument {
12
+ deckDir: string
13
+ workspaceRoot: string
14
+ lang?: string
15
+ plugins: ServedPlugin[]
16
+ service<T>(token: ServiceToken<T>): T | undefined
17
+ settings?: Record<string, Record<string, unknown>>
18
+ operatorDir?: string
19
+ home?: boolean
20
+ }
21
+
22
+ export function servedDocument(compilation: Compilation): ServedDocument {
23
+ const { presmium } = compilation.doc.config
24
+ return {
25
+ deckDir: compilation.deckDir,
26
+ workspaceRoot: compilation.workspaceRoot,
27
+ lang: compilation.doc.meta.lang,
28
+ plugins: compilation.plugins.flatMap((loaded) => {
29
+ if (!loaded.plugin) return []
30
+ const config = presmium[pluginId(loaded)]
31
+ return [{ id: pluginId(loaded), plugin: loaded.plugin, config: config !== null && typeof config === 'object' && !Array.isArray(config) ? config as Record<string, unknown> : {} }]
32
+ }),
33
+ service: compilation.service,
34
+ settings: compilation.settings,
35
+ ...compilation.operatorDir ? { operatorDir: compilation.operatorDir } : {},
36
+ }
37
+ }
38
+
39
+ export interface HostDocument {
40
+ dir: string
41
+ title: string
42
+ lang?: string
43
+ tags?: string[]
44
+ }
45
+
46
+ export interface ServerHost {
47
+ documents(): Promise<HostDocument[]>
48
+ compile(document: string): Promise<{ doc: IRDocument, diagnostics: Finding[] }>
49
+ check(document: string): Promise<Finding[]>
50
+ build(document: string, options?: { to?: string[] }): Promise<{ outputs: { renderer: string, outDir: string }[], findings: Finding[] }>
51
+ run(document: string, target: { section: string, block: string }, signal?: AbortSignal): Promise<RunResult>
52
+ }
package/src/http.ts ADDED
@@ -0,0 +1,169 @@
1
+ import { createServer } from 'node:http'
2
+ import type { IncomingHttpHeaders, IncomingMessage, Server, ServerResponse } from 'node:http'
3
+ import type { AddressInfo } from 'node:net'
4
+ import type { Duplex } from 'node:stream'
5
+ import { getRequestListener } from '@hono/node-server'
6
+ import { json, problem } from '@lincyaw/kernel'
7
+ import { createProxyServer } from 'http-proxy-3'
8
+
9
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]'])
10
+
11
+ export function hostname(host: string | null | undefined): string {
12
+ if (!host) return ''
13
+ const value = host.trim().toLowerCase()
14
+ if (value.startsWith('[')) return value.slice(0, value.indexOf(']') + 1)
15
+ if (value.indexOf(':') !== value.lastIndexOf(':')) return `[${value}]`
16
+ return value.replace(/:\d+$/, '')
17
+ }
18
+
19
+ export function isLoopback(host: string | null | undefined): boolean {
20
+ return LOOPBACK.has(hostname(host))
21
+ }
22
+
23
+ export function originHost(origin: string | null | undefined): string | undefined {
24
+ if (origin === null || origin === undefined) return undefined
25
+ try {
26
+ return hostname(new URL(origin).host)
27
+ } catch {
28
+ return ''
29
+ }
30
+ }
31
+
32
+ export function bearer(value: string | null | undefined): string | undefined {
33
+ const match = /^Bearer\s+(\S+)$/i.exec(value?.trim() ?? '')
34
+ return match?.[1]
35
+ }
36
+
37
+ export { json, problem }
38
+
39
+ export async function limitBody(request: Request, limit: number): Promise<Request | Response> {
40
+ const tooLarge = () => json({ error: `the request body is larger than this route takes (${limit} bytes)` }, 413)
41
+ const declared = Number(request.headers.get('content-length') ?? Number.NaN)
42
+ if (declared > limit) return tooLarge()
43
+ if (!request.body) return request
44
+ const chunks: Uint8Array[] = []
45
+ let size = 0
46
+ const reader = request.body.getReader()
47
+ for (;;) {
48
+ const { done, value } = await reader.read()
49
+ if (done) break
50
+ size += value.byteLength
51
+ if (size > limit) {
52
+ void drop(reader)
53
+ return tooLarge()
54
+ }
55
+ chunks.push(value)
56
+ }
57
+ const body = new Uint8Array(size)
58
+ let at = 0
59
+ for (const chunk of chunks) {
60
+ body.set(chunk, at)
61
+ at += chunk.byteLength
62
+ }
63
+ return new Request(request.url, { method: request.method, headers: request.headers, body, signal: request.signal })
64
+ }
65
+
66
+ async function drop(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<void> {
67
+ try {
68
+ while (!(await reader.read()).done) {}
69
+ } catch {}
70
+ }
71
+
72
+ export function header(headers: IncomingHttpHeaders, name: string): string | undefined {
73
+ const value = headers[name.toLowerCase()]
74
+ return Array.isArray(value) ? value[0] : value
75
+ }
76
+
77
+ export async function send(res: ServerResponse, response: Response): Promise<void> {
78
+ res.writeHead(response.status, Object.fromEntries(response.headers))
79
+ res.end(Buffer.from(await response.arrayBuffer()))
80
+ }
81
+
82
+ export function refuseUpgrade(socket: Duplex, status: number): void {
83
+ socket.end(`HTTP/1.1 ${status} ${status === 401 ? 'Unauthorized' : status === 403 ? 'Forbidden' : 'Not Found'}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
84
+ }
85
+
86
+ export interface ProxyTarget {
87
+ target: string
88
+ path: string
89
+ headers?: Record<string, string>
90
+ }
91
+
92
+ export function createProxy() {
93
+ const proxy = createProxyServer({ ws: true, xfwd: false })
94
+ proxy.on('error', (error: Error, _req: unknown, res: unknown) => {
95
+ const response = res as ServerResponse | Duplex | undefined
96
+ if (response && 'writeHead' in response && !response.headersSent) {
97
+ response.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' })
98
+ response.end(`proxy error: ${error.message}`)
99
+ } else {
100
+ response?.destroy?.()
101
+ }
102
+ })
103
+ return {
104
+ web(req: IncomingMessage, res: ServerResponse, to: ProxyTarget): void {
105
+ req.url = to.path
106
+ proxy.web(req, res, { target: to.target, headers: to.headers })
107
+ },
108
+ ws(req: IncomingMessage, socket: Duplex, head: Buffer, to: ProxyTarget): void {
109
+ req.url = to.path
110
+ proxy.ws(req, socket, head, { target: to.target, headers: to.headers })
111
+ },
112
+ close: () => proxy.close(),
113
+ }
114
+ }
115
+
116
+ export type Proxy = ReturnType<typeof createProxy>
117
+
118
+ export type Decision =
119
+ | { kind: 'fetch' }
120
+ | { kind: 'proxy', to: ProxyTarget }
121
+ | { kind: 'answer', response: Response }
122
+
123
+ export function nodeServer(options: {
124
+ decide(req: IncomingMessage): Promise<Decision>
125
+ decideUpgrade(req: IncomingMessage): Promise<{ to?: ProxyTarget, status?: number }>
126
+ fetch(request: Request, req: IncomingMessage): Promise<Response>
127
+ proxy: Proxy
128
+ }): Server {
129
+ const listener = getRequestListener((request, env) => options.fetch(request, (env as { incoming: IncomingMessage }).incoming))
130
+ const server = createServer((req, res) => {
131
+ void options.decide(req).then((decision) => {
132
+ if (decision.kind === 'fetch') return listener(req, res)
133
+ if (decision.kind === 'proxy') return options.proxy.web(req, res, decision.to)
134
+ return send(res, decision.response)
135
+ }).catch((error: unknown) => {
136
+ if (!res.headersSent) res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' })
137
+ res.end(error instanceof Error ? error.message : String(error))
138
+ })
139
+ })
140
+ server.on('upgrade', (req: IncomingMessage, socket: Duplex, head: Buffer) => {
141
+ void options.decideUpgrade(req).then(({ to, status }) => {
142
+ if (to) options.proxy.ws(req, socket, head, to)
143
+ else refuseUpgrade(socket, status ?? 404)
144
+ }, () => refuseUpgrade(socket, 500))
145
+ })
146
+ return server
147
+ }
148
+
149
+ export function listen(server: Server, port: number, host: string): Promise<number> {
150
+ return new Promise((resolve, reject) => {
151
+ server.once('error', reject)
152
+ server.listen(port, host, () => {
153
+ server.off('error', reject)
154
+ resolve((server.address() as AddressInfo).port)
155
+ })
156
+ })
157
+ }
158
+
159
+ export function closeServer(server: Server): Promise<void> {
160
+ return new Promise((resolve) => {
161
+ server.close(() => resolve())
162
+ server.closeAllConnections()
163
+ })
164
+ }
165
+
166
+ export function urlHost(host: string): string {
167
+ if (host === '0.0.0.0' || host === '::') return '127.0.0.1'
168
+ return host.includes(':') && !host.startsWith('[') ? `[${host}]` : host
169
+ }
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ export { APPROVAL_TIMEOUT_MS, Control } from './control.ts'
2
+ export type { ApprovalPolicy, WindowPosition, WindowReport } from './control.ts'
3
+ export { servedDocument } from './host.ts'
4
+ export type { HostDocument, ServedDocument, ServedPlugin, ServerHost } from './host.ts'
5
+ export { anyAddress, networkAddresses } from './auth.ts'
6
+ export { bearer, isLoopback, json, limitBody, problem } from './http.ts'
7
+ export { LOCAL_AUTHOR, SERVER_PATH, startServer } from './server.ts'
8
+ export type { PresmiumServer, ServerOptions } from './server.ts'
package/src/mcp.ts ADDED
@@ -0,0 +1,64 @@
1
+ import type { AgentTool, Member, ServiceToken } from '@lincyaw/kernel'
2
+ import type { McpHost, McpPluginTools, McpPosition } from '@lincyaw/mcp'
3
+ import type { Control } from './control.ts'
4
+ import type { FocusStore } from './focus.ts'
5
+ import type { ServedDocument, ServerHost } from './host.ts'
6
+
7
+ export interface McpHostOptions {
8
+ serverHost?: ServerHost
9
+ control: Control
10
+ command: 'dev' | 'serve'
11
+ mount(document: string): Promise<ServedDocument | undefined>
12
+ mounted(): Promise<ServedDocument[]>
13
+ service<T>(token: ServiceToken<T>): T | undefined
14
+ focus: FocusStore
15
+ }
16
+
17
+ function toolsOf(documents: ServedDocument[], own: McpHostOptions['service']): McpPluginTools {
18
+ const tools = new Map<string, AgentTool>()
19
+ for (const doc of documents) {
20
+ for (const { plugin } of doc.plugins) for (const tool of plugin.tools ?? []) if (!tools.has(tool.name)) tools.set(tool.name, tool)
21
+ }
22
+ const doc = documents[0]
23
+ return { tools: [...tools.values()], service: <T>(token: ServiceToken<T>) => own(token) ?? doc?.service(token) }
24
+ }
25
+
26
+ export function serverMcpHost(options: McpHostOptions): McpHost {
27
+ const { control } = options
28
+ const host = (): ServerHost => {
29
+ if (!options.serverHost) throw new Error('this server has no host operations')
30
+ return options.serverHost
31
+ }
32
+ const position = (entry: ReturnType<Control['positions']>[number]): McpPosition => {
33
+ const { report } = entry
34
+ const { slide, step, view, section, trail } = report.position!
35
+ return { document: entry.document, member: entry.member, slide, step, view, ...section === undefined ? {} : { section }, ...trail ? { trail } : {}, role: report.role, at: report.at }
36
+ }
37
+ return {
38
+ process: { command: options.command },
39
+ documents: () => host().documents(),
40
+ compile: document => host().compile(document),
41
+ check: document => host().check(document),
42
+ build: (document, build) => host().build(document, build),
43
+ run: (document, target, signal) => host().run(document, target, signal),
44
+ approve: (request, signal) => control.approvals.request(request, signal),
45
+ offers: kind => control.policy(kind) !== 'off',
46
+ approval: kind => control.policy(kind),
47
+ async tools(document) {
48
+ if (document === undefined) return toolsOf(await options.mounted(), options.service)
49
+ const doc = await options.mount(document)
50
+ return toolsOf(doc ? [doc] : [], options.service)
51
+ },
52
+ positions(document: string | undefined, member: Member) {
53
+ const all = control.positions(undefined, document, member)
54
+ const presenting = (w: typeof all[number]) => w.member === member.id && (w.report.role === 'presenter' || w.report.role === 'audience')
55
+ return [...all.filter(presenting), ...all.filter(w => !presenting(w))].map(position)
56
+ },
57
+ watchPositions: listener => control.watch(listener),
58
+ focus: document => options.focus.get(document),
59
+ watchFocus: listener => options.focus.watch(listener),
60
+ classroom: document => control.status(document),
61
+ navigate: (document, to, member) => control.go(to, member, document),
62
+ session: (document, action, name, member) => control.session(action, name, document, member),
63
+ }
64
+ }
package/src/server.ts ADDED
@@ -0,0 +1,469 @@
1
+ import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
2
+ import { chmodSync, mkdirSync, writeFileSync } from 'node:fs'
3
+ import type { IncomingMessage } from 'node:http'
4
+ import { dirname } from 'node:path'
5
+ import { APPROVALS, eventStream, isRecord, MAX_BODY, MCP_ENDPOINT, errorMessage, prefixed } from '@lincyaw/kernel'
6
+ import type {
7
+ ApprovalKind,
8
+ Logger,
9
+ McpEndpoint,
10
+ Member,
11
+ ProxySpec,
12
+ Route,
13
+ ServerContext,
14
+ ServerContribution,
15
+ ServiceToken,
16
+ } from '@lincyaw/kernel'
17
+ import { pluginLogger } from '@lincyaw/compiler'
18
+ import { createPresmiumMcp } from '@lincyaw/mcp'
19
+ import type { McpCaller } from '@lincyaw/mcp'
20
+ import { authenticate, LOCAL_AUTHOR, machineHosts } from './auth.ts'
21
+ import type { Refusal } from './auth.ts'
22
+ import { Control, hasRole } from './control.ts'
23
+ import type { ApprovalPolicy, WindowPosition } from './control.ts'
24
+ import { focusBody, FocusStore } from './focus.ts'
25
+ import type { ServedDocument, ServerHost } from './host.ts'
26
+ import { bearer, closeServer, createProxy, header, isLoopback, json, limitBody, listen, nodeServer, problem, urlHost } from './http.ts'
27
+ import type { Decision, ProxyTarget } from './http.ts'
28
+ import { serverMcpHost } from './mcp.ts'
29
+
30
+ export { LOCAL_AUTHOR }
31
+
32
+ export const SERVER_PATH = '/__presmium/presmium.server'
33
+
34
+ function isMcp(path: string): boolean {
35
+ return path === '/mcp' || path.startsWith('/mcp/')
36
+ }
37
+
38
+ function endedBy(response: Response, signal: AbortSignal, done: () => void): Response {
39
+ if (!response.body) {
40
+ done()
41
+ return response
42
+ }
43
+ const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>()
44
+ void response.body.pipeTo(writable, { signal, preventAbort: true })
45
+ .catch(() => writable.close().catch(() => undefined))
46
+ .finally(done)
47
+ return new Response(readable, { status: response.status, statusText: response.statusText, headers: response.headers })
48
+ }
49
+
50
+ export interface ServerOptions {
51
+ mode: 'dev' | 'serve'
52
+ host?: string
53
+ port?: number
54
+ document(dir: string): Promise<ServedDocument | undefined>
55
+ serverHost?: ServerHost
56
+ settings?: Record<string, Record<string, unknown>>
57
+ approvals?: Partial<Record<ApprovalKind, ApprovalPolicy>>
58
+ forward?(): string | undefined
59
+ operatorDir?: string
60
+ stateFile?: string
61
+ mcp?(request: Request, access: McpCaller): Promise<Response>
62
+ env?: NodeJS.ProcessEnv
63
+ approvalTimeoutMs?: number
64
+ log?: Logger
65
+ }
66
+
67
+ export interface PresmiumServer {
68
+ url: string
69
+ port: number
70
+ token: string
71
+ services: [ServiceToken<unknown>, unknown][]
72
+ control: Control
73
+ serverHost?: ServerHost
74
+ unmount(dir: string): Promise<void>
75
+ close(): Promise<void>
76
+ }
77
+
78
+ interface Mounted {
79
+ doc: ServedDocument
80
+ contributions: Map<string, ServerContribution>
81
+ }
82
+
83
+ function pluginPath(pathname: string): { plugin: string, path: string, raw: string, plain: boolean } | undefined {
84
+ const match = /^\/__presmium\/([^/]+)\/?(.*)$/.exec(pathname)
85
+ if (!match) return undefined
86
+ const raw = match[2]!
87
+ let path = raw
88
+ let plain = !/%(?:2f|5c)/i.test(raw) && !raw.includes('\\')
89
+ try {
90
+ path = decodeURIComponent(raw)
91
+ } catch {
92
+ plain = false
93
+ }
94
+ if (path.split('/').some(part => part === '.' || part === '..')) plain = false
95
+ return { plugin: match[1]!, path, raw, plain }
96
+ }
97
+
98
+ function findRoute(routes: Record<string, Route> | undefined, path: string): { route: Route, rest: string, key: string } | undefined {
99
+ if (!routes) return undefined
100
+ if (routes[path] && !path.endsWith('/*')) return { route: routes[path]!, rest: '', key: path }
101
+ let best: { route: Route, rest: string, key: string } | undefined
102
+ for (const [key, route] of Object.entries(routes)) {
103
+ if (!key.endsWith('/*')) continue
104
+ const prefix = key.slice(0, -1)
105
+ const base = key.slice(0, -2)
106
+ if ((path.startsWith(prefix) || path === base) && (!best || key.length > best.key.length)) best = { route, rest: path.slice(prefix.length), key }
107
+ }
108
+ return best
109
+ }
110
+
111
+ function findProxy(proxies: ProxySpec[] | undefined, path: string): { spec: ProxySpec, rest: string } | undefined {
112
+ for (const spec of proxies ?? []) {
113
+ const base = spec.path.replace(/^\/+|\/+$/g, '')
114
+ if (path === base || path.startsWith(`${base}/`)) return { spec, rest: path.slice(base.length) }
115
+ }
116
+ return undefined
117
+ }
118
+
119
+ function documentOf(headers: IncomingMessage['headers'], url: URL): string {
120
+ const value = header(headers, 'presmium-document') ?? url.searchParams.get('document') ?? ''
121
+ try {
122
+ return decodeURIComponent(value).replace(/^\/+|\/+$/g, '')
123
+ } catch {
124
+ return value
125
+ }
126
+ }
127
+
128
+ function remoteHost(mode: ServerOptions['mode'], host: string, port: number | undefined): string | undefined {
129
+ if (mode === 'serve' || isLoopback(host)) return undefined
130
+ const at = port || 'its port'
131
+ return `presmium ${mode} listens on this machine only, not on ${host}: it serves the one user who runs it. To use it from another machine, forward its port over SSH (ssh -L ${at}:127.0.0.1:${at} <this machine>), or use presmium serve --host`
132
+ }
133
+
134
+ export async function startServer(options: ServerOptions): Promise<PresmiumServer> {
135
+ const env = options.env ?? process.env
136
+ const log = options.log ?? pluginLogger('presmium server')
137
+ const listenHost = options.host ?? '127.0.0.1'
138
+ const refused = remoteHost(options.mode, listenHost, options.port)
139
+ if (refused) throw new Error(refused)
140
+ const local = machineHosts(listenHost)
141
+
142
+ const control = new Control({
143
+ policy: options.approvals ?? {},
144
+ timeoutMs: options.approvalTimeoutMs,
145
+ })
146
+ const token = randomBytes(24).toString('base64url')
147
+ const mcpTokens = new Map<string, McpCaller>()
148
+ const mcpStreams = new Map<string, Set<AbortController>>()
149
+ let url = ''
150
+ const mcpEndpoint: McpEndpoint = {
151
+ issue(member, mode, issued = {}) {
152
+ const value = randomBytes(24).toString('base64url')
153
+ mcpTokens.set(value, { member, mode, ...issued.confirmed ? { confirmed: true } : {}, ...issued.document !== undefined ? { document: issued.document } : {} })
154
+ return {
155
+ url: `${url}/mcp`,
156
+ token: value,
157
+ revoke: () => {
158
+ mcpTokens.delete(value)
159
+ for (const stream of mcpStreams.get(value) ?? []) stream.abort()
160
+ mcpStreams.delete(value)
161
+ },
162
+ }
163
+ },
164
+ }
165
+ const services: [ServiceToken<unknown>, unknown][] = [[APPROVALS, control.approvals], [MCP_ENDPOINT, mcpEndpoint]]
166
+
167
+ const serviceToken = env.PRESMIUM_SERVICE_TOKEN || undefined
168
+ const fromHost = (request: Request) => {
169
+ const given = bearer(request.headers.get('authorization'))
170
+ if (!serviceToken || given === undefined || given.length !== serviceToken.length) return false
171
+ return timingSafeEqual(Buffer.from(given), Buffer.from(serviceToken))
172
+ }
173
+ const sessions = new Map<string, ReturnType<McpEndpoint['issue']>>()
174
+ const focus = new FocusStore()
175
+ const own = new Map(services.map(([token, impl]) => [token.id, impl]))
176
+
177
+ const mounted = new Map<string, Promise<Mounted | undefined>>()
178
+ const mount = (dir: string) => {
179
+ let known = mounted.get(dir)
180
+ if (!known) {
181
+ known = (async () => {
182
+ const doc = await options.document(dir)
183
+ if (!doc) return undefined
184
+ log.debug(`mounting the server contributions of ${dir || 'the deck'}: ${doc.plugins.filter(p => p.plugin.server).map(p => p.id).join(', ') || 'none'}`)
185
+ const contributions = new Map<string, ServerContribution>()
186
+ for (const { id, plugin, config } of doc.plugins) {
187
+ if (!plugin.server) continue
188
+ const operatorDir = options.operatorDir ?? doc.operatorDir
189
+ const ctx: ServerContext = {
190
+ deckDir: doc.deckDir,
191
+ workspaceRoot: doc.workspaceRoot,
192
+ config,
193
+ settings: (options.settings ?? doc.settings)?.[id] ?? {},
194
+ lang: doc.lang,
195
+ service: <T>(token: ServiceToken<T>) => (own.get(token.id) as T | undefined) ?? doc.service(token),
196
+ secret: name => env[name],
197
+ ...operatorDir ? { operatorDir } : {},
198
+ ...doc.home ? { home: true } : {},
199
+ log: prefixed(log, id),
200
+ }
201
+ try {
202
+ contributions.set(id, await plugin.server.call(plugin, ctx))
203
+ } catch (error) {
204
+ log.error(`plugin ${id} failed to make its server contribution: ${errorMessage(error)}`)
205
+ }
206
+ }
207
+ return { doc, contributions }
208
+ })()
209
+ const loading = known
210
+ loading.then((found) => {
211
+ if (!found && mounted.get(dir) === loading) mounted.delete(dir)
212
+ }, () => mounted.delete(dir))
213
+ mounted.set(dir, known)
214
+ }
215
+ return known
216
+ }
217
+
218
+ const mcp = options.mcp ? undefined : createPresmiumMcp(serverMcpHost({
219
+ serverHost: options.serverHost,
220
+ control,
221
+ command: options.mode,
222
+ mount: async dir => (await mount(dir))?.doc,
223
+ mounted: async () => (await Promise.all([...mounted.values()].map(known => known.catch(() => undefined)))).flatMap(m => (m ? [m.doc] : [])),
224
+ service: <T>(token: ServiceToken<T>) => own.get(token.id) as T | undefined,
225
+ focus,
226
+ }))
227
+
228
+ const members = new WeakMap<IncomingMessage, Member | Refusal>()
229
+ const memberOf = (req: IncomingMessage): Member | Refusal => {
230
+ let found = members.get(req)
231
+ if (!found) members.set(req, found = authenticate(req, local))
232
+ return found
233
+ }
234
+
235
+ const refuse = (refusal: Refusal): Decision => ({ kind: 'answer', response: problem(refusal.status, refusal.message) })
236
+
237
+ const decide = async (req: IncomingMessage): Promise<Decision> => {
238
+ const url = new URL(req.url ?? '/', 'http://presmium')
239
+ const path = url.pathname
240
+ const member = memberOf(req)
241
+ if ('status' in member) return refuse(member)
242
+ const target = pluginPath(path)
243
+ if (target && !target.plain) return refuse({ status: 400, message: 'a path with a . or .. part or an encoded separator' })
244
+ if (isMcp(path)) return { kind: 'fetch' }
245
+ if (target) {
246
+ if (target.plugin === 'presmium.server') return { kind: 'fetch' }
247
+ const proxy = await proxyOf(target, documentOf(req.headers, url), member, url.search)
248
+ return proxy ?? { kind: 'fetch' }
249
+ }
250
+ const forward = options.mode === 'serve' ? options.forward?.() : undefined
251
+ if (!forward) return { kind: 'answer', response: problem(404, 'not found') }
252
+ const site = new URL(forward)
253
+ const lan = !isLoopback(header(req.headers, 'host'))
254
+ const headers = lan ? { host: site.host, ...header(req.headers, 'origin') ? { origin: site.origin } : {} } : undefined
255
+ return { kind: 'proxy', to: { target: forward, path: req.url ?? '/', ...headers ? { headers } : {} } }
256
+ }
257
+
258
+ const proxyOf = async (target: { plugin: string, path: string, raw: string }, dir: string, member: Member, search: string): Promise<Decision | undefined> => {
259
+ const contribution = (await mount(dir))?.contributions.get(target.plugin)
260
+ const found = findProxy(contribution?.proxies, target.path)
261
+ if (!found) return undefined
262
+ const role = found.spec.role ?? 'editor'
263
+ if (!hasRole(member, role)) return refuse({ status: 403, message: `this proxy needs the role ${role}` })
264
+ const base = found.spec.path.split('/').filter(Boolean).length
265
+ const rest = target.raw.split('/').slice(base).join('/')
266
+ const path = `${rest ? `/${rest}` : found.rest || '/'}${search}`
267
+ return { kind: 'proxy', to: { target: found.spec.target, path, headers: found.spec.headers } }
268
+ }
269
+
270
+ const decideUpgrade = async (req: IncomingMessage): Promise<{ to?: ProxyTarget, status?: number }> => {
271
+ const decision = await decide(req)
272
+ if (decision.kind === 'proxy') return { to: decision.to }
273
+ return { status: decision.kind === 'answer' ? decision.response.status : 404 }
274
+ }
275
+
276
+ const serveMcp = async (request: Request): Promise<Response> => {
277
+ const given = bearer(request.headers.get('authorization'))
278
+ const access: McpCaller | undefined = given === undefined ? undefined : given === token ? { member: LOCAL_AUTHOR, mode: 'author' as const } : mcpTokens.get(given)
279
+ if (!access) return problem(401, 'MCP needs an Authorization: Bearer token')
280
+ const limited = await limitBody(request, MAX_BODY)
281
+ if (limited instanceof Response) return limited
282
+ request = limited
283
+ const response = await (options.mcp ? options.mcp(request, access) : mcp!.fetch(request, access))
284
+ if (given === token || !response.headers.get('content-type')?.startsWith('text/event-stream')) return response
285
+ if (!mcpTokens.has(given!)) return endedBy(response, AbortSignal.abort(), () => {})
286
+ const stream = new AbortController()
287
+ const open = mcpStreams.get(given!) ?? new Set()
288
+ mcpStreams.set(given!, open.add(stream))
289
+ return endedBy(response, stream.signal, () => open.delete(stream))
290
+ }
291
+
292
+ const handle = async (request: Request, req: IncomingMessage): Promise<Response> => {
293
+ const url = new URL(request.url)
294
+ const path = url.pathname
295
+ const member = memberOf(req)
296
+ if ('status' in member) return problem(member.status, member.message)
297
+ const document = documentOf(req.headers, url)
298
+ if (isMcp(path)) return serveMcp(request)
299
+ if (path.startsWith(`${SERVER_PATH}/`)) return await serverRoute(request, path.slice(SERVER_PATH.length + 1), member, document, req)
300
+ const target = pluginPath(path)
301
+ if (!target) return problem(404, 'not found')
302
+ return await pluginRoute(request, target, member, document)
303
+ }
304
+
305
+ const serverRoute = async (request: Request, route: string, member: Member, document: string, req: IncomingMessage): Promise<Response> => {
306
+ if (route === 'hello') return json({ member, document })
307
+ if (route === 'control') {
308
+ if (request.method === 'GET') {
309
+ const window = new URL(request.url).searchParams.get('window') || randomUUID()
310
+ const stream = control.open(window, member, document)
311
+ req.once('close', () => stream.close())
312
+ return eventStream(stream, request.signal)
313
+ }
314
+ if (request.method !== 'POST') return problem(405, 'GET or POST')
315
+ const limited = await limitBody(request, MAX_BODY)
316
+ if (limited instanceof Response) return limited
317
+ const body: unknown = await limited.json().catch(() => undefined)
318
+ if (!isRecord(body)) return problem(400, 'a JSON object')
319
+ if (body.type === 'answer' && typeof body.id === 'string') {
320
+ const status = control.answer(body.id, body.allow === true, member)
321
+ return status === 200 ? json({ ok: true }) : problem(status, status === 404 ? 'no such approval' : 'this member may not answer this approval')
322
+ }
323
+ if (body.type === 'report' && typeof body.window === 'string') {
324
+ const position = windowPosition(body.position)
325
+ const ok = control.report(body.window, member, { position, role: typeof body.role === 'string' ? body.role : undefined, status: isRecord(body.status) ? body.status : undefined })
326
+ return ok ? json({ ok: true }) : problem(404, 'unknown window')
327
+ }
328
+ return problem(400, 'unknown message')
329
+ }
330
+ if (route === 'tokens') return await tokensRoute(request)
331
+ if (route === 'focus') return await focusRoute(request)
332
+ return problem(404, 'not found')
333
+ }
334
+
335
+ const tokensRoute = async (request: Request): Promise<Response> => {
336
+ if (!serviceToken) return problem(403, 'session tokens are issued only to the host that started this service (PRESMIUM_SERVICE_TOKEN)')
337
+ if (!fromHost(request)) return problem(401, 'session tokens need Authorization: Bearer <the service token>')
338
+ const limited = await limitBody(request, MAX_BODY)
339
+ if (limited instanceof Response) return limited
340
+ const body: unknown = await limited.json().catch(() => ({}))
341
+ const session = isRecord(body) && typeof body.session === 'string' && body.session !== '' ? body.session : undefined
342
+ if (request.method === 'DELETE') {
343
+ const revoked = session === undefined ? [...sessions.keys()] : sessions.has(session) ? [session] : []
344
+ for (const id of revoked) {
345
+ sessions.get(id)!.revoke()
346
+ sessions.delete(id)
347
+ }
348
+ return json({ revoked: revoked.length })
349
+ }
350
+ if (request.method !== 'POST') return problem(405, 'POST or DELETE')
351
+ if (!isRecord(body) || typeof body.document !== 'string' || session === undefined) return problem(400, '{ document, session }')
352
+ const document = body.document
353
+ if (options.serverHost && !(await options.serverHost.documents()).some(doc => doc.dir === document)) return problem(404, `no document ${JSON.stringify(document)}`)
354
+ sessions.get(session)?.revoke()
355
+ const grant = mcpEndpoint.issue(LOCAL_AUTHOR, 'author', { confirmed: true, document })
356
+ sessions.set(session, grant)
357
+ return json({ url: grant.url, token: grant.token, document }, 201)
358
+ }
359
+
360
+ const focusRoute = async (request: Request): Promise<Response> => {
361
+ if (request.method === 'GET') {
362
+ const params = new URL(request.url).searchParams
363
+ const found = focus.get(params.has('document') ? params.get('document')! : undefined)
364
+ return json(found ? { document: found.document, focus: found.focus, reported: new Date(found.at).toISOString() } : { focus: null })
365
+ }
366
+ if (request.method !== 'POST') return problem(405, 'GET or POST')
367
+ if (serviceToken && !fromHost(request)) return problem(401, 'a focus report needs Authorization: Bearer <the service token>')
368
+ if (!options.serverHost) return problem(409, 'this server compiles no document')
369
+ const limited = await limitBody(request, MAX_BODY)
370
+ if (limited instanceof Response) return limited
371
+ const body = focusBody(await limited.json().catch(() => undefined))
372
+ if (typeof body === 'string') return problem(400, body)
373
+ if (!(await options.serverHost.documents()).some(doc => doc.dir === body.document)) return problem(404, `no document ${JSON.stringify(body.document)}`)
374
+ try {
375
+ const { doc } = await options.serverHost.compile(body.document)
376
+ const record = focus.report(body.document, doc, body.focus)
377
+ return json({ document: record.document, focus: record.focus, reported: new Date(record.at).toISOString() })
378
+ } catch (error) {
379
+ return problem(400, errorMessage(error))
380
+ }
381
+ }
382
+
383
+ const pluginRoute = async (request: Request, target: { plugin: string, path: string }, member: Member, document: string): Promise<Response> => {
384
+ const known = await mount(document)
385
+ if (!known) return problem(404, `no document ${JSON.stringify(document)}`)
386
+ const found = findRoute(known.contributions.get(target.plugin)?.routes, target.path)
387
+ if (!found) return problem(404, 'not found')
388
+ const role = found.route.role ?? 'editor'
389
+ if (!hasRole(member, role)) return problem(403, `this route needs the role ${role}`)
390
+ const limited = await limitBody(request, found.route.maxBody ?? MAX_BODY)
391
+ if (limited instanceof Response) return limited
392
+ try {
393
+ const response = await found.route.handle(limited, { member, document, rest: found.rest })
394
+ return response.headers.has('cache-control') ? response : withHeaders(response, { 'Cache-Control': 'no-store' })
395
+ } catch (error) {
396
+ log.error(`route ${target.plugin}/${target.path} failed: ${errorMessage(error)}`)
397
+ return problem(500, errorMessage(error))
398
+ }
399
+ }
400
+
401
+ const proxy = createProxy()
402
+ const server = nodeServer({ decide, decideUpgrade, fetch: handle, proxy })
403
+ const port = await listen(server, options.port ?? (options.mode === 'dev' ? 0 : 4310), listenHost)
404
+ url = `http://${urlHost(listenHost)}:${port}`
405
+ log.debug(`listening at ${url}`)
406
+ if (options.stateFile) {
407
+ mkdirSync(dirname(options.stateFile), { recursive: true })
408
+ writeFileSync(options.stateFile, `${JSON.stringify({ url, mcp: `${url}/mcp`, token, pid: process.pid }, null, 2)}\n`, { mode: 0o600 })
409
+ chmodSync(options.stateFile, 0o600)
410
+ }
411
+
412
+ const takeDown = async (known: Promise<Mounted | undefined>) => {
413
+ for (const [id, contribution] of (await known.catch(() => undefined))?.contributions ?? []) {
414
+ await Promise.resolve(contribution.close?.()).catch((error: unknown) => log.error(`the contribution of ${id} failed to close: ${errorMessage(error)}`))
415
+ }
416
+ }
417
+
418
+ return {
419
+ url,
420
+ port,
421
+ token,
422
+ services,
423
+ control,
424
+ serverHost: options.serverHost,
425
+ async unmount(dir) {
426
+ focus.forget(dir)
427
+ const known = mounted.get(dir)
428
+ mounted.delete(dir)
429
+ if (known) {
430
+ log.debug(`unmounting the server contributions of ${dir || 'the deck'}`)
431
+ await takeDown(known)
432
+ }
433
+ },
434
+ async close() {
435
+ for (const grant of sessions.values()) grant.revoke()
436
+ sessions.clear()
437
+ control.close()
438
+ await mcp?.close().catch((error: unknown) => log.error(`MCP failed to close: ${errorMessage(error)}`))
439
+ for (const known of mounted.values()) await takeDown(known)
440
+ proxy.close()
441
+ await closeServer(server)
442
+ },
443
+ }
444
+ }
445
+
446
+ function withHeaders(response: Response, headers: Record<string, string>): Response {
447
+ for (const [name, value] of Object.entries(headers)) {
448
+ try {
449
+ response.headers.set(name, value)
450
+ } catch {
451
+ const copy = new Response(response.body, response)
452
+ for (const [n, v] of Object.entries(headers)) copy.headers.set(n, v)
453
+ return copy
454
+ }
455
+ }
456
+ return response
457
+ }
458
+
459
+ function windowPosition(value: unknown): WindowPosition | undefined {
460
+ if (!isRecord(value) || typeof value.slide !== 'number' || typeof value.step !== 'number') return undefined
461
+ const { trail } = value
462
+ return {
463
+ slide: value.slide,
464
+ step: value.step,
465
+ ...typeof value.view === 'string' ? { view: value.view } : {},
466
+ ...typeof value.section === 'string' ? { section: value.section } : {},
467
+ ...Array.isArray(trail) && trail.length <= 10_000 && trail.every(key => typeof key === 'string') ? { trail: trail as string[] } : {},
468
+ }
469
+ }