session-override.ts
1621 bytes
1export const SESSION_BASH_ALLOW_ENTRY = "policy-engine-session-bash-allow";
2
3export type SessionBashAllowOverride = {
4 source: string;
5 pattern: RegExp;
6};
7
8type SessionEntry = {
9 type?: unknown;
10 customType?: unknown;
11 data?: unknown;
12};
13
14function sessionPattern(data: unknown, sessionId: string): { matches: boolean; source?: string } {
15 if (!data || typeof data !== "object" || Array.isArray(data)) return { matches: false };
16 const entry = data as { pattern?: unknown; sessionId?: unknown };
17 if (entry.sessionId !== sessionId) return { matches: false };
18 return { matches: true, source: typeof entry.pattern === "string" ? entry.pattern : undefined };
19}
20
21export function createSessionBashAllowOverride(source: string): SessionBashAllowOverride {
22 return { source, pattern: new RegExp(source) };
23}
24
25export function matchesSessionBashAllowOverride(
26 override: SessionBashAllowOverride | undefined,
27 command: string,
28): boolean {
29 return override?.pattern.test(command) ?? false;
30}
31
32export function restoreSessionBashAllowOverride(
33 entries: readonly unknown[],
34 sessionId: string,
35): SessionBashAllowOverride | undefined {
36 let source: string | undefined;
37 for (const entry of entries) {
38 const { type, customType, data } = entry as SessionEntry;
39 if (type !== "custom" || customType !== SESSION_BASH_ALLOW_ENTRY) continue;
40 const storedPattern = sessionPattern(data, sessionId);
41 if (storedPattern.matches) source = storedPattern.source;
42 }
43
44 if (source === undefined) return undefined;
45 try {
46 return createSessionBashAllowOverride(source);
47 } catch {
48 return undefined;
49 }
50}