@xmodelin/dsh-collab-sessions 0.0.0-stage → 0.0.1

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/lib/layout.js ADDED
@@ -0,0 +1,821 @@
1
+ /**
2
+ * Filesystem protocol for collaboration sessions.
3
+ *
4
+ * Every collaboration session keeps its Workspace and uses one per-session
5
+ * working directory inside it:
6
+ *
7
+ * <workspace>/.dsh-collab/sessions/<sessionId>/
8
+ * comm/<peerSessionId>/credential.json shared secret for this pair
9
+ * comm/<peerSessionId>/inbox/*.json unread inbound messages
10
+ * comm/<peerSessionId>/outbox/*.json messages this session sent
11
+ * comm/<peerSessionId>/archive/inbox/*.json read inbound messages
12
+ * comm/<peerSessionId>/archive/outbox/*.json explicitly archived sent messages
13
+ * comm/<peerSessionId>/rejected/ quarantined invalid messages
14
+ * private/ session-only data
15
+ *
16
+ * `comm` is the deliberately shared boundary; `private` must stay unreadable
17
+ * from every other session. The helpers here are pure Node code so they can be
18
+ * unit-tested without a running Harness.
19
+ */
20
+ import crypto from 'node:crypto'
21
+ import fs from 'node:fs'
22
+ import os from 'node:os'
23
+ import path from 'node:path'
24
+
25
+ /** Directory names that mark a collaboration workspace. */
26
+ export const SUBDIR = '.dsh-collab'
27
+
28
+ /** Maximum message body accepted by either side. */
29
+ export const MAX_MESSAGE_BYTES = 64 * 1024
30
+
31
+ /** Maximum stored inbox file read by the receiver. */
32
+ const MAX_STORED_MESSAGE_BYTES = 256 * 1024
33
+
34
+ /** Maximum number of inbox files considered per pair in one read. */
35
+ const MAX_INBOX_FILES = 200
36
+
37
+ /** Maximum message ids retained by the per-session replay ledger. */
38
+ const MAX_SEEN_IDS = 5000
39
+
40
+ /** Session ids become directory names, so accept only one safe path segment. */
41
+ const SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
42
+
43
+ /** Structural spelling of one collaboration session work directory. */
44
+ const SESSION_STRUCTURE = /(?:^|[\\/])\.dsh-collab[\\/]sessions[\\/]([^\\/]+)(?:[\\/]|$)/i
45
+
46
+ /** Default location of the derived session registry. */
47
+ export function defaultRegistryPath() {
48
+ const configured = process.env.DSH_HOME
49
+ const home = typeof configured === 'string' && configured.trim().length > 0
50
+ ? configured.trim()
51
+ : path.join(os.homedir(), '.dsh')
52
+ return path.join(home, 'collab', 'registry.json')
53
+ }
54
+
55
+ /** Whether a value is a safe, DSH-shaped session id. */
56
+ export function isSessionId(value) {
57
+ return typeof value === 'string' && SESSION_ID_PATTERN.test(value)
58
+ }
59
+
60
+ /** Recursively create a directory and enforce its mode where the platform allows it. */
61
+ export function mkdirp(directory, mode = 0o700) {
62
+ fs.mkdirSync(directory, { recursive: true, mode })
63
+ try { fs.chmodSync(directory, mode) } catch { /* platform without POSIX modes */ }
64
+ }
65
+
66
+ /** Cheap identity of one state file, used to invalidate parsed caches. */
67
+ export function fileStamp(file) {
68
+ try {
69
+ const stat = fs.statSync(file)
70
+ return `${stat.ino}:${String(stat.size)}:${String(stat.mtimeMs)}`
71
+ } catch {
72
+ return 'missing'
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Read a durable state document. A malformed document is moved aside so a
78
+ * later write cannot silently replace evidence of corruption with an empty store.
79
+ */
80
+ export function readStateJson(file) {
81
+ if (!fs.existsSync(file)) return undefined
82
+ try {
83
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
84
+ } catch (error) {
85
+ const backup = `${file}.corrupt-${Date.now()}`
86
+ try { fs.renameSync(file, backup) } catch { /* preserve the original path if the backup fails */ }
87
+ const failure = new Error(`collaboration state is corrupted: ${file}; backup: ${backup}`)
88
+ failure.code = 'STATE_CORRUPT'
89
+ failure.cause = error
90
+ throw failure
91
+ }
92
+ }
93
+
94
+ /** Whether a path is an existing directory. */
95
+ export function isDirectory(target) {
96
+ try { return fs.statSync(target).isDirectory() } catch { return false }
97
+ }
98
+
99
+ /** Read JSON, returning undefined for a missing or malformed file. */
100
+ export function readJson(file) {
101
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return undefined }
102
+ }
103
+
104
+ /** Create one JSON file exclusively; an existing file is never replaced. */
105
+ function writeJsonExclusive(file, value, mode = 0o600) {
106
+ mkdirp(path.dirname(file), 0o700)
107
+ fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', flag: 'wx', mode })
108
+ }
109
+
110
+ /** Atomically write one JSON file with owner-only permissions. */
111
+ export function writeJson(file, value, mode = 0o600) {
112
+ mkdirp(path.dirname(file), 0o700)
113
+ const temporary = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`
114
+ const descriptor = fs.openSync(temporary, 'w', mode)
115
+ try {
116
+ fs.writeFileSync(descriptor, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8' })
117
+ try { fs.fsyncSync(descriptor) } catch { /* filesystems without fsync support */ }
118
+ } finally {
119
+ fs.closeSync(descriptor)
120
+ }
121
+ fs.renameSync(temporary, file)
122
+ try { fs.chmodSync(file, mode) } catch { /* platform without POSIX modes */ }
123
+ }
124
+
125
+ /** The collaboration working directory for one session. */
126
+ export function sessionWorkdir(originalCwd, sessionId) {
127
+ if (!isSessionId(sessionId)) throw new Error(`invalid collaboration session id: ${String(sessionId)}`)
128
+ return path.join(originalCwd, SUBDIR, 'sessions', sessionId)
129
+ }
130
+
131
+ /** The workspace base above `<base>/.dsh-collab/sessions/<dir>`, when there is one. */
132
+ export function collabBaseOf(workdir) {
133
+ const resolved = path.resolve(workdir)
134
+ const match = /^(.*)[\\/]\.dsh-collab[\\/]sessions[\\/][^\\/]+$/i.exec(resolved)
135
+ return match === null ? undefined : match[1]
136
+ }
137
+
138
+ /** Whether a directory is already a dedicated collaboration workspace directory. */
139
+ export function isDedicatedCollabWorkdir(workdir) {
140
+ return typeof workdir === 'string' && collabBaseOf(workdir) !== undefined
141
+ }
142
+
143
+ /**
144
+ * Create or repair the `comm` and `private` layout at one exact directory.
145
+ * @returns the layout, including the private metadata record.
146
+ */
147
+ export function ensureLayoutAt({ workdir, originalCwd = workdir, sessionId, preset, now = Date.now() }) {
148
+ const resolvedWorkdir = path.resolve(workdir)
149
+ const commDir = path.join(resolvedWorkdir, 'comm')
150
+ const privateDir = path.join(resolvedWorkdir, 'private')
151
+ mkdirp(resolvedWorkdir, 0o700)
152
+ mkdirp(commDir, 0o700)
153
+ mkdirp(privateDir, 0o700)
154
+ // Keep the marker out of `git status` of the workspace that contains it.
155
+ const base = collabBaseOf(resolvedWorkdir) ?? path.resolve(originalCwd)
156
+ const ignoreFile = path.join(base, SUBDIR, '.gitignore')
157
+ if (!fs.existsSync(ignoreFile)) {
158
+ mkdirp(path.dirname(ignoreFile), 0o700)
159
+ fs.writeFileSync(ignoreFile, '*\n', { mode: 0o600 })
160
+ }
161
+ const metaFile = path.join(resolvedWorkdir, 'session.json')
162
+ const existing = readJson(metaFile)
163
+ const created = existing === undefined || existing.sessionId !== sessionId
164
+ const meta = !created
165
+ ? { ...existing, preset, updatedAt: now }
166
+ : {
167
+ version: 1,
168
+ sessionId,
169
+ preset,
170
+ originalCwd: path.resolve(originalCwd),
171
+ workdir: resolvedWorkdir,
172
+ createdAt: now,
173
+ updatedAt: now,
174
+ }
175
+ writeJson(metaFile, meta, 0o600)
176
+ const readmeFile = path.join(privateDir, 'README.md')
177
+ if (!fs.existsSync(readmeFile)) {
178
+ fs.writeFileSync(
179
+ readmeFile,
180
+ [
181
+ '# Private directory',
182
+ '',
183
+ 'Only this session may read or write this directory.',
184
+ 'Other sessions are denied by the collaboration tool guard; the directory is also mode 0700.',
185
+ '',
186
+ ].join('\n'),
187
+ { mode: 0o600 },
188
+ )
189
+ }
190
+ return { workdir: resolvedWorkdir, commDir, privateDir, meta, created }
191
+ }
192
+
193
+ /**
194
+ * Create or repair the nested layout used when a collab session runs inside a
195
+ * project workspace: `<originalCwd>/.dsh-collab/sessions/<sessionId>/`.
196
+ */
197
+ export function ensureSessionLayout({ originalCwd, sessionId, preset, now = Date.now() }) {
198
+ return ensureLayoutAt({
199
+ workdir: sessionWorkdir(originalCwd, sessionId),
200
+ originalCwd,
201
+ sessionId,
202
+ preset,
203
+ now,
204
+ })
205
+ }
206
+
207
+ /** Bounded lock wait; the default is intentionally short because the wait blocks the event loop. */
208
+ const lockDefaults = { timeoutMs: 1000, staleMs: 10000 }
209
+
210
+ /** Override the bounded lock defaults for this Host process. */
211
+ export function configureFileLocks({ timeoutMs, staleMs } = {}) {
212
+ if (Number.isFinite(Number(timeoutMs)) && Number(timeoutMs) > 0) lockDefaults.timeoutMs = Math.max(1, Number(timeoutMs))
213
+ if (Number.isFinite(Number(staleMs)) && Number(staleMs) > 0) lockDefaults.staleMs = Math.max(1, Number(staleMs))
214
+ }
215
+
216
+ /** Acquire a short-lived cross-process lock for one state document. */
217
+ export function withFileLock(file, operation, options = {}) {
218
+ const timeoutMs = Number.isFinite(Number(options.timeoutMs)) ? Math.max(1, Number(options.timeoutMs)) : lockDefaults.timeoutMs
219
+ const staleMs = Number.isFinite(Number(options.staleMs)) ? Math.max(1, Number(options.staleMs)) : lockDefaults.staleMs
220
+ const lock = `${file}.lock`
221
+ const started = Date.now()
222
+ mkdirp(path.dirname(file), 0o700)
223
+ while (true) {
224
+ try {
225
+ const descriptor = fs.openSync(lock, 'wx', 0o600)
226
+ try { fs.writeFileSync(descriptor, `${String(process.pid)}\n`) } finally { fs.closeSync(descriptor) }
227
+ break
228
+ } catch (error) {
229
+ if (error?.code !== 'EEXIST') throw error
230
+ try {
231
+ const age = Date.now() - fs.statSync(lock).mtimeMs
232
+ if (age > staleMs) fs.unlinkSync(lock)
233
+ } catch { /* the owner may have removed it */ }
234
+ if (Date.now() - started > timeoutMs) {
235
+ let holder = 'unknown'
236
+ try { holder = fs.readFileSync(lock, 'utf8').trim() || holder } catch { /* lock vanished */ }
237
+ throw new Error(`timed out after ${String(timeoutMs)}ms waiting for state lock: ${lock} (holder pid ${holder})`)
238
+ }
239
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10)
240
+ }
241
+ }
242
+ try {
243
+ return operation()
244
+ } finally {
245
+ try { fs.unlinkSync(lock) } catch { /* already removed */ }
246
+ }
247
+ }
248
+
249
+ /** Durable, derived index of collaboration sessions. */
250
+ export class SessionRegistry {
251
+ constructor(file) {
252
+ this.file = file
253
+ this.state = undefined
254
+ }
255
+
256
+ read() {
257
+ const stamp = fileStamp(this.file)
258
+ if (this.state !== undefined && this.stamp === stamp) return this.state
259
+ const raw = readStateJson(this.file)
260
+ const sessions = raw !== null && typeof raw === 'object' && raw.sessions !== null && typeof raw.sessions === 'object'
261
+ ? raw.sessions
262
+ : {}
263
+ this.state = { version: 1, sessions }
264
+ this.stamp = stamp
265
+ return this.state
266
+ }
267
+
268
+ write(state) {
269
+ this.state = state
270
+ writeJson(this.file, { version: 1, sessions: state.sessions })
271
+ this.stamp = fileStamp(this.file)
272
+ }
273
+
274
+ get(sessionId) {
275
+ return this.read().sessions[sessionId]
276
+ }
277
+
278
+ list() {
279
+ return Object.values(this.read().sessions)
280
+ .filter(entry => entry !== null && typeof entry === 'object' && isSessionId(entry.sessionId))
281
+ .sort((left, right) => (left.createdAt ?? 0) - (right.createdAt ?? 0))
282
+ }
283
+
284
+ upsert(entry) {
285
+ if (!isSessionId(entry.sessionId)) return
286
+ withFileLock(this.file, () => {
287
+ this.state = undefined
288
+ const state = this.read()
289
+ state.sessions[entry.sessionId] = { ...state.sessions[entry.sessionId], ...entry }
290
+ this.write(state)
291
+ })
292
+ }
293
+
294
+ remove(sessionId) {
295
+ withFileLock(this.file, () => {
296
+ this.state = undefined
297
+ const state = this.read()
298
+ if (state.sessions[sessionId] === undefined) return
299
+ delete state.sessions[sessionId]
300
+ this.write(state)
301
+ })
302
+ }
303
+
304
+ /** Merge sessions discovered under registered workspace directories. */
305
+ scanWorkspaces(workspacePaths) {
306
+ return withFileLock(this.file, () => {
307
+ this.state = undefined
308
+ const state = this.read()
309
+ let discovered = 0
310
+ let changed = false
311
+ for (const workspacePath of workspacePaths) {
312
+ const sessionsDir = path.join(workspacePath, SUBDIR, 'sessions')
313
+ let entries
314
+ try { entries = fs.readdirSync(sessionsDir, { withFileTypes: true }) } catch { continue }
315
+ const discoveredIds = new Set()
316
+ for (const entry of entries) {
317
+ if (!entry.isDirectory() || !isSessionId(entry.name)) continue
318
+ const workdir = path.join(sessionsDir, entry.name)
319
+ const meta = readJson(path.join(workdir, 'session.json'))
320
+ if (meta === undefined || meta.sessionId !== entry.name) continue
321
+ if (meta.preset !== 'collab' && meta.preset !== 'supervisor') continue
322
+ discoveredIds.add(entry.name)
323
+ const existing = state.sessions[entry.name]
324
+ if (existing === undefined) {
325
+ state.sessions[entry.name] = { ...meta, workdir }
326
+ discovered += 1
327
+ changed = true
328
+ continue
329
+ }
330
+ // A moved workspace or a changed preset must repair the derived entry,
331
+ // while preserving the live title maintained by session events.
332
+ const next = {
333
+ ...existing,
334
+ preset: meta.preset,
335
+ originalCwd: typeof meta.originalCwd === 'string' ? meta.originalCwd : existing.originalCwd,
336
+ workdir,
337
+ updatedAt: typeof meta.updatedAt === 'number' ? meta.updatedAt : existing.updatedAt,
338
+ }
339
+ if (next.preset !== existing.preset || next.originalCwd !== existing.originalCwd || next.workdir !== existing.workdir) {
340
+ state.sessions[entry.name] = next
341
+ changed = true
342
+ }
343
+ }
344
+ for (const [id, entry] of Object.entries(state.sessions)) {
345
+ if (typeof entry?.workdir !== 'string') continue
346
+ if (path.dirname(entry.workdir) !== sessionsDir) continue
347
+ if (discoveredIds.has(id)) continue
348
+ delete state.sessions[id]
349
+ changed = true
350
+ }
351
+ }
352
+ if (changed) this.write(state)
353
+ return discovered
354
+ })
355
+ }
356
+ }
357
+
358
+ /** Path of one peer's credential inside a session's `comm` directory. */
359
+ export function credentialPath(workdir, peerSessionId) {
360
+ if (!isSessionId(peerSessionId)) throw new Error(`invalid peer session id: ${String(peerSessionId)}`)
361
+ return path.join(workdir, 'comm', peerSessionId, 'credential.json')
362
+ }
363
+
364
+ /**
365
+ * Ensure both sides of a pair hold the same shared secret.
366
+ * The first caller generates it; later callers adopt the existing value.
367
+ */
368
+ function ensureCredentialUnlocked({ selfId, selfWorkdir, peerId, peerWorkdir, now = Date.now() }) {
369
+ if (!isSessionId(selfId) || !isSessionId(peerId)) throw new Error('invalid collaboration session id')
370
+ if (selfId === peerId) throw new Error('a session cannot talk to itself')
371
+ if (selfWorkdir === peerWorkdir) throw new Error('peer work directories must differ')
372
+ const ownFile = credentialPath(selfWorkdir, peerId)
373
+ const peerFile = credentialPath(peerWorkdir, selfId)
374
+ const own = readJson(ownFile)
375
+ const peer = readJson(peerFile)
376
+ if (typeof own?.token === 'string' && typeof peer?.token === 'string' && own.token !== peer.token) {
377
+ throw new Error(`credential mismatch for ${selfId} <-> ${peerId}; refusing to overwrite either copy`)
378
+ }
379
+ let token = typeof own?.token === 'string' && own.token.length > 0
380
+ ? own.token
381
+ : (typeof peer?.token === 'string' && peer.token.length > 0 ? peer.token : undefined)
382
+ if (token === undefined) token = crypto.randomBytes(32).toString('hex')
383
+ const ownRecord = {
384
+ version: 1,
385
+ ownerSessionId: selfId,
386
+ peerSessionId: peerId,
387
+ token,
388
+ createdAt: typeof own?.createdAt === 'number' ? own.createdAt : now,
389
+ updatedAt: now,
390
+ }
391
+ if (own?.token !== token) {
392
+ try {
393
+ writeJsonExclusive(ownFile, ownRecord)
394
+ } catch (error) {
395
+ if (error?.code !== 'EEXIST') throw error
396
+ const adopted = readJson(ownFile)
397
+ if (typeof adopted?.token !== 'string' || adopted.token.length === 0) {
398
+ throw new Error(`credential for ${selfId} <-> ${peerId} could not be created or adopted`)
399
+ }
400
+ token = adopted.token
401
+ if (typeof peer?.token === 'string' && peer.token !== token) {
402
+ throw new Error(`credential mismatch for ${selfId} <-> ${peerId}; refusing to overwrite either copy`)
403
+ }
404
+ }
405
+ }
406
+ if (peer?.token !== token) {
407
+ const peerRecord = {
408
+ version: 1,
409
+ ownerSessionId: peerId,
410
+ peerSessionId: selfId,
411
+ token,
412
+ createdAt: typeof peer?.createdAt === 'number' ? peer.createdAt : now,
413
+ updatedAt: now,
414
+ }
415
+ try {
416
+ writeJsonExclusive(peerFile, peerRecord)
417
+ } catch (error) {
418
+ if (error?.code !== 'EEXIST') throw error
419
+ const adopted = readJson(peerFile)
420
+ if (adopted?.token !== token) {
421
+ throw new Error(`credential mismatch for ${selfId} <-> ${peerId}; refusing to overwrite either copy`)
422
+ }
423
+ }
424
+ }
425
+ return token
426
+ }
427
+
428
+ /**
429
+ * Serialize the first-contact credential write for both directions of a pair.
430
+ * Both sides acquire the same pair of lock files in lexicographic order.
431
+ */
432
+ export function ensureCredential(args) {
433
+ const { selfId, selfWorkdir, peerId, peerWorkdir } = args
434
+ const locks = [
435
+ credentialPath(selfWorkdir, peerId),
436
+ credentialPath(peerWorkdir, selfId),
437
+ ].sort()
438
+ return withFileLock(locks[0], () => withFileLock(locks[1], () => ensureCredentialUnlocked(args)))
439
+ }
440
+
441
+ const MESSAGE_KINDS = new Set(['chat', 'request', 'task'])
442
+
443
+ function macInput(message) {
444
+ if (typeof message.kind === 'string') {
445
+ return `${message.id}\n${message.from}\n${message.to}\n${message.createdAt}\n${message.kind}\n${message.text}`
446
+ }
447
+ return `${message.id}\n${message.from}\n${message.to}\n${message.createdAt}\n${message.text}`
448
+ }
449
+
450
+ /** Authenticate one message with its pair secret. */
451
+ export function signMessage(token, message) {
452
+ return crypto.createHmac('sha256', token).update(macInput(message)).digest('hex')
453
+ }
454
+
455
+ function verifyMessage(token, message, peerId, selfId) {
456
+ if (typeof token !== 'string' || token.length === 0) return false
457
+ if (message === null || typeof message !== 'object') return false
458
+ if (typeof message.id !== 'string' || message.id.length === 0 || message.id.length > 128) return false
459
+ if (message.from !== peerId || message.to !== selfId) return false
460
+ if (typeof message.text !== 'string' || message.text.length === 0) return false
461
+ if (message.kind !== undefined && !MESSAGE_KINDS.has(message.kind)) return false
462
+ if (typeof message.createdAt !== 'number' || !Number.isFinite(message.createdAt)) return false
463
+ if (typeof message.mac !== 'string' || message.mac.length !== 64) return false
464
+ const expected = Buffer.from(signMessage(token, message), 'hex')
465
+ const actual = Buffer.from(message.mac, 'hex')
466
+ return expected.length === actual.length && crypto.timingSafeEqual(expected, actual)
467
+ }
468
+
469
+ function quarantine(file, workdir, peerId) {
470
+ try {
471
+ const targetDir = path.join(workdir, 'comm', peerId, 'rejected')
472
+ mkdirp(targetDir, 0o700)
473
+ let target = path.join(targetDir, path.basename(file))
474
+ if (fs.existsSync(target)) target = `${target}.${crypto.randomBytes(3).toString('hex')}`
475
+ fs.renameSync(file, target)
476
+ } catch {
477
+ // Best effort: a file that cannot be quarantined is simply skipped.
478
+ }
479
+ }
480
+
481
+ /** Move every regular file from one directory into another, then remove the empty source. */
482
+ function moveFiles(fromDir, toDir) {
483
+ let entries
484
+ try { entries = fs.readdirSync(fromDir, { withFileTypes: true }) } catch { return }
485
+ if (entries.length === 0) {
486
+ try { fs.rmdirSync(fromDir) } catch { /* best effort */ }
487
+ return
488
+ }
489
+ mkdirp(toDir, 0o700)
490
+ for (const entry of entries) {
491
+ if (!entry.isFile()) continue
492
+ const source = path.join(fromDir, entry.name)
493
+ let target = path.join(toDir, entry.name)
494
+ if (fs.existsSync(target)) target = `${target}.${crypto.randomBytes(3).toString('hex')}`
495
+ try { fs.renameSync(source, target) } catch { /* leave the file for a later retry */ }
496
+ }
497
+ try { fs.rmdirSync(fromDir) } catch { /* non-empty leftovers stay in place */ }
498
+ }
499
+
500
+ /**
501
+ * Migrate the legacy `read/` directory into `archive/inbox/`. Normal
502
+ * `outbox/` messages stay in place; an `archive/outbox/` present from the
503
+ * earlier bulk migration is restored to `outbox/` so sent messages are not
504
+ * silently archived.
505
+ */
506
+ function migratePairLayout(pairDir) {
507
+ const archive = path.join(pairDir, 'archive')
508
+ if (fs.existsSync(path.join(pairDir, 'read'))) moveFiles(path.join(pairDir, 'read'), path.join(archive, 'inbox'))
509
+ const archivedOutbox = path.join(archive, 'outbox')
510
+ if (fs.existsSync(archivedOutbox)) moveFiles(archivedOutbox, path.join(pairDir, 'outbox'))
511
+ }
512
+
513
+ /**
514
+ * Write one authenticated message into both sessions' pair directories.
515
+ * The sender keeps the outbox copy; the receiver gets the inbox copy.
516
+ */
517
+ export function sendMessage({ selfId, selfWorkdir, peerId, peerWorkdir, kind = 'chat', text, now = Date.now() }) {
518
+ if (typeof text !== 'string' || text.trim().length === 0) throw new Error('message text must not be empty')
519
+ if (Buffer.byteLength(text) > MAX_MESSAGE_BYTES) throw new Error('message is larger than 64 KiB')
520
+ if (!MESSAGE_KINDS.has(kind)) throw new Error(`invalid message kind: ${String(kind)}`)
521
+ const token = ensureCredential({ selfId, selfWorkdir, peerId, peerWorkdir, now })
522
+ const message = {
523
+ version: 1,
524
+ id: crypto.randomUUID(),
525
+ from: selfId,
526
+ to: peerId,
527
+ kind,
528
+ createdAt: now,
529
+ text,
530
+ }
531
+ message.mac = signMessage(token, message)
532
+ const fileName = `${String(now).padStart(13, '0')}-${message.id}.json`
533
+ const selfPairDir = path.join(selfWorkdir, 'comm', peerId)
534
+ migratePairLayout(selfPairDir)
535
+ writeJson(path.join(selfPairDir, 'outbox', fileName), message)
536
+ writeJson(path.join(peerWorkdir, 'comm', selfId, 'inbox', fileName), message)
537
+ return message
538
+ }
539
+
540
+ /** Count files waiting in one pair's inbox. */
541
+ export function inboxCount(workdir, peerId) {
542
+ const inbox = path.join(workdir, 'comm', peerId, 'inbox')
543
+ try {
544
+ return fs.readdirSync(inbox).filter(name => name.endsWith('.json')).length
545
+ } catch {
546
+ return 0
547
+ }
548
+ }
549
+
550
+ /**
551
+ * Read every authenticated inbox message for one session.
552
+ * @returns accepted messages with their files, plus a count of rejected files.
553
+ */
554
+ export function listInbox({ selfId, selfWorkdir }) {
555
+ const commDir = path.join(selfWorkdir, 'comm')
556
+ let pairs
557
+ try { pairs = fs.readdirSync(commDir, { withFileTypes: true }) } catch { return { messages: [], rejected: 0, truncated: 0 } }
558
+ const messages = []
559
+ let rejected = 0
560
+ let truncated = 0
561
+ const seenRaw = readJson(path.join(commDir, '.seen.json'))
562
+ const seen = new Set(Array.isArray(seenRaw?.ids) ? seenRaw.ids.filter(id => typeof id === 'string') : [])
563
+ for (const pair of pairs) {
564
+ if (!pair.isDirectory() || !isSessionId(pair.name) || pair.name === selfId) continue
565
+ const peerId = pair.name
566
+ const pairDir = path.join(commDir, peerId)
567
+ migratePairLayout(pairDir)
568
+ const credential = readJson(credentialPath(selfWorkdir, peerId))
569
+ const inbox = path.join(pairDir, 'inbox')
570
+ let files
571
+ try { files = fs.readdirSync(inbox) } catch { continue }
572
+ const jsonFiles = files.filter(fileName => fileName.endsWith('.json')).sort()
573
+ if (jsonFiles.length > MAX_INBOX_FILES) truncated += jsonFiles.length - MAX_INBOX_FILES
574
+ for (const fileName of jsonFiles.slice(0, MAX_INBOX_FILES)) {
575
+ const file = path.join(inbox, fileName)
576
+ let size = 0
577
+ try { size = fs.statSync(file).size } catch { continue }
578
+ if (size > MAX_STORED_MESSAGE_BYTES) {
579
+ quarantine(file, selfWorkdir, peerId)
580
+ rejected += 1
581
+ continue
582
+ }
583
+ const message = readJson(file)
584
+ if (!verifyMessage(credential?.token, message, peerId, selfId)) {
585
+ quarantine(file, selfWorkdir, peerId)
586
+ rejected += 1
587
+ continue
588
+ }
589
+ if (seen.has(message.id)) {
590
+ quarantine(file, selfWorkdir, peerId)
591
+ rejected += 1
592
+ continue
593
+ }
594
+ messages.push({ file, peerId, message })
595
+ }
596
+ }
597
+ messages.sort((left, right) => left.message.createdAt - right.message.createdAt || left.message.id.localeCompare(right.message.id))
598
+ return { messages, rejected, truncated }
599
+ }
600
+
601
+ /** Move one read inbox message to its pair's `archive/inbox/` directory. */
602
+ /** Migrate every pair directory of one session into the archive split. */
603
+ export function migrateSessionArchive(workdir) {
604
+ const commDir = path.join(workdir, 'comm')
605
+ let pairs
606
+ try { pairs = fs.readdirSync(commDir, { withFileTypes: true }) } catch { return }
607
+ for (const pair of pairs) {
608
+ if (!pair.isDirectory() || !isSessionId(pair.name)) continue
609
+ migratePairLayout(path.join(commDir, pair.name))
610
+ }
611
+ }
612
+
613
+ /** Move one read inbox message to its pair's `archive/inbox/` directory. */
614
+ export function markRead(file, workdir) {
615
+ const pairDir = path.dirname(path.dirname(file))
616
+ migratePairLayout(pairDir)
617
+ const message = readJson(file)
618
+ const archiveDir = path.join(pairDir, 'archive', 'inbox')
619
+ mkdirp(archiveDir, 0o700)
620
+ let target = path.join(archiveDir, path.basename(file))
621
+ if (fs.existsSync(target)) target = `${target}.${crypto.randomBytes(3).toString('hex')}`
622
+ fs.renameSync(file, target)
623
+ if (typeof message?.id === 'string' && message.id.length > 0) {
624
+ const seenFile = path.join(path.dirname(pairDir), '.seen.json')
625
+ try {
626
+ withFileLock(seenFile, () => {
627
+ const raw = readJson(seenFile)
628
+ const seen = new Set(Array.isArray(raw?.ids) ? raw.ids.filter(id => typeof id === 'string') : [])
629
+ seen.add(message.id)
630
+ writeJson(seenFile, { version: 1, ids: [...seen].slice(-MAX_SEEN_IDS) }, 0o600)
631
+ })
632
+ } catch { /* a ledger failure must not prevent acknowledging the message */ }
633
+ }
634
+ return target
635
+ }
636
+
637
+ function comparablePath(value) {
638
+ const resolved = path.resolve(value)
639
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved
640
+ }
641
+
642
+ function isInside(candidate, root) {
643
+ const resolvedCandidate = comparablePath(candidate)
644
+ const resolvedRoot = comparablePath(root)
645
+ return resolvedCandidate === resolvedRoot || resolvedCandidate.startsWith(`${resolvedRoot}${path.sep}`)
646
+ }
647
+
648
+ /** Shell-ish path tokens used to inspect a bash command. */
649
+ export function bashPathCandidates(command) {
650
+ const tokens = []
651
+ const pattern = /"([^"]*)"|'([^']*)'|([^\s;&|<>()`]+)/g
652
+ let match
653
+ while ((match = pattern.exec(command)) !== null) {
654
+ let token = match[1] ?? match[2] ?? match[3]
655
+ if (token === undefined || token.length === 0) continue
656
+ if (token.startsWith('-')) continue
657
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)) token = token.slice(token.indexOf('=') + 1)
658
+ if (token.length === 0) continue
659
+ if (token.includes('/') || token.includes('\\') || token === '..' || token === '~' || token.startsWith('~/')) {
660
+ tokens.push(token)
661
+ }
662
+ }
663
+ return tokens
664
+ }
665
+
666
+ function expandToken(token, selfWorkdir) {
667
+ if (token === '~') return os.homedir()
668
+ if (token.startsWith('~/')) return path.join(os.homedir(), token.slice(2))
669
+ return path.resolve(selfWorkdir, token)
670
+ }
671
+
672
+ /** Resolve symlinks for an existing path, or for the existing parent of a new one. */
673
+ export function canonicalPath(target) {
674
+ const resolved = path.resolve(target)
675
+ try { return fs.realpathSync.native(resolved) } catch { /* not existing */ }
676
+ try {
677
+ return path.join(fs.realpathSync.native(path.dirname(resolved)), path.basename(resolved))
678
+ } catch {
679
+ return resolved
680
+ }
681
+ }
682
+
683
+ /**
684
+ * Detect an attempt to touch another session's work directory (comm or private).
685
+ * @returns the offending peer id and input, or undefined.
686
+ */
687
+ export function findForeignSessionAccess(values, { selfId, selfWorkdir, selfLayoutWorkdir, roots = [] }) {
688
+ for (const value of values) {
689
+ if (typeof value !== 'string' || value.length === 0 || value.length > 8192) continue
690
+ const resolved = expandToken(value, selfWorkdir)
691
+ const canonical = canonicalPath(resolved)
692
+ // A wildcard segment under the shared sessions directory can expand into
693
+ // every peer's private/comm, so it is not a harmless literal. Allow only
694
+ // wildcards whose literal prefix stays inside this session's own layout.
695
+ if (/[*?[\]]/.test(value) && (/\.dsh-collab[\\/]sessions[\\/]/i.test(value) || /\.dsh-collab[\\/]sessions[\\/]/i.test(canonical))) {
696
+ const literalPrefix = value.split(/[*?[\]]/)[0]
697
+ const resolvedPrefix = expandToken(literalPrefix, selfWorkdir)
698
+ const canonicalPrefix = canonicalPath(resolvedPrefix)
699
+ const ownLayout = selfLayoutWorkdir ?? selfWorkdir
700
+ const canonicalOwnLayout = canonicalPath(ownLayout)
701
+ if (!isInside(resolvedPrefix, ownLayout) && !isInside(canonicalPrefix, canonicalOwnLayout)) {
702
+ return { sessionId: '<wildcard>', value }
703
+ }
704
+ }
705
+ // The caller's own layout is never foreign, even when its directory name is
706
+ // a generated token rather than the session id.
707
+ if (typeof selfLayoutWorkdir === 'string') {
708
+ const canonicalLayout = canonicalPath(selfLayoutWorkdir)
709
+ if (
710
+ isInside(resolved, selfLayoutWorkdir)
711
+ || isInside(canonical, selfLayoutWorkdir)
712
+ || isInside(canonical, canonicalLayout)
713
+ ) {
714
+ continue
715
+ }
716
+ }
717
+ // Script bodies and quoted prose can mention a path without being one.
718
+ // Wildcard segments are left to the pattern check, which gives a clearer
719
+ // denial than treating `*` as a session id.
720
+ const concrete = segment => segment !== undefined && !/[*?[\]]/.test(segment)
721
+ if (!/[\s<>]/.test(value)) {
722
+ const structural = SESSION_STRUCTURE.exec(value)
723
+ if (structural !== null && concrete(structural[1]) && structural[1] !== selfId) {
724
+ return { sessionId: structural[1], value }
725
+ }
726
+ const canonicalStructural = SESSION_STRUCTURE.exec(canonical)
727
+ if (canonicalStructural !== null && concrete(canonicalStructural[1]) && canonicalStructural[1] !== selfId) {
728
+ return { sessionId: canonicalStructural[1], value }
729
+ }
730
+ }
731
+ for (const root of roots) {
732
+ if (root.sessionId === selfId) continue
733
+ const canonicalRoot = canonicalPath(root.workdir)
734
+ if (
735
+ isInside(resolved, root.workdir)
736
+ || isInside(resolved, canonicalRoot)
737
+ || isInside(canonical, root.workdir)
738
+ || isInside(canonical, canonicalRoot)
739
+ ) {
740
+ return { sessionId: root.sessionId, value }
741
+ }
742
+ }
743
+ }
744
+ return undefined
745
+ }
746
+
747
+ function isStrictAncestor(candidate, child) {
748
+ const resolvedCandidate = comparablePath(candidate)
749
+ const resolvedChild = comparablePath(child)
750
+ return resolvedChild.startsWith(`${resolvedCandidate}${path.sep}`)
751
+ }
752
+
753
+ /**
754
+ * Detect a directory whose recursive search would include another session's
755
+ * work directory. Such a root is refused for search and shell execution.
756
+ */
757
+ export function findForeignAncestorAccess(values, { selfId, selfWorkdir, roots = [] }) {
758
+ for (const value of values) {
759
+ if (typeof value !== 'string' || value.length === 0 || value.length > 8192) continue
760
+ const resolved = expandToken(value, selfWorkdir)
761
+ const canonical = canonicalPath(resolved)
762
+ for (const root of roots) {
763
+ if (root.sessionId === selfId) continue
764
+ const canonicalRoot = canonicalPath(root.workdir)
765
+ if (isStrictAncestor(resolved, root.workdir) || isStrictAncestor(canonical, canonicalRoot)) {
766
+ return { sessionId: root.sessionId, value }
767
+ }
768
+ }
769
+ }
770
+ return undefined
771
+ }
772
+
773
+
774
+ /** Discover sibling session work directories next to one session's layout. */
775
+ export function discoverSiblingWorkdirs(workdir) {
776
+ const resolved = path.resolve(workdir)
777
+ const marker = `${path.sep}${SUBDIR}${path.sep}sessions${path.sep}`
778
+ const index = resolved.lastIndexOf(marker)
779
+ if (index < 0) return []
780
+ const base = resolved.slice(0, index + marker.length - 1)
781
+ let entries
782
+ try { entries = fs.readdirSync(base, { withFileTypes: true }) } catch { return [] }
783
+ const siblings = []
784
+ for (const entry of entries) {
785
+ if (!entry.isDirectory() || !isSessionId(entry.name)) continue
786
+ siblings.push({ sessionId: entry.name, workdir: path.join(base, entry.name) })
787
+ }
788
+ return siblings
789
+ }
790
+
791
+ /** Detect a glob pattern that could expand into another session's work directory. */
792
+ export function findSuspiciousSearchPattern(value, { selfId, roots = [] }) {
793
+ if (typeof value !== 'string' || value.length === 0 || value.length > 8192) return undefined
794
+ // A path pattern, not a code blob or prose that happens to contain `..`.
795
+ if (!/[\\/]/.test(value)) return undefined
796
+ if (/[.*?[]/.test(value) && /\.\./.test(value) && /(private|comm|\.dsh-collab)/i.test(value)) {
797
+ return { sessionId: '<pattern>', value }
798
+ }
799
+ return undefined
800
+ }
801
+
802
+ /** Inspect a shell command, including `cd`-then-relative forms. */
803
+ export function findForeignSessionAccessInCommand(command, options) {
804
+ const tokens = bashPathCandidates(command)
805
+ const hit = findForeignSessionAccess(tokens, options)
806
+ if (hit !== undefined) return hit
807
+ if (options.checkAncestors !== false) {
808
+ const ancestor = findForeignAncestorAccess(tokens, options)
809
+ if (ancestor !== undefined) return ancestor
810
+ }
811
+ for (const token of tokens) {
812
+ if (/[\s<>]/.test(token) || !/[\\/]/.test(token)) continue
813
+ const suspicious = findSuspiciousSearchPattern(token, options)
814
+ if (suspicious !== undefined) return suspicious
815
+ }
816
+ const mentionsPrivate = /\bprivate\b/i.test(command)
817
+ if (!mentionsPrivate) return undefined
818
+ const foreign = options.roots.find(root => root.sessionId !== options.selfId && command.includes(root.sessionId))
819
+ if (foreign !== undefined) return { sessionId: foreign.sessionId, value: command }
820
+ return undefined
821
+ }