dsh-marker 0.1.2 → 0.1.4

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/src/protocol.js CHANGED
@@ -28,6 +28,15 @@ export const HEALTH_PATH = '/ext/anno/health'
28
28
  */
29
29
  export const SESSIONS_PATH = '/ext/anno/sessions'
30
30
 
31
+ /**
32
+ * Online session creation for the overlay's "new session" target.
33
+ *
34
+ * POST only, token-gated like the catalog. Creation is never queued: a session
35
+ * that does not exist yet has no outbox entry to replay, so the route answers
36
+ * or fails while the composer is still open.
37
+ */
38
+ export const SESSION_CREATE_PATH = '/ext/anno/session-create'
39
+
31
40
  /**
32
41
  * Durable hand-off from the extension to the Web Client: mentions waiting to be
33
42
  * appended to one Session's composer. Same-origin only — the GUI is the page
@@ -38,6 +47,15 @@ export const QUEUE_PATH = '/ext/anno/queue'
38
47
  /** Acknowledged queue entries are removed here; POST `{ids}`. */
39
48
  export const QUEUE_ACK_PATH = '/ext/anno/queue/ack'
40
49
 
50
+ /**
51
+ * The page's push channel: one server-sent event stream per Web Client, telling
52
+ * a mounted Session that something it may own just changed. Same-origin only.
53
+ *
54
+ * It carries a *nudge*, never the data — the queue above stays the authority,
55
+ * so a missed event costs a slower delivery rather than a lost one.
56
+ */
57
+ export const EVENTS_PATH = '/ext/anno/events'
58
+
41
59
  /**
42
60
  * The Session the Web Client is showing, reported by that Client so the Host
43
61
  * can answer "where does an annotation go by default?". Same-origin only, for
@@ -147,6 +165,61 @@ export const LIMITS = {
147
165
  sessionsLimit: 100,
148
166
  /** Chip label carried by a routed mention; presentation only, never identity. */
149
167
  labelChars: 200,
168
+ /** Absolute workspace directory path in a session-create request body. */
169
+ workspacePathChars: 1_024,
170
+ /** Workspace title in a session-create request body. */
171
+ workspaceTitleChars: 200,
172
+ /** Whole session-create request body, far below any parser's limits. */
173
+ createBodyChars: 4_096,
174
+ }
175
+
176
+ /** Session-create workspace modes, in the order the picker offers them. */
177
+ export const SESSION_CREATE_MODES = ['default', 'existing', 'new']
178
+
179
+ /**
180
+ * Validate one session-create request body.
181
+ *
182
+ * @param {unknown} body
183
+ * @returns {string[]} human-readable violations; empty means usable
184
+ */
185
+ export function validateSessionCreateRequest(body) {
186
+ if (!isPlainObject(body)) return ['body must be a JSON object']
187
+ /** @type {string[]} */
188
+ const errors = []
189
+ if (!SESSION_CREATE_MODES.includes(body.mode)) {
190
+ return [`mode must be one of ${SESSION_CREATE_MODES.join('|')}`]
191
+ }
192
+ if (body.mode === 'existing') {
193
+ if (!isString(body.workspaceId) || body.workspaceId.length === 0) {
194
+ errors.push('workspaceId is required when mode is existing')
195
+ } else if (body.workspaceId.length > 200) {
196
+ errors.push('workspaceId exceeds 200 characters')
197
+ }
198
+ }
199
+ if (body.mode === 'new') {
200
+ const path = body.path
201
+ if (!isString(path) || path.length === 0) {
202
+ errors.push('path is required when mode is new')
203
+ } else {
204
+ if (path.length > LIMITS.workspacePathChars) {
205
+ errors.push(`path exceeds ${LIMITS.workspacePathChars} characters`)
206
+ }
207
+ // Absolute only: the host resolves it against its own filesystem, and a
208
+ // relative path would silently land wherever the process happens to run.
209
+ if (path.startsWith('/') !== true && path.startsWith('\\') !== true && !/^[A-Za-z]:[\\/]/.test(path)) {
210
+ errors.push('path must be absolute')
211
+ }
212
+ if (path.includes('\0')) errors.push('path must not contain null bytes')
213
+ }
214
+ }
215
+ if (body.title !== undefined) {
216
+ if (!isString(body.title)) errors.push('title must be a string')
217
+ else if (body.title.trim().length === 0) errors.push('title must not be blank')
218
+ else if (body.title.length > LIMITS.workspaceTitleChars) {
219
+ errors.push(`title exceeds ${LIMITS.workspaceTitleChars} characters`)
220
+ }
221
+ }
222
+ return errors
150
223
  }
151
224
 
152
225
  /** Every frame a client may send to the host. */
