@myrialabs/clopen 0.4.8 → 0.4.9
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/backend/artifacts/detect.ts +129 -0
- package/backend/artifacts/engine-map.ts +53 -0
- package/backend/artifacts/frontmatter.ts +68 -0
- package/backend/artifacts/generate.ts +105 -0
- package/backend/artifacts/index.ts +34 -0
- package/backend/artifacts/markers.ts +76 -0
- package/backend/artifacts/matrix.ts +247 -0
- package/backend/artifacts/slug.ts +35 -0
- package/backend/artifacts/sync.ts +130 -0
- package/backend/artifacts/types.ts +152 -0
- package/backend/auth/permissions.ts +51 -1
- package/backend/chat/stream-manager.ts +14 -1
- package/backend/commands/detect.ts +25 -0
- package/backend/commands/index.ts +9 -0
- package/backend/commands/service.ts +178 -0
- package/backend/commands/store.ts +45 -0
- package/backend/commands/sync.ts +94 -0
- package/backend/database/migrations/045_create_commands_table.ts +28 -0
- package/backend/database/migrations/046_create_subagents_table.ts +29 -0
- package/backend/database/migrations/047_create_instructions_table.ts +29 -0
- package/backend/database/migrations/048_add_mcp_tool_overrides.ts +23 -0
- package/backend/database/migrations/049_create_permission_sets_table.ts +50 -0
- package/backend/database/migrations/050_create_profiles_tables.ts +57 -0
- package/backend/database/migrations/051_add_profile_to_sessions.ts +20 -0
- package/backend/database/migrations/052_add_default_profile_to_projects.ts +20 -0
- package/backend/database/migrations/053_add_profile_to_permission_sets.ts +37 -0
- package/backend/database/migrations/054_drop_subagent_agent_type.ts +20 -0
- package/backend/database/migrations/055_artifact_model_tools_per_engine.ts +43 -0
- package/backend/database/migrations/index.ts +77 -0
- package/backend/database/queries/command-queries.ts +82 -0
- package/backend/database/queries/index.ts +12 -2
- package/backend/database/queries/instruction-queries.ts +62 -0
- package/backend/database/queries/mcp-server-queries.ts +25 -0
- package/backend/database/queries/permission-set-queries.ts +155 -0
- package/backend/database/queries/profile-queries.ts +118 -0
- package/backend/database/queries/project-queries.ts +14 -0
- package/backend/database/queries/session-queries.ts +10 -0
- package/backend/database/queries/subagent-queries.ts +92 -0
- package/backend/engine/adapters/claude/stream.ts +27 -3
- package/backend/engine/adapters/codex/stream.ts +46 -14
- package/backend/engine/adapters/copilot/stream.ts +58 -4
- package/backend/engine/adapters/opencode/message-converter.ts +22 -2
- package/backend/engine/adapters/opencode/server.ts +166 -210
- package/backend/engine/adapters/opencode/stream.ts +150 -24
- package/backend/engine/adapters/qwen/stream.ts +23 -3
- package/backend/engine/artifact-sync.ts +51 -0
- package/backend/engine/types.ts +6 -0
- package/backend/instructions/index.ts +8 -0
- package/backend/instructions/service.ts +63 -0
- package/backend/instructions/sync.ts +56 -0
- package/backend/mcp/external/config.ts +42 -20
- package/backend/mcp/external/proxy.ts +89 -5
- package/backend/mcp/external/tools.ts +88 -0
- package/backend/mcp/index.ts +38 -15
- package/backend/mcp/internal/config.ts +48 -11
- package/backend/mcp/internal/remote-server.ts +9 -1
- package/backend/permissions/index.ts +27 -0
- package/backend/permissions/materialize.ts +96 -0
- package/backend/permissions/resolve.test.ts +162 -0
- package/backend/permissions/resolve.ts +106 -0
- package/backend/permissions/service.ts +167 -0
- package/backend/profiles/index.ts +10 -0
- package/backend/profiles/service.ts +169 -0
- package/backend/skills/index.ts +1 -1
- package/backend/skills/sync.ts +88 -128
- package/backend/subagents/detect.ts +23 -0
- package/backend/subagents/index.ts +10 -0
- package/backend/subagents/service.ts +166 -0
- package/backend/subagents/store.ts +44 -0
- package/backend/subagents/sync.ts +144 -0
- package/backend/ws/artifacts/generate.ts +51 -0
- package/backend/ws/artifacts/index.ts +8 -0
- package/backend/ws/chat/stream.ts +33 -2
- package/backend/ws/commands/crud.ts +157 -0
- package/backend/ws/commands/index.ts +8 -0
- package/backend/ws/git/branch.ts +4 -2
- package/backend/ws/git/remote.ts +21 -11
- package/backend/ws/index.ts +17 -1
- package/backend/ws/instructions/crud.ts +53 -0
- package/backend/ws/instructions/index.ts +8 -0
- package/backend/ws/mcp/crud.ts +7 -1
- package/backend/ws/mcp/index.ts +4 -1
- package/backend/ws/mcp/tools.ts +112 -0
- package/backend/ws/permissions/crud.ts +72 -0
- package/backend/ws/permissions/index.ts +8 -0
- package/backend/ws/profiles/crud.ts +149 -0
- package/backend/ws/profiles/index.ts +9 -0
- package/backend/ws/subagents/crud.ts +136 -0
- package/backend/ws/subagents/index.ts +8 -0
- package/dist/assets/{index-jGo0X72U.js → index-BdRui-1z.js} +1 -1
- package/dist/assets/{index-B_F_OgoC.js → index-BjaIjmd4.js} +1 -1
- package/dist/assets/{main-BkCc3WEB.js → main-Cf8SUfQ1.js} +367 -315
- package/dist/assets/main-D4pdkiQK.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/constants/engine-tools.ts +56 -0
- package/shared/types/database/schema.ts +2 -0
- package/shared/types/stores/settings.ts +15 -0
- package/shared/types/unified/stream.ts +7 -0
- package/shared/utils/logger.ts +6 -0
- package/dist/assets/main-CWDwET4x.css +0 -1
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-disk "honesty" materialization for permissions.
|
|
3
|
+
*
|
|
4
|
+
* Enforcement is a runtime hook (see the engine adapters + resolve.ts); this
|
|
5
|
+
* module additionally writes the resolved rules into Claude's ISOLATED
|
|
6
|
+
* `settings.json` so they are inspectable and also apply to that engine's own
|
|
7
|
+
* settings resolution. Only Claude gets a file: it is the one engine with a
|
|
8
|
+
* config Clopen can manage safely (isolated dir) AND whose native
|
|
9
|
+
* `permissions.allow`/`permissions.deny` schema matches this feature's model.
|
|
10
|
+
*
|
|
11
|
+
* The merge is managed-KEYS: only `permissions.allow` / `permissions.deny` are
|
|
12
|
+
* touched; any other content in the file (Claude's own settings) is preserved.
|
|
13
|
+
* Global scope only — writing a repo's `.claude/settings.json` touches the
|
|
14
|
+
* working tree and must be an explicit user action, never silent at stream start.
|
|
15
|
+
*
|
|
16
|
+
* Never throws — a stream is never broken because permissions couldn't be
|
|
17
|
+
* written to disk.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { mkdir, readFile, writeFile, stat } from 'node:fs/promises';
|
|
21
|
+
import { join } from 'path';
|
|
22
|
+
import { resolveArtifact } from '$backend/artifacts';
|
|
23
|
+
import { debug } from '$shared/utils/logger';
|
|
24
|
+
import { resolvePermissionsFromDb } from './service';
|
|
25
|
+
import { hasAnyRestriction } from './resolve';
|
|
26
|
+
import type { ArtifactEngineKey } from './service';
|
|
27
|
+
|
|
28
|
+
async function readJson(path: string): Promise<Record<string, unknown>> {
|
|
29
|
+
try {
|
|
30
|
+
await stat(path);
|
|
31
|
+
} catch {
|
|
32
|
+
return {};
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
36
|
+
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};
|
|
37
|
+
} catch {
|
|
38
|
+
// Malformed settings.json — don't clobber it. Skip the write.
|
|
39
|
+
return { __unparsable__: true };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Materialize the global permission set for one engine into its isolated config
|
|
45
|
+
* file (Claude only). Called per stream (global scope). No-op for engines without
|
|
46
|
+
* a managed permission file.
|
|
47
|
+
*/
|
|
48
|
+
export async function syncPermissions(engine: ArtifactEngineKey): Promise<void> {
|
|
49
|
+
try {
|
|
50
|
+
if (engine !== 'claude') return; // Only Claude has a managed on-disk file today.
|
|
51
|
+
|
|
52
|
+
const resolution = resolveArtifact('permission', { engine, scope: 'global' });
|
|
53
|
+
if (!resolution.supported) return;
|
|
54
|
+
const target = resolution.locateEffective({ engine, scope: 'global' });
|
|
55
|
+
if (!target) return;
|
|
56
|
+
|
|
57
|
+
const resolved = resolvePermissionsFromDb('claude-code');
|
|
58
|
+
|
|
59
|
+
// Nothing to enforce and no file to clean up → don't create a spurious `{}`.
|
|
60
|
+
const fileExists = await stat(target).then(() => true).catch(() => false);
|
|
61
|
+
if (!hasAnyRestriction(resolved) && !fileExists) return;
|
|
62
|
+
|
|
63
|
+
const current = await readJson(target);
|
|
64
|
+
if (current.__unparsable__) {
|
|
65
|
+
debug.warn('permissions', `Skipping settings.json write — ${target} is not valid JSON`);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const permissions = (typeof current.permissions === 'object' && current.permissions
|
|
70
|
+
? { ...(current.permissions as Record<string, unknown>) }
|
|
71
|
+
: {}) as Record<string, unknown>;
|
|
72
|
+
|
|
73
|
+
if (hasAnyRestriction(resolved)) {
|
|
74
|
+
permissions.allow = resolved.allow;
|
|
75
|
+
permissions.deny = resolved.deny;
|
|
76
|
+
} else {
|
|
77
|
+
// No rules → drop our managed keys, leaving any other permission config.
|
|
78
|
+
delete permissions.allow;
|
|
79
|
+
delete permissions.deny;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const next: Record<string, unknown> = { ...current };
|
|
83
|
+
if (Object.keys(permissions).length > 0) next.permissions = permissions;
|
|
84
|
+
else delete next.permissions;
|
|
85
|
+
|
|
86
|
+
const serialized = JSON.stringify(next, null, 2) + '\n';
|
|
87
|
+
const existing = await readFile(target, 'utf8').catch(() => '');
|
|
88
|
+
if (serialized === existing) return;
|
|
89
|
+
|
|
90
|
+
await mkdir(join(target, '..'), { recursive: true });
|
|
91
|
+
await writeFile(target, serialized, 'utf8');
|
|
92
|
+
debug.log('permissions', `🔐 Wrote Claude permissions → ${target} (${resolved.allow.length} allow, ${resolved.deny.length} deny)`);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
debug.warn('permissions', `Permission materialization for ${engine} failed (continuing without):`, error);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import type { PermissionSet } from '$backend/database/queries';
|
|
3
|
+
import {
|
|
4
|
+
matchesPattern,
|
|
5
|
+
matchesAny,
|
|
6
|
+
mergePermissions,
|
|
7
|
+
mergeLayers,
|
|
8
|
+
isToolAllowed,
|
|
9
|
+
hasAnyRestriction,
|
|
10
|
+
pickEngineSet,
|
|
11
|
+
EMPTY_PERMISSIONS
|
|
12
|
+
} from './resolve';
|
|
13
|
+
|
|
14
|
+
describe('matchesPattern', () => {
|
|
15
|
+
test('exact match', () => {
|
|
16
|
+
expect(matchesPattern('Bash', 'Bash')).toBe(true);
|
|
17
|
+
expect(matchesPattern('Bash', 'Edit')).toBe(false);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('trailing wildcard', () => {
|
|
21
|
+
expect(matchesPattern('mcp__github__*', 'mcp__github__create_issue')).toBe(true);
|
|
22
|
+
expect(matchesPattern('mcp__github__*', 'mcp__gitlab__x')).toBe(false);
|
|
23
|
+
// A bare `*` matches everything.
|
|
24
|
+
expect(matchesPattern('*', 'anything')).toBe(true);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test('wildcard does not match middle', () => {
|
|
28
|
+
expect(matchesPattern('mcp__*__issue', 'mcp__github__issue')).toBe(false);
|
|
29
|
+
});
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
describe('matchesAny', () => {
|
|
33
|
+
test('any pattern hits', () => {
|
|
34
|
+
expect(matchesAny(['Read', 'Write'], 'Write')).toBe(true);
|
|
35
|
+
expect(matchesAny(['Read', 'Write'], 'Bash')).toBe(false);
|
|
36
|
+
expect(matchesAny([], 'Bash')).toBe(false);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
describe('isToolAllowed', () => {
|
|
41
|
+
test('empty set allows everything', () => {
|
|
42
|
+
expect(isToolAllowed(EMPTY_PERMISSIONS, 'Bash')).toBe(true);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('deny blocks', () => {
|
|
46
|
+
expect(isToolAllowed({ allow: [], deny: ['Bash'] }, 'Bash')).toBe(false);
|
|
47
|
+
expect(isToolAllowed({ allow: [], deny: ['Bash'] }, 'Read')).toBe(true);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('allowlist gates non-listed tools', () => {
|
|
51
|
+
const set = { allow: ['Read', 'Grep'], deny: [] };
|
|
52
|
+
expect(isToolAllowed(set, 'Read')).toBe(true);
|
|
53
|
+
expect(isToolAllowed(set, 'Bash')).toBe(false);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test('deny wins over allow', () => {
|
|
57
|
+
const set = { allow: ['Bash'], deny: ['Bash'] };
|
|
58
|
+
expect(isToolAllowed(set, 'Bash')).toBe(false);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('wildcards in both lists', () => {
|
|
62
|
+
const set = { allow: ['mcp__github__*'], deny: ['mcp__github__delete_*'] };
|
|
63
|
+
expect(isToolAllowed(set, 'mcp__github__create_issue')).toBe(true);
|
|
64
|
+
expect(isToolAllowed(set, 'mcp__github__delete_repo')).toBe(false);
|
|
65
|
+
expect(isToolAllowed(set, 'Bash')).toBe(false); // not in allowlist
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
describe('mergePermissions', () => {
|
|
70
|
+
test('deny is the union of both scopes', () => {
|
|
71
|
+
const merged = mergePermissions({ allow: [], deny: ['Bash'] }, { allow: [], deny: ['Write'] });
|
|
72
|
+
expect(merged.deny.sort()).toEqual(['Bash', 'Write']);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test('project allowlist overrides global when non-empty', () => {
|
|
76
|
+
const merged = mergePermissions({ allow: ['Read'], deny: [] }, { allow: ['Grep'], deny: [] });
|
|
77
|
+
expect(merged.allow).toEqual(['Grep']);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('global allowlist applies when project has none', () => {
|
|
81
|
+
const merged = mergePermissions({ allow: ['Read'], deny: [] }, { allow: [], deny: ['Bash'] });
|
|
82
|
+
expect(merged.allow).toEqual(['Read']);
|
|
83
|
+
expect(merged.deny).toEqual(['Bash']);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test('undefined scopes yield empty', () => {
|
|
87
|
+
expect(mergePermissions(undefined, undefined)).toEqual({ allow: [], deny: [] });
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('deny union de-duplicates', () => {
|
|
91
|
+
const merged = mergePermissions({ allow: [], deny: ['Bash'] }, { allow: [], deny: ['Bash'] });
|
|
92
|
+
expect(merged.deny).toEqual(['Bash']);
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
describe('mergeLayers', () => {
|
|
97
|
+
test('deny unions across all layers', () => {
|
|
98
|
+
const merged = mergeLayers([
|
|
99
|
+
{ allow: [], deny: ['Bash'] },
|
|
100
|
+
{ allow: [], deny: ['Write'] },
|
|
101
|
+
{ allow: [], deny: ['WebFetch'] }
|
|
102
|
+
]);
|
|
103
|
+
expect(merged.deny.sort()).toEqual(['Bash', 'WebFetch', 'Write']);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('most specific non-empty allowlist wins', () => {
|
|
107
|
+
const merged = mergeLayers([
|
|
108
|
+
{ allow: ['Read'], deny: [] }, // global
|
|
109
|
+
{ allow: ['Grep'], deny: [] }, // project
|
|
110
|
+
{ allow: ['Edit'], deny: [] } // profile (most specific)
|
|
111
|
+
]);
|
|
112
|
+
expect(merged.allow).toEqual(['Edit']);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('broader allowlist applies when more specific layers have none', () => {
|
|
116
|
+
const merged = mergeLayers([
|
|
117
|
+
{ allow: ['Read'], deny: [] },
|
|
118
|
+
undefined,
|
|
119
|
+
{ allow: [], deny: ['Bash'] }
|
|
120
|
+
]);
|
|
121
|
+
expect(merged.allow).toEqual(['Read']);
|
|
122
|
+
expect(merged.deny).toEqual(['Bash']);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test('profile layer only adds deny (union), keeps base allow', () => {
|
|
126
|
+
const merged = mergeLayers([
|
|
127
|
+
{ allow: ['Read', 'Edit'], deny: ['Bash'] }, // base (global)
|
|
128
|
+
undefined, // no project
|
|
129
|
+
{ allow: [], deny: ['WebFetch'] } // profile overlay
|
|
130
|
+
]);
|
|
131
|
+
expect(merged.allow).toEqual(['Read', 'Edit']);
|
|
132
|
+
expect(merged.deny.sort()).toEqual(['Bash', 'WebFetch']);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test('all-undefined yields empty', () => {
|
|
136
|
+
expect(mergeLayers([undefined, undefined, undefined])).toEqual({ allow: [], deny: [] });
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
describe('hasAnyRestriction', () => {
|
|
141
|
+
test('true when either list is non-empty', () => {
|
|
142
|
+
expect(hasAnyRestriction({ allow: ['Read'], deny: [] })).toBe(true);
|
|
143
|
+
expect(hasAnyRestriction({ allow: [], deny: ['Bash'] })).toBe(true);
|
|
144
|
+
expect(hasAnyRestriction(EMPTY_PERMISSIONS)).toBe(false);
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe('pickEngineSet', () => {
|
|
149
|
+
const sets: PermissionSet[] = [
|
|
150
|
+
{ id: 1, scope: 'global', projectId: null, profileId: null, engine: 'claude-code', allow: ['Read'], deny: ['Bash'] },
|
|
151
|
+
{ id: 2, scope: 'global', projectId: null, profileId: null, engine: 'codex', allow: [], deny: ['shell'] }
|
|
152
|
+
];
|
|
153
|
+
|
|
154
|
+
test('finds the row for the engine', () => {
|
|
155
|
+
expect(pickEngineSet(sets, 'claude-code')).toEqual({ allow: ['Read'], deny: ['Bash'] });
|
|
156
|
+
expect(pickEngineSet(sets, 'codex')).toEqual({ allow: [], deny: ['shell'] });
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test('undefined when engine has no row', () => {
|
|
160
|
+
expect(pickEngineSet(sets, 'qwen')).toBeUndefined();
|
|
161
|
+
});
|
|
162
|
+
});
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Permission resolution — the pure decision logic behind Settings → Permissions.
|
|
3
|
+
*
|
|
4
|
+
* A permission set is a pair of tool-pattern lists (`allow` + `deny`) stored per
|
|
5
|
+
* `(scope, project, engine)`. This module answers one question at the engine's
|
|
6
|
+
* auto-approve hook: *is this tool allowed to run?* The stored sets are enforced
|
|
7
|
+
* at runtime (each engine consults {@link isToolAllowed} in the hook it already
|
|
8
|
+
* uses to auto-approve tools — see the adapters), which is why enforcement is
|
|
9
|
+
* real even though every engine otherwise auto-approves.
|
|
10
|
+
*
|
|
11
|
+
* Resolution across the two scopes (documented in migration 049):
|
|
12
|
+
* - deny = global.deny ∪ project.deny (deny always adds restriction)
|
|
13
|
+
* - allow = project.allow if non-empty, else global.allow
|
|
14
|
+
* - deny WINS over allow; an empty allow means "all tools except deny".
|
|
15
|
+
*
|
|
16
|
+
* Everything here is pure (no DB) so it is unit-tested directly; the DB-reading
|
|
17
|
+
* wrapper lives in {@link resolvePermissionsFromDb} (service.ts).
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { EngineType } from '$shared/types/unified';
|
|
21
|
+
import type { PermissionSet } from '$backend/database/queries';
|
|
22
|
+
|
|
23
|
+
export interface ResolvedPermissions {
|
|
24
|
+
allow: string[];
|
|
25
|
+
deny: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const EMPTY_PERMISSIONS: ResolvedPermissions = { allow: [], deny: [] };
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Match a tool name against one pattern. Supports an exact name or a single
|
|
32
|
+
* trailing `*` wildcard (e.g. `mcp__github__*`). Kept deliberately simple and
|
|
33
|
+
* consistent across engines — argument-scoped rules (Claude's `Bash(git:*)`) are
|
|
34
|
+
* intentionally out of scope for v1.
|
|
35
|
+
*/
|
|
36
|
+
export function matchesPattern(pattern: string, tool: string): boolean {
|
|
37
|
+
if (pattern === tool) return true;
|
|
38
|
+
if (pattern.endsWith('*')) {
|
|
39
|
+
return tool.startsWith(pattern.slice(0, -1));
|
|
40
|
+
}
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** True when `tool` matches ANY pattern in the list. */
|
|
45
|
+
export function matchesAny(patterns: string[], tool: string): boolean {
|
|
46
|
+
return patterns.some(p => matchesPattern(p, tool));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Merge a global and a project set into the effective allow/deny for one engine.
|
|
51
|
+
* `undefined` means "no rule at that scope".
|
|
52
|
+
*/
|
|
53
|
+
export function mergePermissions(
|
|
54
|
+
global: ResolvedPermissions | undefined,
|
|
55
|
+
project: ResolvedPermissions | undefined
|
|
56
|
+
): ResolvedPermissions {
|
|
57
|
+
const deny = Array.from(new Set([...(global?.deny ?? []), ...(project?.deny ?? [])]));
|
|
58
|
+
// A project allowlist, when present, replaces the global one (tightening a
|
|
59
|
+
// specific project); otherwise the global allowlist applies. Unioning allow
|
|
60
|
+
// lists would loosen rather than scope, so we deliberately override.
|
|
61
|
+
const allow = project?.allow && project.allow.length > 0 ? project.allow : (global?.allow ?? []);
|
|
62
|
+
return { allow, deny };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Merge an ordered list of scope layers (least → most specific, e.g.
|
|
67
|
+
* global → project → profile) into one effective policy.
|
|
68
|
+
* - `deny` unions across every layer (deny always tightens);
|
|
69
|
+
* - `allow` uses the MOST specific non-empty allowlist (a more specific scope's
|
|
70
|
+
* allowlist replaces a broader one, mirroring {@link mergePermissions}).
|
|
71
|
+
* `undefined`/absent layers are skipped.
|
|
72
|
+
*/
|
|
73
|
+
export function mergeLayers(layers: (ResolvedPermissions | undefined)[]): ResolvedPermissions {
|
|
74
|
+
const denySet = new Set<string>();
|
|
75
|
+
let allow: string[] = [];
|
|
76
|
+
for (const layer of layers) {
|
|
77
|
+
if (!layer) continue;
|
|
78
|
+
for (const d of layer.deny) denySet.add(d);
|
|
79
|
+
if (layer.allow.length > 0) allow = layer.allow; // most specific non-empty wins
|
|
80
|
+
}
|
|
81
|
+
return { allow, deny: Array.from(denySet) };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The core decision. Deny wins; then, if an allowlist exists, the tool must match
|
|
86
|
+
* it; otherwise everything not denied is allowed.
|
|
87
|
+
*/
|
|
88
|
+
export function isToolAllowed(resolved: ResolvedPermissions, tool: string): boolean {
|
|
89
|
+
if (matchesAny(resolved.deny, tool)) return false;
|
|
90
|
+
if (resolved.allow.length > 0 && !matchesAny(resolved.allow, tool)) return false;
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Whether a resolved set imposes any restriction at all (used to skip work). */
|
|
95
|
+
export function hasAnyRestriction(resolved: ResolvedPermissions): boolean {
|
|
96
|
+
return resolved.allow.length > 0 || resolved.deny.length > 0;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Pick the set for one engine out of a scope's rows (each row is one engine).
|
|
101
|
+
* Pure so it can be tested without a DB.
|
|
102
|
+
*/
|
|
103
|
+
export function pickEngineSet(sets: PermissionSet[], engine: EngineType): ResolvedPermissions | undefined {
|
|
104
|
+
const row = sets.find(s => s.engine === engine);
|
|
105
|
+
return row ? { allow: row.allow, deny: row.deny } : undefined;
|
|
106
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Permission service — bridges the `permission_sets` table and Settings →
|
|
3
|
+
* Permissions, and resolves the effective allow/deny for one engine at stream
|
|
4
|
+
* start (consumed by each adapter's auto-approve hook).
|
|
5
|
+
*
|
|
6
|
+
* The inventory (what the UI offers as allow/deny targets) is the union of:
|
|
7
|
+
* - built-in engine tools ({@link ENGINE_BUILTIN_TOOLS}),
|
|
8
|
+
* - live MCP tools from enabled Connectors (best-effort; a server that fails to
|
|
9
|
+
* connect is simply skipped),
|
|
10
|
+
* - tool names named by subagent allowlists.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { EngineType } from '$shared/types/unified';
|
|
14
|
+
import { ENGINES } from '$shared/constants/engines';
|
|
15
|
+
import { ENGINE_BUILTIN_TOOLS, ENGINE_TOOLS_BEST_EFFORT } from '$shared/constants/engine-tools';
|
|
16
|
+
import { permissionSetQueries, subagentQueries, type PermissionScope } from '$backend/database/queries';
|
|
17
|
+
import { getEnabledExternalServers, listExternalServerTools } from '$backend/mcp';
|
|
18
|
+
import { isBestEffortTarget, parseEngineMap } from '$backend/artifacts';
|
|
19
|
+
import { debug } from '$shared/utils/logger';
|
|
20
|
+
import { mergeLayers, pickEngineSet, isToolAllowed, hasAnyRestriction, type ResolvedPermissions } from './resolve';
|
|
21
|
+
|
|
22
|
+
/** Engine keys used by the artifact matrix (config-dir slugs). */
|
|
23
|
+
export type ArtifactEngineKey = 'claude' | 'codex' | 'copilot' | 'qwen' | 'opencode';
|
|
24
|
+
|
|
25
|
+
const ENGINE_TYPE_TO_ARTIFACT: Record<EngineType, ArtifactEngineKey> = {
|
|
26
|
+
'claude-code': 'claude',
|
|
27
|
+
codex: 'codex',
|
|
28
|
+
copilot: 'copilot',
|
|
29
|
+
qwen: 'qwen',
|
|
30
|
+
opencode: 'opencode'
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export function toArtifactEngine(engine: EngineType): ArtifactEngineKey {
|
|
34
|
+
return ENGINE_TYPE_TO_ARTIFACT[engine];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The engine's built-in tools that a policy blocks (denied, or excluded by a
|
|
39
|
+
* non-empty allowlist). Used by adapters whose per-call permission hook does NOT
|
|
40
|
+
* fire for every tool (e.g. Qwen's `canUseTool` only runs for write tools) — the
|
|
41
|
+
* blocked names are passed to the SDK's `excludeTools` so read-only tools are
|
|
42
|
+
* hidden too. MCP tools are handled separately at the bridge, so only the
|
|
43
|
+
* built-in catalog is considered here.
|
|
44
|
+
*/
|
|
45
|
+
export function excludedBuiltinTools(permissions: ResolvedPermissions, engine: EngineType): string[] {
|
|
46
|
+
if (!hasAnyRestriction(permissions)) return [];
|
|
47
|
+
return (ENGINE_BUILTIN_TOOLS[engine] ?? []).filter(name => !isToolAllowed(permissions, name));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Effective allow/deny for one engine, merging the global set with the project
|
|
52
|
+
* set (if a project is streaming) and the active profile's overlay (if a profile
|
|
53
|
+
* is active). Layers apply least → most specific (global → project → profile);
|
|
54
|
+
* deny unions across all, the most specific allowlist wins. Reads the DB; the
|
|
55
|
+
* merge logic itself is pure (see resolve.ts).
|
|
56
|
+
*/
|
|
57
|
+
export function resolvePermissionsFromDb(engine: EngineType, projectId?: string, profileId?: number): ResolvedPermissions {
|
|
58
|
+
const global = pickEngineSet(permissionSetQueries.getGlobal(), engine);
|
|
59
|
+
const project = projectId
|
|
60
|
+
? pickEngineSet(permissionSetQueries.getForProject(projectId), engine)
|
|
61
|
+
: undefined;
|
|
62
|
+
const profile = profileId != null
|
|
63
|
+
? pickEngineSet(permissionSetQueries.getForProfile(profileId), engine)
|
|
64
|
+
: undefined;
|
|
65
|
+
return mergeLayers([global, project, profile]);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** One engine's stored rules for the Settings UI (scopes flattened by caller). */
|
|
69
|
+
export interface PermissionSetDTO {
|
|
70
|
+
scope: PermissionScope;
|
|
71
|
+
projectId: string | null;
|
|
72
|
+
profileId: number | null;
|
|
73
|
+
engine: EngineType;
|
|
74
|
+
allow: string[];
|
|
75
|
+
deny: string[];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface EngineInventory {
|
|
79
|
+
engine: EngineType;
|
|
80
|
+
/** Built-in tool names for this engine. */
|
|
81
|
+
builtin: string[];
|
|
82
|
+
/** Whether this engine's builtin names / enforcement are best-effort. */
|
|
83
|
+
bestEffort: boolean;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface PermissionInventory {
|
|
87
|
+
engines: EngineInventory[];
|
|
88
|
+
/** Live MCP tool names (namespaced), shared across engines. */
|
|
89
|
+
mcp: string[];
|
|
90
|
+
/** Tool names referenced by subagent allowlists. */
|
|
91
|
+
subagent: string[];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export const permissionService = {
|
|
95
|
+
/** All stored global/project permission sets for the admin listing. Profile
|
|
96
|
+
* overlays are excluded — they are managed in the profile editor. */
|
|
97
|
+
list(projectId?: string): PermissionSetDTO[] {
|
|
98
|
+
const rows = projectId
|
|
99
|
+
? [...permissionSetQueries.getGlobal(), ...permissionSetQueries.getForProject(projectId)]
|
|
100
|
+
: permissionSetQueries.getAll();
|
|
101
|
+
return rows
|
|
102
|
+
.filter(r => r.scope !== 'profile')
|
|
103
|
+
.map(r => ({ scope: r.scope, projectId: r.projectId, profileId: r.profileId, engine: r.engine, allow: r.allow, deny: r.deny }));
|
|
104
|
+
},
|
|
105
|
+
|
|
106
|
+
/** One profile's per-engine allow/deny overlay, for the profile editor. */
|
|
107
|
+
listForProfile(profileId: number): PermissionSetDTO[] {
|
|
108
|
+
return permissionSetQueries.getForProfile(profileId)
|
|
109
|
+
.map(r => ({ scope: r.scope, projectId: r.projectId, profileId: r.profileId, engine: r.engine, allow: r.allow, deny: r.deny }));
|
|
110
|
+
},
|
|
111
|
+
|
|
112
|
+
/** Upsert one (scope, project, profile, engine) rule set. Empty lists delete the row. */
|
|
113
|
+
save(
|
|
114
|
+
scope: PermissionScope,
|
|
115
|
+
projectId: string | null,
|
|
116
|
+
profileId: number | null,
|
|
117
|
+
engine: EngineType,
|
|
118
|
+
allow: string[],
|
|
119
|
+
deny: string[]
|
|
120
|
+
): void {
|
|
121
|
+
const clean = (list: string[]) => Array.from(new Set(list.map(s => s.trim()).filter(Boolean)));
|
|
122
|
+
permissionSetQueries.save(scope, projectId, profileId, engine, clean(allow), clean(deny));
|
|
123
|
+
const suffix = scope === 'project' && projectId ? `/${projectId.slice(0, 8)}` : scope === 'profile' && profileId ? `/p${profileId}` : '';
|
|
124
|
+
debug.log('permissions', `🔐 Saved permission set: ${engine}/${scope}${suffix}`);
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
/** Tool inventory offered by the UI as allow/deny targets. */
|
|
128
|
+
async inventory(): Promise<PermissionInventory> {
|
|
129
|
+
const engines: EngineInventory[] = ENGINES.map(e => ({
|
|
130
|
+
engine: e.type,
|
|
131
|
+
builtin: ENGINE_BUILTIN_TOOLS[e.type] ?? [],
|
|
132
|
+
bestEffort: ENGINE_TOOLS_BEST_EFFORT[e.type] ?? isBestEffortTarget('permission', toArtifactEngine(e.type))
|
|
133
|
+
}));
|
|
134
|
+
|
|
135
|
+
// Live MCP tools — best-effort: skip any server we can't connect to.
|
|
136
|
+
const mcpSet = new Set<string>();
|
|
137
|
+
for (const server of getEnabledExternalServers()) {
|
|
138
|
+
try {
|
|
139
|
+
const tools = await listExternalServerTools(server.slug);
|
|
140
|
+
// Claude-style namespaced name (`mcp__<namespace>__<tool>`) — the form
|
|
141
|
+
// the authoritative Claude hook sees. MCP exposure is primarily
|
|
142
|
+
// governed by Connectors (Prompt 2); these are a belt-and-suspenders
|
|
143
|
+
// deny target.
|
|
144
|
+
for (const tool of tools) mcpSet.add(`mcp__${server.namespace}__${tool.name}`);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
debug.warn('permissions', `Inventory: could not list tools for MCP "${server.slug}" (skipping):`, error);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Subagent allowlists — the tools individual subagents are scoped to
|
|
151
|
+
// (tools are per-engine now; union every engine's allowlist).
|
|
152
|
+
const subagentSet = new Set<string>();
|
|
153
|
+
for (const row of subagentQueries.getAll()) {
|
|
154
|
+
for (const list of Object.values(parseEngineMap(row.tools_by_engine))) {
|
|
155
|
+
for (const name of list.split(/[\s,]+/).map(t => t.trim()).filter(Boolean)) {
|
|
156
|
+
subagentSet.add(name);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
engines,
|
|
163
|
+
mcp: Array.from(mcpSet).sort(),
|
|
164
|
+
subagent: Array.from(subagentSet).sort()
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Profiles — reusable artifact bundles activated per-session.
|
|
3
|
+
*
|
|
4
|
+
* Public facade: the service (CRUD + inventory for Settings) plus the two pure
|
|
5
|
+
* resolution helpers the stream path calls to scope artifacts to the active
|
|
6
|
+
* profile. See `service.ts` for the design.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export { profileService, resolveActiveProfileId, artifactFilter } from './service';
|
|
10
|
+
export type { ProfileDTO, ProfileInventory, ProfileInventoryEntry } from './service';
|