dsh-permission-rules 0.4.2 → 0.5.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.
Files changed (73) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.es.md +22 -0
  3. package/README.hi.md +22 -0
  4. package/README.md +22 -0
  5. package/README.pt.md +22 -0
  6. package/README.zh.md +22 -0
  7. package/lib/client.js +4696 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +1520 -172
  10. package/lib/typert.host.js +4305 -0
  11. package/lib/types/client/index.d.ts +28 -0
  12. package/lib/types/client/index.d.ts.map +1 -0
  13. package/lib/types/client/locales.d.ts +9 -0
  14. package/lib/types/client/locales.d.ts.map +1 -0
  15. package/lib/types/client/remote.d.ts +181 -0
  16. package/lib/types/client/remote.d.ts.map +1 -0
  17. package/lib/types/client/section.d.ts +35 -0
  18. package/lib/types/client/section.d.ts.map +1 -0
  19. package/lib/types/config.d.ts +52 -0
  20. package/lib/types/config.d.ts.map +1 -1
  21. package/lib/types/events.d.ts +45 -0
  22. package/lib/types/events.d.ts.map +1 -1
  23. package/lib/types/index.d.ts +2 -0
  24. package/lib/types/index.d.ts.map +1 -1
  25. package/lib/types/network.d.ts +90 -0
  26. package/lib/types/network.d.ts.map +1 -0
  27. package/lib/types/prose.d.ts +15 -0
  28. package/lib/types/prose.d.ts.map +1 -1
  29. package/lib/types/proxy.d.ts +128 -0
  30. package/lib/types/proxy.d.ts.map +1 -0
  31. package/lib/types/remote-service.d.ts +45 -0
  32. package/lib/types/remote-service.d.ts.map +1 -0
  33. package/lib/types/rules.d.ts +131 -0
  34. package/lib/types/rules.d.ts.map +1 -1
  35. package/lib/types/runtime.d.ts +141 -12
  36. package/lib/types/runtime.d.ts.map +1 -1
  37. package/lib/types/settings.d.ts +28 -0
  38. package/lib/types/settings.d.ts.map +1 -0
  39. package/lib/types/typert.host.d.ts +166 -0
  40. package/lib/types/typert.host.d.ts.map +1 -0
  41. package/lib/types/wire.d.ts +421 -0
  42. package/lib/types/wire.d.ts.map +1 -0
  43. package/package.json +40 -6
  44. package/src/client/index.ts +111 -0
  45. package/src/client/locales.ts +94 -0
  46. package/src/client/remote.ts +41 -0
  47. package/src/client/section.ts +201 -0
  48. package/src/config.ts +111 -0
  49. package/src/events.ts +46 -0
  50. package/src/index.ts +2 -0
  51. package/src/network.ts +177 -0
  52. package/src/prose.ts +85 -10
  53. package/src/proxy.ts +327 -0
  54. package/src/remote-service.ts +109 -0
  55. package/src/rules.ts +424 -5
  56. package/src/runtime.ts +454 -46
  57. package/src/settings.ts +74 -0
  58. package/src/typert.host.ts +25 -0
  59. package/src/wire.ts +239 -0
  60. package/lib/types/config.js +0 -99
  61. package/lib/types/config.js.map +0 -1
  62. package/lib/types/events.js +0 -44
  63. package/lib/types/events.js.map +0 -1
  64. package/lib/types/glob.js +0 -307
  65. package/lib/types/glob.js.map +0 -1
  66. package/lib/types/index.js +0 -27
  67. package/lib/types/index.js.map +0 -1
  68. package/lib/types/prose.js +0 -173
  69. package/lib/types/prose.js.map +0 -1
  70. package/lib/types/rules.js +0 -610
  71. package/lib/types/rules.js.map +0 -1
  72. package/lib/types/runtime.js +0 -818
  73. package/lib/types/runtime.js.map +0 -1
