@restregular/dsh-memory 0.23.1 → 0.24.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.
@@ -0,0 +1,245 @@
1
+ /**
2
+ * 会话级作用域授权(grants)。
3
+ *
4
+ * 与「可见域」分开存储是刻意的:`visibility/<session>.json` 是**用户对会话策略**的
5
+ * 显式声明(可整份重置),而 grant 是 Agent 申请、用户批准出来的**例外**,需要
6
+ * grantId、主体、能力、到期、撤销与审计。混在一份文件里时,面板保存 / 恢复默认 /
7
+ * 撤销授权会互相误伤。
8
+ *
9
+ * 位置:`<storeDir>/grants/<safeName(session)>.json`,每个会话一个文件(与
10
+ * `visibility/` 同款并发取舍:按会话分文件,写入只碰自己那份,原子 rename)。
11
+ *
12
+ * 语义(0.24.0 / D3):
13
+ * - 只有 `duration: 'session'` 会落盘;`once` 继续走现有 allowed-once 审批,不持久化;
14
+ * - 只读 / 可写分开授权,互不推导;
15
+ * - 子 Agent 沿 parentSession 链继承(provider 负责解析链,本文件只管单会话);
16
+ * - `absolute` 下 grant **不生效**(硬隔离),由 authorize 负责判断,存储层不解释等级;
17
+ * - 作用域键被删除重建后,`scopeGeneration` 对不上即失效(S6)。
18
+ */
19
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
20
+ import { createHash, randomUUID } from 'node:crypto'
21
+ import { join } from 'node:path'
22
+
23
+ export const GRANTS_VERSION = 1
24
+
25
+
26
+ export const GRANT_PERMISSIONS = ['read', 'write']
27
+
28
+
29
+
30
+
31
+
32
+             
33
+
34
+
35
+
36
+
37
+
38
+
39
+                             
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+ /** 会话 id 通常已经是 UUID;异常字符换成 `_`,改写过的再加 8 位 hash 防碰撞。 */
50
+ function safeName(sessionId ) {
51
+ const cleaned = sessionId.replace(/[^A-Za-z0-9._-]+/g, '_').slice(0, 80)
52
+ if (cleaned === sessionId && cleaned !== '') return cleaned
53
+ const base = cleaned === '' ? 'session' : cleaned.slice(0, 64)
54
+ return `${base}-${createHash('sha1').update(sessionId).digest('hex').slice(0, 8)}`
55
+ }
56
+
57
+ function asString(value ) {
58
+ return typeof value === 'string' && value.length > 0 ? value : undefined
59
+ }
60
+
61
+ function cleanPermissions(raw ) {
62
+ if (!Array.isArray(raw)) return []
63
+ const out = []
64
+ for (const item of raw) {
65
+ if ((item === 'read' || item === 'write') && !out.includes(item)) out.push(item)
66
+ }
67
+ return out
68
+ }
69
+
70
+ function parseGrant(raw , sessionId ) {
71
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
72
+ const value = raw
73
+ const scope = asString(value.scope)
74
+ const id = asString(value.id)
75
+ if (scope === undefined || id === undefined) return undefined
76
+ const permissions = cleanPermissions(value.permissions)
77
+ if (permissions.length === 0) return undefined
78
+ return {
79
+ id,
80
+ scope,
81
+ permissions,
82
+ duration: 'session',
83
+ sessionId: asString(value.sessionId) ?? sessionId,
84
+ grantedBy: asString(value.grantedBy) ?? 'user',
85
+ grantedAt: typeof value.grantedAt === 'number' && Number.isFinite(value.grantedAt) ? value.grantedAt : Date.now(),
86
+ ...(typeof value.expiresAt === 'number' && Number.isFinite(value.expiresAt) ? { expiresAt: value.expiresAt } : {}),
87
+ ...(typeof value.revokedAt === 'number' && Number.isFinite(value.revokedAt) ? { revokedAt: value.revokedAt } : {}),
88
+ ...(asString(value.scopeGeneration) !== undefined ? { scopeGeneration: asString(value.scopeGeneration) } : {}),
89
+ }
90
+ }
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+ export class SessionGrantsStore {
105
+ dir
106
+
107
+ constructor(options ) {
108
+ this.dir = join(options.root, 'grants')
109
+ }
110
+
111
+ fileFor(sessionId ) {
112
+ return join(this.dir, `${safeName(sessionId)}.json`)
113
+ }
114
+
115
+ /** 某会话自己的 grant(不含已撤销 / 已过期;子 Agent 链由 provider 负责)。 */
116
+ list(sessionId ) {
117
+ const file = this.fileFor(sessionId)
118
+ let text
119
+ try {
120
+ text = readFileSync(file, 'utf8')
121
+ } catch {
122
+ return []
123
+ }
124
+ let raw
125
+ try {
126
+ raw = JSON.parse(text)
127
+ } catch {
128
+ return []
129
+ }
130
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return []
131
+ const grants = (raw ).grants
132
+ if (!Array.isArray(grants)) return []
133
+ const now = Date.now()
134
+ const out = []
135
+ for (const item of grants) {
136
+ const grant = parseGrant(item, sessionId)
137
+ if (grant === undefined) continue
138
+ if (grant.revokedAt !== undefined) continue
139
+ if (grant.expiresAt !== undefined && grant.expiresAt <= now) continue
140
+ out.push(grant)
141
+ }
142
+ return out
143
+ }
144
+
145
+ /** 所有会话的 grant 文件(面板审计 / 清理用)。 */
146
+ listAll() {
147
+ let entries
148
+ try {
149
+ entries = readdirSync(this.dir)
150
+ } catch {
151
+ return []
152
+ }
153
+ const out = []
154
+ for (const entry of entries) {
155
+ if (!entry.endsWith('.json')) continue
156
+ const sessionId = entry.slice(0, -'.json'.length)
157
+ // 文件名可能被 safeName 改写;grant 自身带 sessionId,优先用它。
158
+ for (const grant of this.list(sessionId)) out.push(grant)
159
+ }
160
+ return out
161
+ }
162
+
163
+ /**
164
+ * 新增或合并授权:同一作用域已有有效 grant 时合并权限(read / write 独立),
165
+ * 不重复造条目;`scopeGeneration` 变化视为新代次,旧条目先撤销再新增。
166
+ */
167
+ add(sessionId , input ) {
168
+ const permissions = cleanPermissions(input.permissions)
169
+ if (permissions.length === 0) throw new Error('grant requires at least one permission')
170
+ const all = this.readAll(sessionId)
171
+ const now = Date.now()
172
+ const existing = all.grants.find((grant) => grant.scope === input.scope
173
+ && grant.revokedAt === undefined
174
+ && (grant.expiresAt === undefined || grant.expiresAt > now)
175
+ && (grant.scopeGeneration === input.scopeGeneration))
176
+ if (existing !== undefined) {
177
+ const merged = [...new Set([...existing.permissions, ...permissions])]
178
+ existing.permissions = merged
179
+ existing.grantedAt = now
180
+ if (input.expiresAt !== undefined) existing.expiresAt = input.expiresAt
181
+ this.write(sessionId, all)
182
+ return existing
183
+ }
184
+ // 同作用域但代次不同:旧代次的 grant 明确作废,避免“同名重建复活旧授权”。
185
+ for (const grant of all.grants) {
186
+ if (grant.scope === input.scope && grant.revokedAt === undefined && grant.scopeGeneration !== input.scopeGeneration) {
187
+ grant.revokedAt = now
188
+ }
189
+ }
190
+ const grant = {
191
+ id: randomUUID(),
192
+ scope: input.scope,
193
+ permissions,
194
+ duration: 'session',
195
+ sessionId,
196
+ grantedBy: input.grantedBy ?? 'user',
197
+ grantedAt: now,
198
+ ...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),
199
+ ...(input.scopeGeneration !== undefined ? { scopeGeneration: input.scopeGeneration } : {}),
200
+ }
201
+ all.grants.push(grant)
202
+ this.write(sessionId, all)
203
+ return grant
204
+ }
205
+
206
+ /** 撤销一条授权;返回是否找到。 */
207
+ revoke(sessionId , id ) {
208
+ const all = this.readAll(sessionId)
209
+ const grant = all.grants.find((item) => item.id === id)
210
+ if (grant === undefined) return false
211
+ grant.revokedAt = Date.now()
212
+ this.write(sessionId, all)
213
+ return true
214
+ }
215
+
216
+ readAll(sessionId ) {
217
+ const file = this.fileFor(sessionId)
218
+ try {
219
+ const raw = JSON.parse(readFileSync(file, 'utf8'))
220
+ if (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) {
221
+ const grants = (raw ).grants
222
+ if (Array.isArray(grants)) {
223
+ return {
224
+ version: GRANTS_VERSION,
225
+ sessionId,
226
+ grants: grants.map((item) => parseGrant(item, sessionId)).filter((item) => item !== undefined),
227
+ }
228
+ }
229
+ }
230
+ } catch { /* 没有 / 坏文件 → 空 */ }
231
+ return { version: GRANTS_VERSION, sessionId, grants: [] }
232
+ }
233
+
234
+ write(sessionId , all ) {
235
+ mkdirSync(this.dir, { recursive: true })
236
+ const file = this.fileFor(sessionId)
237
+ const tmp = `${file}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`
238
+ const payload = { version: GRANTS_VERSION, sessionId, grants: all.grants }
239
+ writeFileSync(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
240
+ renameSync(tmp, file)
241
+ }
242
+ }
243
+
244
+
245
+ //# sourceURL=source/memory-local/src/grants.ts