-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermission-forwarding-store.ts
More file actions
84 lines (67 loc) · 2.55 KB
/
permission-forwarding-store.ts
File metadata and controls
84 lines (67 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import type { Permission } from "@opencode-ai/sdk";
type ForwardedPermissionStatus = "allow" | "deny";
type DecisionStore = {
allow: Set<string>;
deny: Set<string>;
};
export class PermissionForwardingStore {
private readonly permissionByID = new Map<string, Permission>();
private readonly decisionsByOrchestratorSessionID = new Map<string, DecisionStore>();
public capturePermission(permission: Permission): void {
this.permissionByID.set(permission.id, permission);
}
public getPermission(permissionID: string): Permission | null {
return this.permissionByID.get(permissionID) ?? null;
}
public captureReply(orchestratorSessionID: string, permission: Permission, response: string): void {
const decision = normalizePermissionReply(response);
if (!decision) return;
const store = this.getOrCreateDecisionStore(orchestratorSessionID);
const keys = toDecisionKeys(permission);
for (const key of keys) {
if (decision === "allow") {
store.allow.add(key);
store.deny.delete(key);
continue;
}
store.deny.add(key);
store.allow.delete(key);
}
}
public getForwardedStatus(orchestratorSessionID: string, permission: Permission): ForwardedPermissionStatus | null {
const store = this.decisionsByOrchestratorSessionID.get(orchestratorSessionID);
if (!store) return null;
const keys = toDecisionKeys(permission);
for (const key of keys) {
if (store.deny.has(key)) return "deny";
}
for (const key of keys) {
if (store.allow.has(key)) return "allow";
}
return null;
}
private getOrCreateDecisionStore(orchestratorSessionID: string): DecisionStore {
const existing = this.decisionsByOrchestratorSessionID.get(orchestratorSessionID);
if (existing) return existing;
const created: DecisionStore = {
allow: new Set<string>(),
deny: new Set<string>(),
};
this.decisionsByOrchestratorSessionID.set(orchestratorSessionID, created);
return created;
}
}
function normalizePermissionReply(response: string): ForwardedPermissionStatus | null {
if (response === "always") return "allow";
if (response === "reject") return "deny";
return null;
}
function toDecisionKeys(permission: Permission): string[] {
const patterns = normalizePatterns(permission.pattern);
return patterns.map((pattern) => `${permission.type}:${pattern}`);
}
function normalizePatterns(pattern: Permission["pattern"]): string[] {
if (typeof pattern === "string") return [pattern];
if (Array.isArray(pattern)) return pattern;
return [""];
}