package/src/proxy.ts ADDED
@@ -0,0 +1,327 @@
1
+ /**
2
+ * The plugin's built-in local HTTP/CONNECT proxy: the process-level
3
+ * network gate for shell subprocess traffic. Bash/pwsh children inherit
4
+ * `HTTP(S)_PROXY`/`ALL_PROXY` environment variables pointing here, and the
5
+ * proxy adjudicates EVERY connection target against the loaded network
6
+ * rules and the active policy mode — the domain decision lives in the
7
+ * proxy layer, not in per-command wrappers.
8
+ *
9
+ * Boundaries (documented in the README): DSH's official `ctx.sandbox`
10
+ * enforces FILE effects only, so network interception is entirely this
11
+ * plugin's job; the proxy has no session context, so an `ask` decision at
12
+ * the proxy layer cannot ride the interactive approval seam — it blocks
13
+ * the connection with a structured message and is audit-logged instead
14
+ * (web tools get the real approval seam at `tools/pre-execute`).
15
+ * @module dsh-permission-rules/proxy
16
+ */
17
+
18
+ import { createServer, request as httpRequest } from 'node:http'
19
+ import { request as httpsRequest } from 'node:https'
20
+ import { connect } from 'node:net'
21
+ import { lookup } from 'node:dns/promises'
22
+ import type { AddressInfo } from 'node:net'
23
+ import type { Duplex } from 'node:stream'
24
+ import type { Server, IncomingMessage, ServerResponse } from 'node:http'
25
+ import type { CallId } from '@deepseek-ai/dsh-llm'
26
+ import type { NetworkDecision, NetworkMode } from './network.ts'
27
+ import { blockMessage } from './network.ts'
28
+ import { isIpLiteral, parseUrlTarget } from './rules.ts'
29
+ import type { NetworkTarget, SchemeName } from './rules.ts'
30
+
31
+ /** Proxy environment variable names the injector sets/restores (uppercase + lowercase for mixed-ecosystem CLIs). */
32
+ export const PROXY_ENV_NAMES: readonly string[] = ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy']
33
+
34
+ /** NO_PROXY names cleared (or preserved) by the injector. */
35
+ export const NO_PROXY_ENV_NAMES: readonly string[] = ['NO_PROXY', 'no_proxy']
36
+
37
+ /** One recorded proxy-layer block (settings-page list + session audit + logger). */
38
+ export interface NetworkBlockRecord {
39
+ readonly time: number
40
+ readonly tool: string
41
+ readonly attributed: boolean
42
+ readonly callId?: CallId
43
+ readonly domain: string
44
+ readonly scheme?: SchemeName
45
+ readonly port?: number
46
+ readonly action: 'deny' | 'ask'
47
+ readonly mode: NetworkMode
48
+ readonly matched: boolean
49
+ readonly source: string
50
+ readonly ruleIndex?: number
51
+ readonly reason?: string
52
+ }
53
+
54
+ /** Cumulative proxy-layer block counters. */
55
+ export interface NetworkStats {
56
+ denied: number
57
+ askBlocked: number
58
+ }
59
+
60
+ /** The attribution the runtime supplies for one connection (the newest in-flight shell execution). */
61
+ export interface ProxyAttribution {
62
+ readonly tool: string
63
+ readonly callId?: CallId
64
+ readonly agent?: {
65
+ readonly session: { append(type: 'permissionRules/network', data: unknown, options?: { ignorable?: true }): unknown }
66
+ }
67
+ }
68
+
69
+ /** Construction options for {@link NetworkProxy}. */
70
+ export interface NetworkProxyOptions {
71
+ /** Bind address (loopback by config). */
72
+ readonly bind: string
73
+ /** Requested port; `0` binds an ephemeral port. */
74
+ readonly port: number
75
+ /** Cap on recent-block records kept in memory. */
76
+ readonly maxRecent: number
77
+ /** Decision function supplied by the runtime (rules + mode). */
78
+ readonly decide: (target: NetworkTarget) => NetworkDecision
79
+ /** Current attribution (newest in-flight shell execution), or undefined. */
80
+ readonly attribution?: () => ProxyAttribution | undefined
81
+ /** Called for every blocked connection, after the response is sent. */
82
+ readonly onBlock?: (record: NetworkBlockRecord, attribution: ProxyAttribution | undefined) => void
83
+ /** Logger sink (proxy failures must never crash the host). */
84
+ readonly logger: { warn(message: string): void }
85
+ }
86
+
87
+ /**
88
+ * The local HTTP/CONNECT policy proxy. Binds on demand (the plugin calls
89
+ * {@link start} inside an effect and {@link close} from its disposer);
90
+ * every live tunnel socket is tracked and destroyed on close so updates
91
+ * and uninstalls leave no orphaned connections.
92
+ */
93
+ export class NetworkProxy {
94
+ private server: Server | undefined
95
+ private readonly sockets = new Set<Duplex>()
96
+ private readonly recent: NetworkBlockRecord[] = []
97
+ private readonly stats: NetworkStats = { denied: 0, askBlocked: 0 }
98
+ private actualPort = 0
99
+
100
+ constructor(private readonly options: NetworkProxyOptions) {}
101
+
102
+ /** The bound port (valid after {@link start} resolves). */
103
+ get port(): number {
104
+ return this.actualPort
105
+ }
106
+
107
+ /** Deny/ask blocks recorded since mount, newest first (settings-page list). */
108
+ recentBlocks(): readonly NetworkBlockRecord[] {
109
+ return this.recent
110
+ }
111
+
112
+ /** Cumulative block counters. */
113
+ blockStats(): NetworkStats {
114
+ return { ...this.stats }
115
+ }
116
+
117
+ /** Bind the server and return the actual port. */
118
+ start(): Promise<number> {
119
+ const server = createServer((req, res) => {
120
+ void this.handleRequest(req, res)
121
+ })
122
+ server.on('connect', (req, socket, head) => {
123
+ void this.handleConnect(req, socket, head)
124
+ })
125
+ server.on('error', (error: unknown) => {
126
+ this.options.logger.warn(`permission-rules: proxy server error: ${String(error)}`)
127
+ })
128
+ this.server = server
129
+ return new Promise((resolve, reject) => {
130
+ const onError = (error: Error): void => {
131
+ server.off('listening', onListening)
132
+ reject(error)
133
+ }
134
+ const onListening = (): void => {
135
+ server.off('error', onError)
136
+ const address = server.address() as AddressInfo
137
+ this.actualPort = address.port
138
+ resolve(address.port)
139
+ }
140
+ server.once('error', onError)
141
+ server.once('listening', onListening)
142
+ server.listen(this.options.port, this.options.bind)
143
+ })
144
+ }
145
+
146
+ /** Stop the server and destroy every tunnel; resolves when sockets are closed. */
147
+ close(): Promise<void> {
148
+ const server = this.server
149
+ this.server = undefined
150
+ for (const socket of this.sockets) socket.destroy()
151
+ this.sockets.clear()
152
+ if (server === undefined) return Promise.resolve()
153
+ return new Promise(resolve => {
154
+ server.close(() => resolve())
155
+ })
156
+ }
157
+
158
+ /** Plain-HTTP proxying: absolute-form requests are adjudicated and forwarded (or blocked with a structured 403). */
159
+ private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
160
+ const target = parseUrlTarget(req.url ?? '')
161
+ if (target === undefined || target.scheme === undefined) {
162
+ res.writeHead(404, { 'content-type': 'text/plain' })
163
+ res.end('permission-rules proxy: only absolute-form proxy requests are served here\n')
164
+ return
165
+ }
166
+ await this.forwardOrBlock(res, target, () => {
167
+ const upstream = new URL(req.url as string)
168
+ const send = upstream.protocol === 'https:' ? httpsRequest : httpRequest
169
+ const proxyReq = send(upstream, { method: req.method, headers: req.headers }, proxyRes => {
170
+ res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers)
171
+ proxyRes.pipe(res)
172
+ })
173
+ proxyReq.on('error', (error: unknown) => {
174
+ if (!res.headersSent) {
175
+ res.writeHead(502, { 'content-type': 'text/plain' })
176
+ res.end(`[network: upstream error] ${String(error)}\n`)
177
+ } else {
178
+ res.destroy()
179
+ }
180
+ })
181
+ req.pipe(proxyReq)
182
+ })
183
+ }
184
+
185
+ /** CONNECT tunneling (HTTPS and friends): adjudicate, then either 403 or an established TCP tunnel. */
186
+ private async handleConnect(req: IncomingMessage, socket: Duplex, head: Buffer): Promise<void> {
187
+ const target = connectTarget(req.url ?? '')
188
+ if (target === undefined) {
189
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
190
+ return
191
+ }
192
+ const decision = await this.decideWithResolution(target)
193
+ if (decision.action !== 'allow') {
194
+ this.recordBlock(decision, target)
195
+ const body = blockMessage(decision)
196
+ socket.end(`HTTP/1.1 403 Forbidden\r\ncontent-type: text/plain\r\ncontent-length: ${Buffer.byteLength(body)}\r\n\r\n${body}`)
197
+ return
198
+ }
199
+ const upstream = connect(target.port ?? 443, target.host)
200
+ this.sockets.add(socket)
201
+ this.sockets.add(upstream)
202
+ const cleanup = (): void => {
203
+ this.sockets.delete(socket)
204
+ this.sockets.delete(upstream)
205
+ }
206
+ socket.on('close', cleanup)
207
+ upstream.on('close', cleanup)
208
+ upstream.on('error', () => socket.destroy())
209
+ socket.on('error', () => upstream.destroy())
210
+ upstream.once('connect', () => {
211
+ socket.write('HTTP/1.1 200 Connection Established\r\n\r\n')
212
+ if (head.length > 0) upstream.write(head)
213
+ upstream.pipe(socket)
214
+ socket.pipe(upstream)
215
+ })
216
+ }
217
+
218
+ /** Adjudicate one plain-HTTP request; deny/ask blocks with a structured 403 before any forwarding. */
219
+ private async forwardOrBlock(res: ServerResponse, target: NetworkTarget, forward: () => void): Promise<void> {
220
+ const decision = await this.decideWithResolution(target)
221
+ if (decision.action !== 'allow') {
222
+ this.recordBlock(decision, target)
223
+ const body = blockMessage(decision)
224
+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8', 'content-length': Buffer.byteLength(body) })
225
+ res.end(body)
226
+ return
227
+ }
228
+ forward()
229
+ }
230
+
231
+ /** Resolve a hostname once so `ips`-scoped rules see the real addresses, then decide. */
232
+ private async decideWithResolution(target: NetworkTarget): Promise<NetworkDecision> {
233
+ if (!isIpLiteral(target.host)) {
234
+ try {
235
+ const addresses = await lookup(target.host, { all: true, verbatim: true })
236
+ const resolved = addresses.map(entry => entry.address)
237
+ if (resolved.length > 0) return this.options.decide({ ...target, ips: [...target.ips, ...resolved] })
238
+ } catch {
239
+ // Unresolvable target: decide on the literal name (ip-scoped rules simply cannot fire).
240
+ }
241
+ }
242
+ return this.options.decide(target)
243
+ }
244
+
245
+ /** Record a block: counters, recent ring, and the runtime hook (logger + session audit). */
246
+ private recordBlock(decision: NetworkDecision, target: NetworkTarget): void {
247
+ const attribution = this.options.attribution?.()
248
+ const record: NetworkBlockRecord = {
249
+ time: Date.now(),
250
+ tool: attribution?.tool ?? 'subprocess',
251
+ attributed: attribution !== undefined,
252
+ ...(attribution?.callId !== undefined ? { callId: attribution.callId } : {}),
253
+ domain: target.host,
254
+ ...(target.scheme !== undefined ? { scheme: target.scheme } : {}),
255
+ ...(target.port !== undefined ? { port: target.port } : {}),
256
+ action: decision.action === 'ask' ? 'ask' : 'deny',
257
+ mode: decision.mode,
258
+ matched: decision.matched,
259
+ source: decision.source ?? '',
260
+ ...(decision.ruleIndex !== undefined ? { ruleIndex: decision.ruleIndex } : {}),
261
+ ...(decision.rule !== undefined ? { reason: decision.rule.reason } : {}),
262
+ }
263
+ if (record.action === 'deny') this.stats.denied += 1
264
+ else this.stats.askBlocked += 1
265
+ this.recent.unshift(record)
266
+ if (this.recent.length > this.options.maxRecent) this.recent.length = this.options.maxRecent
267
+ this.options.logger.warn(`permission-rules: network ${record.action === 'deny' ? 'denied' : 'ask-blocked'} ${target.scheme ?? '?'}://${target.host}${target.port !== undefined ? `:${target.port}` : ''} (mode ${decision.mode}${decision.matched ? `, rule ${(decision.ruleIndex ?? 0) + 1}` : ', mode default'})`)
268
+ try {
269
+ this.options.onBlock?.(record, attribution)
270
+ } catch (error: unknown) {
271
+ this.options.logger.warn(`permission-rules: network block hook failed: ${String(error)}`)
272
+ }
273
+ }
274
+ }
275
+
276
+ /** Parse a CONNECT authority (`host:port`) into an https target with an explicit port. */
277
+ function connectTarget(authority: string): NetworkTarget | undefined {
278
+ const colon = authority.lastIndexOf(':')
279
+ if (colon <= 0) return undefined
280
+ const host = authority.slice(0, colon).replace(/^\[|\]$/g, '').toLowerCase().replace(/\.+$/, '')
281
+ const port = Number(authority.slice(colon + 1))
282
+ if (host.length === 0 || !Number.isInteger(port) || port < 1 || port > 65535) return undefined
283
+ return { scheme: 'https', host, port, ips: isIpLiteral(host) ? [host] : [] }
284
+ }
285
+
286
+ /**
287
+ * Inject the proxy environment variables for subprocesses and return a
288
+ * disposer restoring every previous value exactly (so updates and
289
+ * uninstalls leave the host environment untouched). `noProxy: 'clear'`
290
+ * empties NO_PROXY so the policy cannot be bypassed through ambient
291
+ * exclusions; `preserve` keeps ambient values.
292
+ *
293
+ * The snapshot pass covers EVERY name BEFORE any write: on Windows
294
+ * `process.env` is case-insensitive, so the uppercase/lowercase spellings
295
+ * share one variable — writing `HTTP_PROXY` mid-loop would otherwise
296
+ * poison the later snapshot of `http_proxy` and make the restore write
297
+ * the proxy address back over the original.
298
+ * @param port - the bound proxy port.
299
+ * @param noProxy - the configured NO_PROXY handling.
300
+ * @returns the restore disposer.
301
+ */
302
+ export function injectProxyEnv(port: number, noProxy: 'clear' | 'preserve'): () => void {
303
+ const previous = new Map<string, string | undefined>()
304
+ const value = `http://127.0.0.1:${port}`
305
+ for (const name of PROXY_ENV_NAMES) previous.set(name, process.env[name])
306
+ if (noProxy === 'clear') {
307
+ for (const name of NO_PROXY_ENV_NAMES) previous.set(name, process.env[name])
308
+ }
309
+ for (const name of PROXY_ENV_NAMES) process.env[name] = value
310
+ if (noProxy === 'clear') {
311
+ for (const name of NO_PROXY_ENV_NAMES) process.env[name] = ''
312
+ }
313
+ return () => {
314
+ for (const name of PROXY_ENV_NAMES) {
315
+ const old = previous.get(name)
316
+ if (old === undefined) delete process.env[name]
317
+ else process.env[name] = old
318
+ }
319
+ if (noProxy === 'clear') {
320
+ for (const name of NO_PROXY_ENV_NAMES) {
321
+ const old = previous.get(name)
322
+ if (old === undefined) delete process.env[name]
323
+ else process.env[name] = old
324
+ }
325
+ }
326
+ }
327
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The settings-page Remote service: exposes the `permissionRules` Typert
3
+ * namespace (network snapshot + rule-file read/save/reload) to the
4
+ * browser half. All state lives in the {@link PermissionRulesRuntime}
5
+ * this service delegates to; the service itself only bridges the wire
6
+ * vocabulary. The rule editor only ever touches KNOWN rule sources —
7
+ * arbitrary paths are refused by the runtime.
8
+ * @module dsh-permission-rules/remote-service
9
+ */
10
+
11
+ import { existsSync } from 'node:fs'
12
+ import type { Context } from '@deepseek-ai/cordis'
13
+ import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
14
+ import type { PermissionRulesRuntime } from './runtime.ts'
15
+ import type { PermissionRulesSnapshot, RulesReadResult, RulesReloadResult, RulesSaveResult } from './wire.ts'
16
+
17
+ declare module '@deepseek-ai/cordis' {
18
+ interface Context {
19
+ /** Settings-page snapshot + rule-editor bridge (this package). */
20
+ permissionRules: PermissionRulesRemoteService
21
+ }
22
+ }
23
+
24
+ /** Service config: the runtime instance whose state the wire exposes. */
25
+ export interface PermissionRulesRemoteServiceConfig {
26
+ /** The runtime holding the loaded rules, proxy state, and block records. */
27
+ runtime: PermissionRulesRuntime
28
+ }
29
+
30
+ /**
31
+ * The Typert Remote service behind the settings page. Registered through
32
+ * `ctx.plugin(PermissionRulesRemoteService, { runtime })` in
33
+ * {@link apply}; the typert gateway binds its public methods to the
34
+ * invocation descriptors in `./wire.ts`.
35
+ */
36
+ export class PermissionRulesRemoteService extends TypertRemoteService {
37
+ static inject = [] as string[]
38
+
39
+ constructor(ctx: Context, private readonly config: PermissionRulesRemoteServiceConfig) {
40
+ super(ctx, 'permissionRules')
41
+ }
42
+
43
+ /** The settings-page snapshot: mode mapping, proxy liveness, counters, recent blocks, editable rule sources. */
44
+ networkStatus(): PermissionRulesSnapshot {
45
+ const snapshot = this.config.runtime.networkSnapshot()
46
+ const sources = this.config.runtime.knownRuleSources().map(path => {
47
+ const owner = this.config.runtime.sourceOwner(path)
48
+ return { path, exists: existsSync(path), cwd: owner ?? null }
49
+ })
50
+ return {
51
+ enabled: snapshot.enabled,
52
+ mode: snapshot.mode,
53
+ configuredMode: snapshot.configuredMode,
54
+ sandboxMode: snapshot.sandboxMode ?? null,
55
+ proxyPort: snapshot.proxyPort,
56
+ proxyActive: snapshot.proxyActive,
57
+ denied: snapshot.denied,
58
+ askBlocked: snapshot.askBlocked,
59
+ recent: snapshot.recent.map(block => ({
60
+ time: block.time,
61
+ tool: block.tool,
62
+ attributed: block.attributed,
63
+ domain: block.domain,
64
+ scheme: block.scheme ?? null,
65
+ port: block.port ?? null,
66
+ action: block.action,
67
+ mode: block.mode,
68
+ matched: block.matched,
69
+ source: block.source,
70
+ ruleIndex: block.ruleIndex ?? null,
71
+ reason: block.reason ?? null,
72
+ })),
73
+ sources,
74
+ }
75
+ }
76
+
77
+ /** Read one known rule file for the editor. */
78
+ rulesRead(path: string): RulesReadResult {
79
+ const result = this.config.runtime.readRuleFile(path)
80
+ return {
81
+ path: result.path,
82
+ exists: result.exists,
83
+ text: result.text,
84
+ error: result.error ?? null,
85
+ }
86
+ }
87
+
88
+ /** Validate and write one known rule file; invalid edits are rejected before anything touches disk. */
89
+ rulesSave(path: string, text: string): RulesSaveResult {
90
+ const result = this.config.runtime.saveRuleFile(path, text)
91
+ return {
92
+ ok: result.ok,
93
+ error: result.error ?? null,
94
+ reloaded: result.reloaded ?? null,
95
+ }
96
+ }
97
+
98
+ /** Re-read every cached workspace chain (after an external edit). */
99
+ reload(): RulesReloadResult {
100
+ try {
101
+ this.config.runtime.reloadAll()
102
+ return { ok: true, error: null }
103
+ } catch (error: unknown) {
104
+ return { ok: false, error: error instanceof Error ? error.message : String(error) }
105
+ }
106
+ }
107
+ }
108
+
109
+ export default PermissionRulesRemoteService