@@ -0,0 +1,323 @@
1
+ /**
2
+ * Online session creation for the overlay's "new session" target.
3
+ *
4
+ * The overlay's picker lists Sessions that already exist; this module is the
5
+ * other arm — "this annotation starts a new conversation" — which only the
6
+ * Host can honour, because only it owns `sessionController.create` and the
7
+ * workspace registry. Three workspace modes:
8
+ *
9
+ * - `default` the deployment's first-use Workspace ("默认工作区"), joined by
10
+ * its fixed title when the registry has it; a bare no-location
11
+ * create otherwise;
12
+ * - `existing` one registered workspace by id, the Session joins it;
13
+ * - `new` an absolute path (and optional title), registered first — a
14
+ * missing directory is created here (the registry itself will
15
+ * not), and an already-registered directory resolves
16
+ * idempotently.
17
+ *
18
+ * Nothing here is queued. A session that does not exist yet has no outbox
19
+ * entry to replay, so a failure is answered while the composer is still open
20
+ * and the annotation stays unsent in the browser.
21
+ *
22
+ * @module dsh-marker/provision
23
+ */
24
+
25
+ import { mkdir } from 'node:fs/promises'
26
+
27
+ import { LIMITS, SESSION_CREATE_PATH, validateSessionCreateRequest } from './protocol.js'
28
+
29
+ /** The Client picks its workspace rows per open; a second of staleness is invisible. */
30
+ const WORKSPACES_TTL_MS = 1_000
31
+
32
+ /**
33
+ * Fixed first-use Workspace title (DSH's `DEFAULT_WORKSPACE_DIRECTORY`, on the
34
+ * Documents path). Language-neutral by design, so a title comparison is enough.
35
+ */
36
+ const DEFAULT_WORKSPACE_TITLE = 'default-workspace'
37
+
38
+ /**
39
+ * @param {object} options
40
+ * @param {(name: string) => any} options.get Cordis service lookup for the mounting context.
41
+ * @param {{ list: (options?: object) => Promise<{ items?: any[] }> } | undefined} [options.catalog]
42
+ * Session catalog, when one is mounted; its blank rows are what "reuse the
43
+ * workspace's blank Session" is answered from.
44
+ * @param {(body: any) => void | Promise<void>} options.onCreated Side effect after one created session (push, focus hints).
45
+ * @param {{ warn?: (...args: any[]) => void, info?: (...args: any[]) => void }} [options.logger]
46
+ * @param {() => number} [options.now] Clock, injected by tests.
47
+ */
48
+ export function createProvisioner({ get, catalog, onCreated, logger, now = Date.now }) {
49
+ /** @type {{ at: number, items: any[] } | null} */
50
+ let workspaceCache = null
51
+
52
+ /**
53
+ * Every registered workspace, ordered as the registry keeps them (display
54
+ * order). Cached for a moment so the picker's workspaces list and a create
55
+ * that follows in the same gesture do not scan the registry twice.
56
+ * @returns {Promise<any[]>} `{ id, title, path }` rows
57
+ */
58
+ async function listWorkspaces() {
59
+ const registry = get('workspaceRegistry')
60
+ if (registry === undefined) throw new Error('the workspace registry is not mounted in this profile')
61
+ if (workspaceCache !== null && now() - workspaceCache.at < WORKSPACES_TTL_MS) return workspaceCache.items
62
+ const items = []
63
+ try {
64
+ for (const workspace of registry.list()) {
65
+ items.push({ id: workspace.id, title: workspace.title, path: workspace.path })
66
+ }
67
+ } catch (error) {
68
+ throw new Error(`the workspace registry could not be read (${messageOf(error)})`)
69
+ }
70
+ workspaceCache = { at: now(), items }
71
+ return items
72
+ }
73
+
74
+ /**
75
+ * Create one Session in the requested workspace mode.
76
+ *
77
+ * @param {any} body validated request: `{ mode, workspaceId?, path?, title? }`
78
+ * @returns {Promise<{ sessionId: string, workspace: { id: string, title: string, path: string } | null }>}
79
+ */
80
+ async function createSession(body) {
81
+ const controller = get('sessionController')
82
+ if (controller === undefined) throw new Error('the session controller is not mounted in this profile')
83
+
84
+ let workspace = null
85
+ let request = {}
86
+ if (body.mode === 'existing') {
87
+ workspace = await findByWorkspaceId(String(body.workspaceId))
88
+ if (workspace === null) throw new Error('that workspace no longer exists on this host')
89
+ // `workspaceId` joins the Session to the workspace record; `cwd` is the
90
+ // standalone alternative and the two are exclusive by contract.
91
+ request = await requestFor(workspace)
92
+ } else if (body.mode === 'new') {
93
+ workspace = await registerWorkspace(String(body.path), typeof body.title === 'string' ? body.title : undefined)
94
+ request = await requestFor(workspace)
95
+ } else {
96
+ // `default` is the row the Client labels "默认工作区": the deployment's
97
+ // first-use Workspace, recognised by its fixed title. A Session created
98
+ // without it belongs to no Workspace row and never shows in that group,
99
+ // so join it when the registry has it. A registry that cannot be read
100
+ // (missing, or a failed scan) keeps the bare no-location create: this
101
+ // mode has always worked without one.
102
+ try {
103
+ const items = await listWorkspaces()
104
+ workspace = items.find((item) => item.title === DEFAULT_WORKSPACE_TITLE) ?? null
105
+ } catch {
106
+ workspace = null
107
+ }
108
+ if (workspace !== null) request = await requestFor(workspace)
109
+ }
110
+
111
+ const value = await controller.create(request)
112
+ const sessionId = typeof value?.sessionId === 'string' ? value.sessionId : ''
113
+ if (sessionId === '') throw new Error('the host created the session but returned no identity')
114
+ logger?.info?.(`annotations: session ${sessionId} created (mode ${String(body.mode)})`)
115
+ if (onCreated) await onCreated({ sessionId, workspace })
116
+ return { sessionId, workspace }
117
+ }
118
+
119
+ /** @param {string} workspaceId */
120
+ async function findByWorkspaceId(workspaceId) {
121
+ const items = await listWorkspaces()
122
+ return items.find((item) => item.id === workspaceId) ?? null
123
+ }
124
+
125
+ /**
126
+ * Join the workspace, reusing its blank Session when the catalog can name
127
+ * one: annotations that target "a new conversation here" must append to the
128
+ * same conversation, not mint a sibling per send. The controller owns the
129
+ * final say — it re-checks that the named Session is still blank and still a
130
+ * workspace member before reusing it, so a stale answer here can only cost a
131
+ * fresh Session, never a wrong reuse.
132
+ * @param {{ id: string, title: string, path: string }} workspace
133
+ */
134
+ async function requestFor(workspace) {
135
+ const blank = await findBlankIn(workspace)
136
+ return { workspaceId: workspace.id, ...(blank === undefined ? {} : { sessionId: blank }) }
137
+ }
138
+
139
+ /**
140
+ * The workspace's most recently active blank Session, when the catalog can
141
+ * name one. A failed lookup is a warning, not a failed create.
142
+ * @param {{ id: string, title: string, path: string }} workspace
143
+ * @returns {Promise<string | undefined>}
144
+ */
145
+ async function findBlankIn(workspace) {
146
+ if (catalog === undefined) return undefined
147
+ try {
148
+ const value = await catalog.list({ query: workspace.title, limit: 50 })
149
+ const rows = Array.isArray(value?.items) ? value.items : []
150
+ let best = null
151
+ for (const row of rows) {
152
+ if (row?.workspace?.id !== workspace.id || row.blank !== true) continue
153
+ if (best === null || Number(row.updatedAt ?? 0) > Number(best.updatedAt ?? 0)) best = row
154
+ }
155
+ return best !== null && typeof best.id === 'string' ? best.id : undefined
156
+ } catch (error) {
157
+ logger?.warn?.(`annotations: blank session lookup failed (${messageOf(error)})`)
158
+ return undefined
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Register (or idempotently resolve) one workspace over an absolute path.
164
+ *
165
+ * The registry canonicalises through `realpath` and does not create the
166
+ * directory (verified against DSH 0.2.2), while the browser half cannot make
167
+ * one at all — so a missing directory is made here and the registration
168
+ * retried once before the failure is reported.
169
+ * @param {string} path
170
+ * @param {string | undefined} title
171
+ */
172
+ async function registerWorkspace(path, title) {
173
+ const registry = get('workspaceRegistry')
174
+ if (registry === undefined) throw new Error('the workspace registry is not mounted in this profile')
175
+ try {
176
+ return await register(registry, path, title)
177
+ } catch (error) {
178
+ const message = messageOf(error)
179
+ if (!/ENOENT/.test(message)) throw new Error(`the workspace could not be created (${message})`)
180
+ try {
181
+ await mkdir(path, { recursive: true })
182
+ } catch (madeError) {
183
+ throw new Error(`the workspace directory could not be created (${messageOf(madeError)})`)
184
+ }
185
+ try {
186
+ return await register(registry, path, title)
187
+ } catch (again) {
188
+ throw new Error(`the workspace could not be created (${messageOf(again)})`)
189
+ }
190
+ }
191
+ }
192
+
193
+ /**
194
+ * One registration attempt, bare: the ENOENT test in {@link registerWorkspace}
195
+ * must see the registry's own error, not this module's wrapping of it.
196
+ * @param {any} registry
197
+ * @param {string} path
198
+ * @param {string | undefined} title
199
+ */
200
+ async function register(registry, path, title) {
201
+ const workspace = await registry.create(path, title)
202
+ workspaceCache = null
203
+ return { id: workspace.id, title: workspace.title, path: workspace.path }
204
+ }
205
+
206
+ return { listWorkspaces, createSession }
207
+ }
208
+
209
+ /**
210
+ * Serve session creation on the Host webserver.
211
+ *
212
+ * The bridge token is the only gate, exactly like the catalog: the overlay
213
+ * runs on an arbitrary http(s) page, so no cookie or Origin assumption can
214
+ * hold. POST only; the body is bounded far below anything the parser cares
215
+ * about, and validation happens before any Host service is touched.
216
+ *
217
+ * @param {any} webServer
218
+ * @param {object} options
219
+ * @param {ReturnType<typeof createProvisioner>} options.provisioner
220
+ * @param {string} options.token
221
+ * @param {(presented: unknown, expected: string) => boolean} options.matchesToken
222
+ * @param {string} [options.path]
223
+ * @returns {() => void} disposer
224
+ */
225
+ export function registerProvisionRoutes(webServer, { provisioner, token, matchesToken, path = SESSION_CREATE_PATH }) {
226
+ const headers = {
227
+ 'content-type': 'application/json; charset=utf-8',
228
+ 'cache-control': 'no-store',
229
+ 'access-control-allow-origin': '*',
230
+ 'access-control-allow-headers': 'authorization, content-type, x-anno-token',
231
+ 'access-control-allow-methods': 'POST, OPTIONS',
232
+ }
233
+ /** @param {number} status @param {any} payload @param {any} request @param {any} response */
234
+ const send = (status, payload, request, response) => {
235
+ const body = JSON.stringify(payload)
236
+ response.writeHead(status, headers)
237
+ response.end(request.method === 'HEAD' ? undefined : body)
238
+ }
239
+
240
+ return webServer.register({
241
+ kind: 'exact',
242
+ path,
243
+ auth: 'anonymous',
244
+ handler: (request, response) => {
245
+ if (request.method === 'OPTIONS') {
246
+ response.writeHead(204, headers)
247
+ response.end()
248
+ return
249
+ }
250
+ if (request.method !== 'POST' && request.method !== 'HEAD') {
251
+ send(405, { ok: false, error: 'method' }, request, response)
252
+ return
253
+ }
254
+ if (!matchesToken(presentedToken(request), token)) {
255
+ send(401, { ok: false, error: 'token' }, request, response)
256
+ return
257
+ }
258
+ if (request.method === 'HEAD') {
259
+ send(200, { ok: true }, request, response)
260
+ return
261
+ }
262
+
263
+ readJson(request)
264
+ .then(async (body) => {
265
+ const errors = validateSessionCreateRequest(body)
266
+ if (errors.length > 0) {
267
+ send(400, { ok: false, error: 'request', message: errors.join('; ') }, request, response)
268
+ return
269
+ }
270
+ const value = await provisioner.createSession(body)
271
+ send(200, { ok: true, ...value }, request, response)
272
+ })
273
+ .catch((error) => {
274
+ // A Host service refusing the operation is the expected failure
275
+ // (missing registry, unusable path); answer it, do not log it twice.
276
+ send(500, { ok: false, error: 'create', message: messageOf(error) }, request, response)
277
+ })
278
+ },
279
+ })
280
+ }
281
+
282
+ /** Accept the token from a bearer header, the dedicated header, or the query string. */
283
+ function presentedToken(request) {
284
+ const header = request.headers?.authorization
285
+ if (typeof header === 'string' && header.toLowerCase().startsWith('bearer ')) return header.slice(7).trim()
286
+ const custom = request.headers?.['x-anno-token']
287
+ if (typeof custom === 'string' && custom !== '') return custom
288
+ try {
289
+ return new URL(request.url ?? '/', 'http://127.0.0.1').searchParams.get('token') ?? ''
290
+ } catch {
291
+ return ''
292
+ }
293
+ }
294
+
295
+ /** @param {any} request */
296
+ function readJson(request) {
297
+ return new Promise((resolve, reject) => {
298
+ let size = 0
299
+ const chunks = []
300
+ request.on('data', (chunk) => {
301
+ size += chunk.length
302
+ if (size > LIMITS.createBodyChars) {
303
+ reject(new Error('body too large'))
304
+ request.destroy()
305
+ return
306
+ }
307
+ chunks.push(chunk)
308
+ })
309
+ request.on('end', () => {
310
+ try {
311
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
312
+ } catch (error) {
313
+ reject(error)
314
+ }
315
+ })
316
+ request.on('error', reject)
317
+ })
318
+ }
319
+
320
+ /** @param {unknown} error */
321
+ function messageOf(error) {
322
+ return error instanceof Error ? error.message : String(error)
323
+ }