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

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/auth.js ADDED
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Explicit, bilateral session-pair authorization for collaboration messaging.
3
+ *
4
+ * A grant is directional: `from` authorizes communicating with `to`. Two
5
+ * sessions may exchange messages only when BOTH directions exist. A single
6
+ * side's grant is therefore never sufficient, and the management page shows
7
+ * such one-sided grants as pending until the other side is granted.
8
+ */
9
+ import path from 'node:path'
10
+
11
+ import { fileStamp, isSessionId, readStateJson, withFileLock, writeJson } from './layout.js'
12
+
13
+ /** Stable key for a directed grant. */
14
+ export function grantKey(from, to) {
15
+ return `${from}\u0000${to}`
16
+ }
17
+
18
+ /** Stable key for an unordered pair; stored with the smaller id first. */
19
+ export function pairKey(a, b) {
20
+ return [a, b].sort().join('\u0000')
21
+ }
22
+
23
+ function normalizeGrants(raw) {
24
+ const grants = []
25
+ const seen = new Set()
26
+ const add = (entry) => {
27
+ if (!isSessionId(entry?.from) || !isSessionId(entry?.to) || entry.from === entry.to) return
28
+ const key = grantKey(entry.from, entry.to)
29
+ if (seen.has(key)) return
30
+ seen.add(key)
31
+ grants.push({
32
+ from: entry.from,
33
+ to: entry.to,
34
+ createdAt: typeof entry.createdAt === 'number' ? entry.createdAt : Date.now(),
35
+ updatedAt: typeof entry.updatedAt === 'number' ? entry.updatedAt : Date.now(),
36
+ ...(typeof entry.authorizedBy === 'string' ? { authorizedBy: entry.authorizedBy } : {}),
37
+ })
38
+ }
39
+ if (Array.isArray(raw?.grants)) {
40
+ for (const entry of raw.grants) add(entry)
41
+ return grants
42
+ }
43
+ // Version 1 stored one symmetric pair record. Preserve it as both
44
+ // directions so an already-authorized pair keeps working.
45
+ if (Array.isArray(raw?.pairs)) {
46
+ for (const entry of raw.pairs) {
47
+ if (!isSessionId(entry?.a) || !isSessionId(entry?.b) || entry.a === entry.b) continue
48
+ add({ from: entry.a, to: entry.b, createdAt: entry.createdAt, updatedAt: entry.updatedAt, authorizedBy: entry.authorizedBy })
49
+ add({ from: entry.b, to: entry.a, createdAt: entry.createdAt, updatedAt: entry.updatedAt, authorizedBy: entry.authorizedBy })
50
+ }
51
+ }
52
+ return grants
53
+ }
54
+
55
+ /** Durable set of directed authorization grants. */
56
+ export class AuthorizationStore {
57
+ constructor(file) {
58
+ this.file = file
59
+ this.state = undefined
60
+ }
61
+
62
+ read() {
63
+ const stamp = fileStamp(this.file)
64
+ if (this.state !== undefined && this.stamp === stamp) return this.state
65
+ this.state = { version: 2, grants: normalizeGrants(readStateJson(this.file)) }
66
+ this.stamp = stamp
67
+ return this.state
68
+ }
69
+
70
+ write(state) {
71
+ this.state = state
72
+ writeJson(this.file, { version: 2, grants: state.grants })
73
+ this.stamp = fileStamp(this.file)
74
+ }
75
+
76
+ /** Every directional grant, for the management page and audit. */
77
+ listGrants() {
78
+ return this.read().grants
79
+ .map(entry => ({ ...entry }))
80
+ .sort((left, right) => (left.createdAt ?? 0) - (right.createdAt ?? 0))
81
+ }
82
+
83
+ /** Pairs where both directions exist. */
84
+ listPairs() {
85
+ const grants = this.read().grants
86
+ const keys = new Set(grants.map(entry => grantKey(entry.from, entry.to)))
87
+ const pairs = []
88
+ const seen = new Set()
89
+ for (const grant of grants) {
90
+ if (!keys.has(grantKey(grant.to, grant.from))) continue
91
+ const key = pairKey(grant.from, grant.to)
92
+ if (seen.has(key)) continue
93
+ seen.add(key)
94
+ const [a, b] = [grant.from, grant.to].sort()
95
+ const reverse = grants.find(entry => entry.from === b && entry.to === a)
96
+ pairs.push({
97
+ a,
98
+ b,
99
+ createdAt: Math.min(grant.createdAt ?? 0, reverse?.createdAt ?? 0),
100
+ updatedAt: Math.max(grant.updatedAt ?? 0, reverse?.updatedAt ?? 0),
101
+ })
102
+ }
103
+ return pairs
104
+ }
105
+
106
+ /** One-sided grants whose reverse direction is still missing. */
107
+ listPending() {
108
+ const grants = this.read().grants
109
+ const keys = new Set(grants.map(entry => grantKey(entry.from, entry.to)))
110
+ return grants
111
+ .filter(grant => !keys.has(grantKey(grant.to, grant.from)))
112
+ .map(grant => ({ ...grant }))
113
+ .sort((left, right) => (left.createdAt ?? 0) - (right.createdAt ?? 0))
114
+ }
115
+
116
+ hasGrant(from, to) {
117
+ if (!isSessionId(from) || !isSessionId(to) || from === to) return false
118
+ return this.read().grants.some(entry => entry.from === from && entry.to === to)
119
+ }
120
+
121
+ /** Communication requires both directions. */
122
+ isAuthorized(a, b) {
123
+ if (!isSessionId(a) || !isSessionId(b) || a === b) return false
124
+ return this.hasGrant(a, b) && this.hasGrant(b, a)
125
+ }
126
+
127
+ grant(from, to, authorizedBy, now = Date.now()) {
128
+ if (!isSessionId(from) || !isSessionId(to) || from === to) {
129
+ throw new Error('grant requires two different session ids')
130
+ }
131
+ return withFileLock(this.file, () => {
132
+ this.state = undefined
133
+ const state = this.read()
134
+ const existing = state.grants.find(entry => entry.from === from && entry.to === to)
135
+ if (existing !== undefined) {
136
+ if (typeof authorizedBy === 'string') existing.authorizedBy = authorizedBy
137
+ existing.updatedAt = now
138
+ this.write(state)
139
+ return existing
140
+ }
141
+ const grant = {
142
+ from,
143
+ to,
144
+ createdAt: now,
145
+ updatedAt: now,
146
+ ...(typeof authorizedBy === 'string' ? { authorizedBy } : {}),
147
+ }
148
+ state.grants.push(grant)
149
+ this.write(state)
150
+ return grant
151
+ })
152
+ }
153
+
154
+ /** Grant both directions in one explicit bilateral action. */
155
+ authorize(a, b, authorizedBy, now = Date.now()) {
156
+ if (!isSessionId(a) || !isSessionId(b) || a === b) {
157
+ throw new Error('authorize requires two different session ids')
158
+ }
159
+ this.grant(a, b, authorizedBy, now)
160
+ this.grant(b, a, authorizedBy, now)
161
+ return this.listPairs().find(pair => pairKey(pair.a, pair.b) === pairKey(a, b))
162
+ }
163
+
164
+ revokeGrant(from, to) {
165
+ return withFileLock(this.file, () => {
166
+ this.state = undefined
167
+ const state = this.read()
168
+ const next = state.grants.filter(entry => !(entry.from === from && entry.to === to))
169
+ if (next.length === state.grants.length) return false
170
+ this.write({ ...state, grants: next })
171
+ return true
172
+ })
173
+ }
174
+
175
+ /** Revoke both directions. */
176
+ revoke(a, b) {
177
+ if (!isSessionId(a) || !isSessionId(b)) return false
178
+ const revokedOne = this.revokeGrant(a, b)
179
+ const revokedOther = this.revokeGrant(b, a)
180
+ return revokedOne || revokedOther
181
+ }
182
+ }
183
+
184
+ /** Path of the authorization document beside the session registry. */
185
+ export function authorizationPathFor(registryPath) {
186
+ return path.join(path.dirname(registryPath), 'authorization.json')
187
+ }