osuite 2.10.0 → 2.10.2
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/README.md +107 -75
- package/activationMetrics.js +116 -0
- package/cli.js +409 -57
- package/credentials.js +234 -0
- package/installationIdentity.js +113 -0
- package/osuite.js +32 -11
- package/package.json +9 -3
- package/projectHooks.js +204 -29
- package/runtime/admission.mjs +209 -0
- package/runtime/config.mjs +58 -0
- package/runtime/context.mjs +122 -0
- package/runtime/cursor.mjs +83 -0
- package/runtime/git.mjs +46 -0
- package/runtime/hook.mjs +202 -0
- package/runtime/mcp.mjs +219 -0
- package/runtime/outcome.mjs +98 -0
- package/runtime/posture.mjs +168 -0
- package/runtime/protocol.mjs +101 -0
- package/runtime/shell.mjs +186 -0
- package/runtime/state.mjs +83 -0
- package/tryContract.js +47 -0
- package/tryFlow.js +90 -0
package/projectHooks.js
CHANGED
|
@@ -5,8 +5,9 @@ import fs from 'node:fs';
|
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import crypto from 'node:crypto';
|
|
7
7
|
import { spawn } from 'node:child_process';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
8
9
|
|
|
9
|
-
const HOOK_SCRIPT_RE = /osuite_(?:pretool|posttool|stop)\.py/;
|
|
10
|
+
const HOOK_SCRIPT_RE = /osuite_(?:pretool|posttool|stop|session)\.(?:py|mjs)/;
|
|
10
11
|
|
|
11
12
|
export const RUNTIME_HOOKS = {
|
|
12
13
|
claude: {
|
|
@@ -20,6 +21,10 @@ export const RUNTIME_HOOKS = {
|
|
|
20
21
|
settings: ['.codex/hooks.json'],
|
|
21
22
|
config: '.codex/config.toml',
|
|
22
23
|
},
|
|
24
|
+
cursor: {
|
|
25
|
+
label: 'Cursor', dir: '.cursor', settings: ['.cursor/hooks.json'],
|
|
26
|
+
preEvent: 'preToolUse', postEvent: 'postToolUse', flatHooks: true,
|
|
27
|
+
},
|
|
23
28
|
};
|
|
24
29
|
|
|
25
30
|
const MERGED_FILES = {
|
|
@@ -27,6 +32,9 @@ const MERGED_FILES = {
|
|
|
27
32
|
'.claude/settings.local.json': 'json',
|
|
28
33
|
'.codex/hooks.json': 'json',
|
|
29
34
|
'.codex/config.toml': 'toml',
|
|
35
|
+
'.mcp.json': 'mcp',
|
|
36
|
+
'.cursor/hooks.json': 'cursor-hooks',
|
|
37
|
+
'.cursor/mcp.json': 'mcp',
|
|
30
38
|
};
|
|
31
39
|
|
|
32
40
|
export const DOCTOR_COMMAND = 'echo "OSuite doctor hook check"';
|
|
@@ -45,7 +53,7 @@ function hookScriptName(command) {
|
|
|
45
53
|
function sameHook(existing, wanted) {
|
|
46
54
|
const existingScript = hookScriptName(existing?.command);
|
|
47
55
|
const wantedScript = hookScriptName(wanted?.command);
|
|
48
|
-
if (existingScript && wantedScript) return existingScript === wantedScript;
|
|
56
|
+
if (existingScript && wantedScript) return existingScript.replace(/\.(py|mjs)$/, '') === wantedScript.replace(/\.(py|mjs)$/, '');
|
|
49
57
|
return String(existing?.command || '').trim() === String(wanted?.command || '').trim();
|
|
50
58
|
}
|
|
51
59
|
|
|
@@ -96,30 +104,163 @@ export function mergeHookSettings(existingText, templateText) {
|
|
|
96
104
|
const wanted = isPlainObject(template.hooks) ? template.hooks : {};
|
|
97
105
|
const merged = { ...hooks };
|
|
98
106
|
const added = [];
|
|
107
|
+
const migrated = [];
|
|
108
|
+
const migrationConflicts = [];
|
|
99
109
|
for (const [event, groups] of Object.entries(wanted)) {
|
|
100
110
|
const current = merged[event] === undefined ? [] : merged[event];
|
|
101
111
|
if (!Array.isArray(current)) return { status: 'error', error: `"hooks.${event}" must be a list` };
|
|
102
|
-
const
|
|
103
|
-
const next = [
|
|
112
|
+
const requested = (Array.isArray(groups) ? groups : []).flatMap(group => group.hooks || []);
|
|
113
|
+
const next = current.map(group => ({ ...group, hooks: (group.hooks || []).map(existing => {
|
|
114
|
+
const replacement = requested.find(hook => sameHook(existing, hook));
|
|
115
|
+
if (!replacement || !hookScriptName(existing.command).endsWith('.py') || !hookScriptName(replacement.command).endsWith('.mjs')) return existing;
|
|
116
|
+
const script = hookScriptName(existing.command);
|
|
117
|
+
const stock = [`python3 .claude/hooks/${script}`, `python3 .codex/hooks/${script}`,
|
|
118
|
+
`python3 "$(git rev-parse --show-toplevel)/.codex/hooks/${script}"`];
|
|
119
|
+
if (!stock.includes(existing.command)) {
|
|
120
|
+
migrationConflicts.push(`custom legacy ${script} command was preserved; review its Node migration before relying on this installation`);
|
|
121
|
+
return existing;
|
|
122
|
+
}
|
|
123
|
+
migrated.push({ event, matcher: group.matcher, command: replacement.command });
|
|
124
|
+
return { ...existing, ...replacement };
|
|
125
|
+
}) }));
|
|
126
|
+
const present = next.flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []));
|
|
104
127
|
for (const group of Array.isArray(groups) ? groups : []) {
|
|
105
128
|
const missing = (group.hooks || []).filter((hook) => !present.some((existing) => sameHook(existing, hook)));
|
|
106
129
|
if (!missing.length) continue;
|
|
107
130
|
next.push({ ...group, hooks: missing });
|
|
108
131
|
missing.forEach((hook) => added.push({ event, matcher: group.matcher, command: hook.command }));
|
|
109
132
|
}
|
|
110
|
-
if (next.length !== current.length) merged[event] = next;
|
|
133
|
+
if (next.length !== current.length || migrated.some(item => item.event === event)) merged[event] = next;
|
|
111
134
|
}
|
|
112
135
|
|
|
113
136
|
const result = {
|
|
114
|
-
added,
|
|
137
|
+
added, migrated,
|
|
115
138
|
keptHooks: countHooks(hooks),
|
|
116
139
|
keptKeys: Object.keys(settings).filter((key) => key !== 'hooks'),
|
|
117
|
-
conflicts: disabledHookSettings(settings),
|
|
140
|
+
conflicts: [...disabledHookSettings(settings), ...migrationConflicts],
|
|
118
141
|
};
|
|
119
|
-
if (!added.length) return { ...result, status: 'unchanged', body: existingText };
|
|
142
|
+
if (!added.length && !migrated.length) return { ...result, status: 'unchanged', body: existingText };
|
|
120
143
|
return { ...result, status: 'merged', body: `${JSON.stringify({ ...settings, hooks: merged }, null, 2)}\n` };
|
|
121
144
|
}
|
|
122
145
|
|
|
146
|
+
function mergeMcpSettings(existingText, templateText) {
|
|
147
|
+
const template = JSON.parse(templateText);
|
|
148
|
+
const existing = existingText ? JSON.parse(existingText) : {};
|
|
149
|
+
if (!isPlainObject(existing) || (existing.mcpServers !== undefined && !isPlainObject(existing.mcpServers))) return { status: 'error', error: 'expected an MCP configuration object' };
|
|
150
|
+
const servers = { ...(existing.mcpServers || {}) };
|
|
151
|
+
const added = [], conflicts = [];
|
|
152
|
+
for (const [name, server] of Object.entries(template.mcpServers || {})) {
|
|
153
|
+
if (servers[name] && JSON.stringify(servers[name]) !== JSON.stringify(server)) {
|
|
154
|
+
conflicts.push(`${name} MCP registration differs; it was preserved for explicit operator review`);
|
|
155
|
+
} else if (!servers[name]) { servers[name] = server; added.push(name); }
|
|
156
|
+
}
|
|
157
|
+
return { status: existingText == null ? 'created' : added.length ? 'merged' : 'unchanged', added, conflicts,
|
|
158
|
+
body: added.length || existingText == null ? `${JSON.stringify({ ...existing, mcpServers: servers }, null, 2)}\n` : existingText };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function mergeCursorHookSettings(existingText, templateText) {
|
|
162
|
+
const template = JSON.parse(templateText);
|
|
163
|
+
const existing = existingText == null ? { version: 1, hooks: {} } : JSON.parse(existingText);
|
|
164
|
+
if (!isPlainObject(existing) || existing.version !== 1 || !isPlainObject(existing.hooks ?? {})) {
|
|
165
|
+
return { status: 'error', error: 'Cursor hooks require version 1 and a hooks object; existing configuration was preserved' };
|
|
166
|
+
}
|
|
167
|
+
const hooks = { ...(existing.hooks || {}) }, added = [], conflicts = [...disabledHookSettings(existing)];
|
|
168
|
+
for (const [event, handlers] of Object.entries(hooks)) {
|
|
169
|
+
if (!Array.isArray(handlers)) return { status: 'error', error: `hooks.${event} must be a list; existing configuration was preserved` };
|
|
170
|
+
}
|
|
171
|
+
// Cursor does not document this flag. Do not rely on it to suppress newly
|
|
172
|
+
// added hooks when preserving an operator's explicit disablement intent.
|
|
173
|
+
if (existing.disableAllHooks === true) return { status: 'unchanged', body: existingText, added: [],
|
|
174
|
+
conflicts: ['Existing disableAllHooks intent was preserved; no Cursor hook registrations were added'],
|
|
175
|
+
keptHooks: Object.values(hooks).reduce((count, handlers) => count + handlers.length, 0),
|
|
176
|
+
keptKeys: Object.keys(existing).filter(key => key !== 'hooks') };
|
|
177
|
+
for (const [event, handlers] of Object.entries(template.hooks)) {
|
|
178
|
+
const next = [...(hooks[event] || [])];
|
|
179
|
+
for (const handler of handlers) {
|
|
180
|
+
const present = next.find(current => sameHook(current, handler));
|
|
181
|
+
if (!present) { next.push(handler); added.push({ event, ...handler }); }
|
|
182
|
+
else if (present.command !== handler.command || present.enabled === false || present.disabled === true || !['command', undefined].includes(present.type)
|
|
183
|
+
|| (event === 'preToolUse' && (present.failClosed !== true || !['', '*', undefined].includes(present.matcher)))) {
|
|
184
|
+
conflicts.push(`custom Cursor ${event} command or safety flags were preserved; review before relying on this installation`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
hooks[event] = next;
|
|
188
|
+
}
|
|
189
|
+
return { status: existingText == null ? 'created' : added.length ? 'merged' : 'unchanged', added, conflicts,
|
|
190
|
+
keptHooks: Object.values(existing.hooks || {}).reduce((count, handlers) => count + handlers.length, 0),
|
|
191
|
+
keptKeys: Object.keys(existing).filter(key => key !== 'hooks'),
|
|
192
|
+
body: existingText == null || added.length ? `${JSON.stringify({ ...existing, hooks }, null, 2)}\n` : existingText };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function packagedRuntimeFiles(directory) {
|
|
196
|
+
const source = fileURLToPath(new URL('./runtime/', import.meta.url));
|
|
197
|
+
return Object.fromEntries(fs.readdirSync(source).sort().filter(name => /^[a-zA-Z0-9-]+\.mjs$/.test(name))
|
|
198
|
+
.map(name => [`${directory}/runtime/${name}`, fs.readFileSync(path.join(source, name), 'utf8')]));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function buildCursorBootstrap(bootstrap) {
|
|
202
|
+
const files = { ...bootstrap.files, ...packagedRuntimeFiles('.cursor') };
|
|
203
|
+
const events = { preToolUse: 'pretool', postToolUse: 'posttool', sessionStart: 'session', stop: 'stop' };
|
|
204
|
+
const hooks = {};
|
|
205
|
+
for (const [event, script] of Object.entries(events)) {
|
|
206
|
+
files[`.cursor/hooks/osuite_${script}.mjs`] = `#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runCursorHookCli } from '../runtime/cursor.mjs';\nawait runCursorHookCli({ installDir: fileURLToPath(new URL('..', import.meta.url)), event: ${JSON.stringify(event)} });\n`;
|
|
207
|
+
hooks[event] = [{ command: `node .cursor/hooks/osuite_${script}.mjs`, timeout: 60, ...(event === 'preToolUse' ? { failClosed: true } : {}) }];
|
|
208
|
+
}
|
|
209
|
+
hooks.postToolUseFailure = hooks.postToolUse;
|
|
210
|
+
hooks.sessionEnd = hooks.sessionStart;
|
|
211
|
+
files['.cursor/hooks.json'] = `${JSON.stringify({ version: 1, hooks }, null, 2)}\n`;
|
|
212
|
+
files['.cursor/server/osuite_runtime_mcp.mjs'] = "#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runMcpCli } from '../runtime/mcp.mjs';\nawait runMcpCli({ host: 'cursor', runtimeId: 'cursor_hooks', installDir: fileURLToPath(new URL('..', import.meta.url)) });\n";
|
|
213
|
+
files['.cursor/mcp.json'] = `${JSON.stringify({ mcpServers: { osuite_runtime_governance: {
|
|
214
|
+
type: 'stdio', command: 'node', args: ['${workspaceFolder}/.cursor/server/osuite_runtime_mcp.mjs'],
|
|
215
|
+
} } }, null, 2)}\n`;
|
|
216
|
+
files['.cursor/README.node-runtime.md'] = '# OSuite Cursor Node runtime\n\nNode.js 18+; no Python or runtime dependency installation.\nProject hooks run from the project root in a trusted workspace. Preserve explicit disabled settings.\nGeneric Agent hooks are installed, not Tab hooks. Session start does not block; every preflight refreshes verified posture.\nThe MCP bridge is advisory and does not execute upstream tools.\nDirect diagnostics and wire fixtures do not establish native host invocation or all-action coverage.\n';
|
|
217
|
+
return { ...bootstrap, files, runtime: { ...bootstrap.runtime, id: 'cursor_hooks', implementation: 'node', implementation_version: 1 },
|
|
218
|
+
node_runtime: { schema_version: 'osuite.node_runtime.v1', minimum_node_major: 18, settings_path: '.cursor/hooks.json', requires_host_trust_review: true } };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Locally packaged, dependency-free runtime code replaces downloaded legacy launchers. */
|
|
222
|
+
export function buildNodeRuntimeBootstrap(runtime, bootstrap = {}, { projectRoot = process.cwd() } = {}) {
|
|
223
|
+
if (['cursor', 'cursor_hooks'].includes(runtime)) return buildCursorBootstrap(bootstrap);
|
|
224
|
+
const host = ['claude', 'claude-code', 'claude_code_hooks'].includes(runtime) ? 'claude'
|
|
225
|
+
: ['codex', 'codex_hooks'].includes(runtime) ? 'codex' : null;
|
|
226
|
+
if (!host) throw new Error('Node bootstrap supports Claude Code, Codex and Cursor project hooks only');
|
|
227
|
+
const directory = host === 'claude' ? '.claude' : '.codex';
|
|
228
|
+
const runtimeId = host === 'claude' ? 'claude_code_hooks' : 'codex_hooks';
|
|
229
|
+
const files = Object.fromEntries(Object.entries(bootstrap.files || {}).filter(([name]) => !/osuite_(pretool|posttool|stop)\.py$/.test(name)
|
|
230
|
+
&& !['.claude/settings.json', '.claude/settings.local.json', '.codex/hooks.json', '.codex/config.toml'].includes(name)));
|
|
231
|
+
Object.assign(files, packagedRuntimeFiles(directory));
|
|
232
|
+
const literal = value => JSON.stringify(value);
|
|
233
|
+
const shellQuote = value => `'${String(value).replace(/'/g, "'\\''")}'`;
|
|
234
|
+
const events = { PreToolUse: 'pretool', PostToolUse: 'posttool', SessionStart: 'session', Stop: 'stop' };
|
|
235
|
+
const settings = { hooks: {} };
|
|
236
|
+
for (const [event, script] of Object.entries(events)) {
|
|
237
|
+
files[`${directory}/hooks/osuite_${script}.mjs`] = `#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runHookCli } from '../runtime/hook.mjs';\nawait runHookCli({ host: ${literal(host)}, runtimeId: ${literal(runtimeId)}, installDir: fileURLToPath(new URL('..', import.meta.url)), event: ${literal(event)} });\n`;
|
|
238
|
+
const absolute = path.join(path.resolve(projectRoot), directory, `hooks/osuite_${script}.mjs`);
|
|
239
|
+
const handler = { type: 'command', command: `node ${shellQuote(absolute)}`, timeout: 60 };
|
|
240
|
+
if (host === 'codex') handler.commandWindows = `node "${absolute.replace(/"/g, '""')}"`;
|
|
241
|
+
settings.hooks[event] = [{ hooks: [handler] }];
|
|
242
|
+
}
|
|
243
|
+
if (host === 'claude') settings.hooks.PostToolUseFailure = settings.hooks.PostToolUse;
|
|
244
|
+
let settingsPath = host === 'claude' ? '.claude/settings.json' : '.codex/hooks.json';
|
|
245
|
+
if (host === 'claude') {
|
|
246
|
+
// Do not duplicate an existing registration across project and local layers.
|
|
247
|
+
for (const candidate of ['.claude/settings.json', '.claude/settings.local.json']) {
|
|
248
|
+
try {
|
|
249
|
+
const current = JSON.parse(fs.readFileSync(path.join(projectRoot, candidate), 'utf8'));
|
|
250
|
+
if (Object.values(current.hooks || {}).some(groups => Array.isArray(groups) && groups.some(group => (group.hooks || []).some(hook => HOOK_SCRIPT_RE.test(hook.command || ''))))) { settingsPath = candidate; break; }
|
|
251
|
+
} catch { /* The installer reports malformed settings without overwriting them. */ }
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
files[settingsPath] = `${JSON.stringify(settings, null, 2)}\n`;
|
|
255
|
+
files[`${directory}/server/osuite_runtime_mcp.mjs`] = `#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runMcpCli } from '../runtime/mcp.mjs';\nawait runMcpCli({ host: ${literal(host)}, runtimeId: ${literal(runtimeId)}, installDir: fileURLToPath(new URL('..', import.meta.url)) });\n`;
|
|
256
|
+
const mcpScript = path.join(path.resolve(projectRoot), directory, 'server/osuite_runtime_mcp.mjs');
|
|
257
|
+
if (host === 'claude') files['.mcp.json'] = `${JSON.stringify({ mcpServers: { osuite_runtime_governance: { command: 'node', args: [mcpScript] } } }, null, 2)}\n`;
|
|
258
|
+
else files['.codex/config.toml'] = `[features]\nhooks = true\n\n[mcp_servers.osuite_runtime_governance]\ncommand = "node"\nargs = [${literal(mcpScript)}]\n`;
|
|
259
|
+
files[`${directory}/README.node-runtime.md`] = '# OSuite Node runtime\n\nNode.js 18+ is required. No Python or runtime package installation is used.\nHooks read only this installation\'s .env and the process environment.\nRemote posture is refreshed at session start and preflight; expired enforce configuration blocks.\nReview changed hook definitions in the host. Existing disabled settings are preserved.\nDoctor is a direct diagnostic, not proof that the host has trusted or invoked a hook.\nThe MCP bridge does not execute upstream tools or prevent direct resource access.\n';
|
|
260
|
+
return { ...bootstrap, files, runtime: { ...bootstrap.runtime, implementation: 'node', implementation_version: 1 },
|
|
261
|
+
node_runtime: { schema_version: 'osuite.node_runtime.v1', minimum_node_major: 18, settings_path: settingsPath, requires_host_trust_review: host === 'codex' } };
|
|
262
|
+
}
|
|
263
|
+
|
|
123
264
|
// --- TOML ------------------------------------------------------------------
|
|
124
265
|
// Line-based on purpose: the CLI has no dependencies, and the partial only sets
|
|
125
266
|
// plain keys. Lines inside multi-line strings and arrays are skipped.
|
|
@@ -269,6 +410,9 @@ export function mergeTomlPartial(existingText, partialText) {
|
|
|
269
410
|
const current = scan.values.get(fullKey);
|
|
270
411
|
if (current !== entry.value && !HOOK_FLAGS.includes(fullKey)) {
|
|
271
412
|
kept.push({ key: describeTomlEntry({ ...entry, value: current }), suggested: entry.value });
|
|
413
|
+
if (entry.table === 'mcp_servers.osuite_runtime_governance') {
|
|
414
|
+
conflicts.push(`OSuite MCP ${entry.key} differs; the existing registration was preserved for explicit operator review`);
|
|
415
|
+
}
|
|
272
416
|
}
|
|
273
417
|
continue;
|
|
274
418
|
}
|
|
@@ -379,7 +523,8 @@ export function installProjectFile(projectRoot, relativePath, body, { force = fa
|
|
|
379
523
|
if (kind) {
|
|
380
524
|
let merge;
|
|
381
525
|
try {
|
|
382
|
-
merge = kind === 'json' ? mergeHookSettings(existing, String(body ?? '')) :
|
|
526
|
+
merge = kind === 'json' ? mergeHookSettings(existing, String(body ?? '')) : kind === 'cursor-hooks' ? mergeCursorHookSettings(existing, String(body ?? ''))
|
|
527
|
+
: kind === 'mcp' ? mergeMcpSettings(existing, String(body ?? '')) : mergeTomlPartial(existing, String(body ?? ''));
|
|
383
528
|
} catch (error) {
|
|
384
529
|
merge = { status: 'error', error: `OSuite template could not be read (${error.message})` };
|
|
385
530
|
}
|
|
@@ -415,11 +560,12 @@ export function describeInstallResult(result) {
|
|
|
415
560
|
lines.push(`failed ${name}: ${result.error}. Nothing was changed; fix the file and run this again.`);
|
|
416
561
|
return lines;
|
|
417
562
|
}
|
|
418
|
-
if (result.kind === 'json') {
|
|
563
|
+
if (result.kind === 'json' || result.kind === 'cursor-hooks') {
|
|
419
564
|
if (result.status === 'unchanged') lines.push(`unchanged ${name} (OSuite hooks already there)`);
|
|
420
565
|
else lines.push(`${result.status === 'created' ? 'created' : 'merged '} ${name}`);
|
|
421
566
|
if (result.status !== 'unchanged') {
|
|
422
567
|
result.added.forEach((hook) => lines.push(` + ${hook.event} ${hook.matcher || '*'} → ${hook.command}`));
|
|
568
|
+
(result.migrated || []).forEach((hook) => lines.push(` migrated ${hook.event} to Node; review the changed hook in the host`));
|
|
423
569
|
}
|
|
424
570
|
if (result.status === 'merged') {
|
|
425
571
|
const others = result.keptKeys.length ? ` and your other settings (${result.keptKeys.join(', ')})` : '';
|
|
@@ -452,11 +598,14 @@ function readJson(absolute) {
|
|
|
452
598
|
return JSON.parse(fs.readFileSync(absolute, 'utf8'));
|
|
453
599
|
}
|
|
454
600
|
|
|
455
|
-
function
|
|
601
|
+
function eventHooks(settings, event, flat = false) {
|
|
456
602
|
const groups = Array.isArray(settings?.hooks?.[event]) ? settings.hooks[event] : [];
|
|
457
|
-
return groups
|
|
458
|
-
|
|
459
|
-
|
|
603
|
+
return flat ? groups : groups.flatMap(group => Array.isArray(group?.hooks) ? group.hooks : []);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function findCommand(settings, event, script, flat = false) {
|
|
607
|
+
return eventHooks(settings, event, flat)
|
|
608
|
+
.find((hook) => typeof hook?.command === 'string' && hookScriptName(hook.command).replace(/\.(py|mjs)$/, '') === script.replace(/\.(py|mjs)$/, '')) || null;
|
|
460
609
|
}
|
|
461
610
|
|
|
462
611
|
/** OSuite hooks registered in this project, with anything that stops them from running. */
|
|
@@ -466,6 +615,8 @@ export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIM
|
|
|
466
615
|
if (!spec) return [];
|
|
467
616
|
const problems = [];
|
|
468
617
|
const disabledReasons = [];
|
|
618
|
+
let pretoolCount = 0;
|
|
619
|
+
let posttoolCount = 0;
|
|
469
620
|
let pretool = null;
|
|
470
621
|
let posttool = null;
|
|
471
622
|
spec.settings.forEach((settingsPath) => {
|
|
@@ -478,18 +629,32 @@ export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIM
|
|
|
478
629
|
problems.push(`${settingsPath} is not valid JSON, so ${spec.label} cannot load its hooks`);
|
|
479
630
|
return;
|
|
480
631
|
}
|
|
481
|
-
disabledHookSettings(settings).forEach((reason) => disabledReasons.push(`${settingsPath}: ${
|
|
482
|
-
|
|
483
|
-
const
|
|
632
|
+
disabledHookSettings(settings).forEach((reason) => disabledReasons.push(`${settingsPath}: ${runtime === 'cursor'
|
|
633
|
+
? 'explicit disableAllHooks intent was preserved; this is not a documented Cursor host control' : reason}`));
|
|
634
|
+
const preEvent = spec.preEvent || 'PreToolUse', postEvent = spec.postEvent || 'PostToolUse';
|
|
635
|
+
const pre = findCommand(settings, preEvent, 'osuite_pretool.py', spec.flatHooks);
|
|
636
|
+
const post = findCommand(settings, postEvent, 'osuite_posttool.py', spec.flatHooks);
|
|
637
|
+
pretoolCount += eventHooks(settings, preEvent, spec.flatHooks)
|
|
638
|
+
.filter(hook => /osuite_pretool\.(?:py|mjs)/.test(hook?.command || '')).length;
|
|
639
|
+
posttoolCount += eventHooks(settings, postEvent, spec.flatHooks)
|
|
640
|
+
.filter(hook => /osuite_posttool\.(?:py|mjs)/.test(hook?.command || '')).length;
|
|
641
|
+
if (runtime === 'cursor') {
|
|
642
|
+
if (settings.version !== 1) problems.push(`${settingsPath} is not Cursor hooks schema version 1`);
|
|
643
|
+
if ([pre, post].some(handler => handler && !['command', undefined].includes(handler.type))) problems.push('Cursor OSuite hooks must use command execution type, not a prompt');
|
|
644
|
+
if (pre && pre.failClosed !== true) problems.push('Cursor preToolUse must have failClosed: true to block hook process failures');
|
|
645
|
+
if (pre && !['', '*', undefined].includes(pre.matcher)) problems.push('Cursor preToolUse matcher restricts coverage; the custom matcher was preserved');
|
|
646
|
+
if (pre?.disabled === true || pre?.enabled === false) disabledReasons.push('Cursor preToolUse contains explicit disabled intent; it was preserved');
|
|
647
|
+
}
|
|
484
648
|
if (pre && !pretool) pretool = { settingsPath, command: pre.command };
|
|
485
649
|
if (post && !posttool) posttool = { settingsPath, command: post.command };
|
|
486
650
|
});
|
|
651
|
+
if (!disabledReasons.length && (pretoolCount > 1 || posttoolCount > 1)) problems.push('Multiple OSuite hook registrations were preserved; resolve duplicate hooks before relying on a single governed invocation');
|
|
487
652
|
|
|
488
653
|
const scriptPath = `${spec.dir}/hooks/osuite_pretool.py`;
|
|
489
|
-
const scriptPresent = fs.existsSync(path.join(projectRoot, scriptPath));
|
|
654
|
+
const scriptPresent = fs.existsSync(path.join(projectRoot, scriptPath)) || fs.existsSync(path.join(projectRoot, scriptPath.replace(/\.py$/, '.mjs')));
|
|
490
655
|
if (!pretool && !scriptPresent && !problems.length) return [];
|
|
491
656
|
if (!pretool) {
|
|
492
|
-
problems.push(`no PreToolUse hook in ${spec.settings.join(' or ')} runs osuite_pretool
|
|
657
|
+
problems.push(`no ${spec.preEvent || 'PreToolUse'} hook in ${spec.settings.join(' or ')} runs osuite_pretool.${runtime === 'cursor' ? 'mjs' : 'py'}`);
|
|
493
658
|
}
|
|
494
659
|
if (spec.config) {
|
|
495
660
|
const config = readIfExists(path.join(projectRoot, spec.config));
|
|
@@ -530,7 +695,7 @@ export function hookCredentials(projectRoot, installation, shellEnv = process.en
|
|
|
530
695
|
baseUrl: String(env.OSUITE_BASE_URL || env.DASHCLAW_BASE_URL || '').replace(/\/$/, ''),
|
|
531
696
|
apiKey: String(env.OSUITE_API_KEY || env.DASHCLAW_API_KEY || ''),
|
|
532
697
|
envFile: `${installation.installDir}/.env`,
|
|
533
|
-
hookMode: String(env.OSUITE_HOOK_MODE || env.DASHCLAW_HOOK_MODE || 'enforce'),
|
|
698
|
+
hookMode: String(env.OSUITE_HOOK_MODE || env.DASHCLAW_HOOK_MODE || (installation.runtime === 'cursor' ? 'observe' : 'enforce')),
|
|
534
699
|
};
|
|
535
700
|
}
|
|
536
701
|
|
|
@@ -563,7 +728,8 @@ function hookMessages(stdout) {
|
|
|
563
728
|
return String(stdout || '').split(/\r?\n/).flatMap((line) => {
|
|
564
729
|
try {
|
|
565
730
|
const parsed = JSON.parse(line);
|
|
566
|
-
return
|
|
731
|
+
return [...new Set(['systemMessage', 'user_message', 'agent_message', 'additional_context']
|
|
732
|
+
.map(field => parsed?.[field]).filter(value => typeof value === 'string' && value))];
|
|
567
733
|
} catch {
|
|
568
734
|
return [];
|
|
569
735
|
}
|
|
@@ -595,7 +761,7 @@ async function fetchSessionEvents(fetchImpl, { baseUrl, apiKey, sessionId }) {
|
|
|
595
761
|
}
|
|
596
762
|
|
|
597
763
|
/**
|
|
598
|
-
* Directly probe the registered hook with an inert
|
|
764
|
+
* Directly probe the registered hook with an inert shell call. Configuration,
|
|
599
765
|
* telemetry, and policy outcomes are separate checks; this is not a host launch.
|
|
600
766
|
*/
|
|
601
767
|
export async function runHookCheck({
|
|
@@ -636,11 +802,12 @@ export async function runHookCheck({
|
|
|
636
802
|
const id = crypto.randomBytes(4).toString('hex');
|
|
637
803
|
sessionId = `osuite-doctor-${id}`;
|
|
638
804
|
const toolUseId = `osuite_doctor_${id}`;
|
|
805
|
+
const cursor = installation.runtime === 'cursor';
|
|
639
806
|
const sample = {
|
|
640
|
-
session_id: sessionId,
|
|
807
|
+
...(cursor ? { conversation_id: sessionId, generation_id: `osuite-doctor-generation-${id}` } : { session_id: sessionId }),
|
|
641
808
|
cwd: projectRoot,
|
|
642
|
-
hook_event_name: 'PreToolUse',
|
|
643
|
-
tool_name: 'Bash',
|
|
809
|
+
hook_event_name: cursor ? 'preToolUse' : 'PreToolUse',
|
|
810
|
+
tool_name: cursor ? 'Shell' : 'Bash',
|
|
644
811
|
tool_input: { command: DOCTOR_COMMAND, description: 'OSuite doctor hook check' },
|
|
645
812
|
tool_use_id: toolUseId,
|
|
646
813
|
};
|
|
@@ -664,7 +831,7 @@ export async function runHookCheck({
|
|
|
664
831
|
steps.push({
|
|
665
832
|
ok: true,
|
|
666
833
|
label: 'Hook test',
|
|
667
|
-
detail: `sample
|
|
834
|
+
detail: `sample ${sample.tool_name} call (${DOCTOR_COMMAND}) ${run.code === 0 ? 'allowed' : 'stopped'} by the hook${run.code === 2 && said ? `: ${said}` : ''}`,
|
|
668
835
|
});
|
|
669
836
|
|
|
670
837
|
let lookup = await fetchSessionEvents(fetchImpl, { ...credentials, sessionId });
|
|
@@ -682,8 +849,9 @@ export async function runHookCheck({
|
|
|
682
849
|
timeoutMs,
|
|
683
850
|
input: JSON.stringify({
|
|
684
851
|
...sample,
|
|
685
|
-
hook_event_name: 'PostToolUse',
|
|
686
|
-
|
|
852
|
+
hook_event_name: cursor ? 'postToolUse' : 'PostToolUse',
|
|
853
|
+
...(cursor ? { tool_output: JSON.stringify({ exitCode: 0 }) }
|
|
854
|
+
: { tool_response: { stdout: 'OSuite doctor hook check', stderr: '', interrupted: false, exit_code: 0 } }),
|
|
687
855
|
}),
|
|
688
856
|
});
|
|
689
857
|
}
|
|
@@ -703,7 +871,10 @@ export async function runHookCheck({
|
|
|
703
871
|
detail: `${[...new Set(seen.map((event) => event.event_type))].join(', ')} reached OSuite (session ${sessionId})`,
|
|
704
872
|
});
|
|
705
873
|
|
|
706
|
-
const
|
|
874
|
+
const nodeHook = /\bosuite_pretool\.mjs\b/.test(installation.pretool.command);
|
|
875
|
+
const preflightModes = seen.filter((event) => event.event_type === 'tool_preflight')
|
|
876
|
+
.map((event) => event.payload?.hook_mode).filter((mode) => ['observe', 'enforce', 'strict'].includes(mode));
|
|
877
|
+
const observing = (!preflightModes.length && credentials.hookMode === 'observe') || seen.some((event) => (
|
|
707
878
|
event.payload?.hook_mode === 'observe' || event.payload?.observe_only === true
|
|
708
879
|
|| String(event.payload?.decision || '').startsWith('observe_')
|
|
709
880
|
));
|
|
@@ -712,6 +883,9 @@ export async function runHookCheck({
|
|
|
712
883
|
if (unavailable) return fail('Governance', `Not governed: guard unavailable; the hook ${run.code === 0 ? 'failed open' : 'failed closed'}, and telemetry alone does not verify governance`);
|
|
713
884
|
const ungoverned = warnings.find((warning) => /Not governed/i.test(warning));
|
|
714
885
|
if (ungoverned) return fail('Governance', ungoverned);
|
|
886
|
+
if (nodeHook && !preflightModes.some((mode) => mode === 'enforce' || mode === 'strict')) {
|
|
887
|
+
return fail('Governance', 'Not verified: no matching event-time enforcing posture was recorded for the sample call');
|
|
888
|
+
}
|
|
715
889
|
|
|
716
890
|
const outcome = seen.find((event) => {
|
|
717
891
|
const decision = event.payload?.decision;
|
|
@@ -725,6 +899,7 @@ export async function runHookCheck({
|
|
|
725
899
|
&& ['require_approval', 'require_dual_approval'].includes(decision);
|
|
726
900
|
}
|
|
727
901
|
if (event.event_type === 'tool_blocked' && decision === 'block') {
|
|
902
|
+
if (nodeHook) return event.payload?.reason === 'policy_block';
|
|
728
903
|
return event.payload?.reason !== 'action_creation_not_authorized'
|
|
729
904
|
&& !String(event.payload?.reason || '').startsWith('Unsupported guard decision:');
|
|
730
905
|
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
|
+
import { canonicalJson, isObject, safeId, RULE_ROLLOUT_CAPABILITY } from './protocol.mjs';
|
|
3
|
+
|
|
4
|
+
export const REVIEW_DECISIONS = new Set(['require_approval', 'require_dual_approval']);
|
|
5
|
+
const DECISIONS = new Set(['allow', 'warn', 'block', ...REVIEW_DECISIONS]);
|
|
6
|
+
const closed = (reason, extra = {}) => ({ authorized: false, decision: 'block', reason, retryAutomatically: false, ...extra });
|
|
7
|
+
|
|
8
|
+
function rolloutSnapshots(payload) {
|
|
9
|
+
const current = isObject(payload?.decision) ? payload.decision : payload;
|
|
10
|
+
return [current?.policy_snapshot, payload?.contracts?.policy_snapshot, payload?.action?.policy_snapshot,
|
|
11
|
+
payload?.action?.proof_bundle?.policy_snapshot, payload?.contracts?.proof_bundle?.policy_snapshot].filter(isObject);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function rolloutAuthority(payload, context, config, expected) {
|
|
15
|
+
const current = isObject(payload?.decision) ? payload.decision : payload;
|
|
16
|
+
const snapshots = rolloutSnapshots(payload);
|
|
17
|
+
const present = [current, ...snapshots].filter(isObject)
|
|
18
|
+
.some(value => Object.hasOwn(value, 'rule_rollout') || Object.hasOwn(value, 'rule_rollout_binding'));
|
|
19
|
+
const negotiated = config.ruleRollout;
|
|
20
|
+
if (!present && !expected && !negotiated?.enabled) return { valid: true, binding: null };
|
|
21
|
+
const binding = current?.rule_rollout_binding, report = current?.rule_rollout;
|
|
22
|
+
const scopeKeys = ['org_id', 'runtime_id', 'agent_id', 'provider', 'connection_id'];
|
|
23
|
+
const digest = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
|
|
24
|
+
// These fields arrive from the authenticated API, never the tool request.
|
|
25
|
+
// Their only authority is to forbid observe bypass, not to grant execution.
|
|
26
|
+
if (expected === null || !isObject(binding) || !isObject(report) || (negotiated && !negotiated.enabled)
|
|
27
|
+
|| binding.schema_version !== 'osuite.rule_rollout_binding.v1' || binding.enforcement_required !== true
|
|
28
|
+
|| !isObject(binding.scope) || Object.keys(binding.scope).length !== scopeKeys.length
|
|
29
|
+
|| scopeKeys.some(key => !safeId(binding.scope[key]) || binding.scope[key].length > 128)
|
|
30
|
+
|| binding.scope.agent_id !== config.agentId || binding.scope.agent_id !== context.agent_id
|
|
31
|
+
|| binding.scope.runtime_id !== config.runtimeId
|
|
32
|
+
|| (negotiated?.enabled && (binding.version !== negotiated.version || canonicalJson(binding.scope) !== canonicalJson(negotiated.scope)
|
|
33
|
+
|| binding.credential_id !== negotiated.credential_id || binding.connection_generation !== negotiated.connection_generation
|
|
34
|
+
|| binding.expires_at !== negotiated.expires_at))
|
|
35
|
+
|| (config.orgId && binding.scope.org_id !== config.orgId) || (config.provider && binding.scope.provider !== config.provider)
|
|
36
|
+
|| !Number.isSafeInteger(binding.version) || binding.version < 1
|
|
37
|
+
|| !Number.isFinite(approvalTime(binding.expires_at)) || approvalTime(binding.expires_at) <= Date.now()
|
|
38
|
+
|| !safeId(binding.runtime_session_id) || binding.runtime_session_id !== context.runtime_session_id
|
|
39
|
+
|| !digest(binding.tool_input_digest) || binding.tool_input_digest !== context.tool_input_digest
|
|
40
|
+
|| !binding.action_type || binding.action_type !== context.action_type
|
|
41
|
+
|| !digest(binding.policy_context_fingerprint) || binding.policy_context_fingerprint !== current.policy_context_fingerprint
|
|
42
|
+
|| report.schema_version !== 'osuite.rule_rollout_evaluation.v1' || report.status !== 'evaluated'
|
|
43
|
+
|| report.version !== binding.version || report.expires_at !== binding.expires_at
|
|
44
|
+
|| canonicalJson(report.scope) !== canonicalJson(binding.scope)
|
|
45
|
+
|| !isObject(current.policy_snapshot) || !snapshots.length
|
|
46
|
+
|| current.policy_snapshot.effective_decision !== ({ block: 'deny', warn: 'allow_with_evidence' }[current.decision] || current.decision)
|
|
47
|
+
|| snapshots.some(snapshot => canonicalJson(snapshot.rule_rollout_binding) !== canonicalJson(binding)
|
|
48
|
+
|| canonicalJson(snapshot.rule_rollout) !== canonicalJson(report))
|
|
49
|
+
|| (expected && canonicalJson(binding) !== canonicalJson(expected))) return { valid: false, binding: null };
|
|
50
|
+
return { valid: true, binding };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function approvalReceipts(payload) {
|
|
54
|
+
const action = payload?.action || payload || {};
|
|
55
|
+
return [action.approval_receipts, action.proof_bundle?.approval_receipts,
|
|
56
|
+
payload?.approval_receipts, payload?.contracts?.proof_bundle?.approval_receipts]
|
|
57
|
+
.flatMap(value => Array.isArray(value) ? value.filter(isObject) : []);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function cavaFingerprint(payload) {
|
|
61
|
+
return [payload?.contracts?.action_envelope?.cava?.fingerprint,
|
|
62
|
+
payload?.contracts?.proof_bundle?.action_envelope?.cava?.fingerprint,
|
|
63
|
+
payload?.action?.action_envelope?.cava?.fingerprint,
|
|
64
|
+
payload?.action?.proof_bundle?.action_envelope?.cava?.fingerprint,
|
|
65
|
+
payload?.action_envelope?.cava?.fingerprint, payload?.proof_bundle?.action_envelope?.cava?.fingerprint]
|
|
66
|
+
.find(value => typeof value === 'string' && value.trim()) || null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function matchesAction(payload, context, { actionId = null, fingerprint = null } = {}) {
|
|
70
|
+
const action = payload?.action || payload;
|
|
71
|
+
if (!isObject(action) || !safeId(action.action_id)) return false;
|
|
72
|
+
if (actionId && action.action_id !== actionId) return false;
|
|
73
|
+
if (payload.action_id && payload.action_id !== action.action_id) return false;
|
|
74
|
+
if (action.tool_input_digest && action.tool_input_digest !== context.tool_input_digest) return false;
|
|
75
|
+
if (action.agent_id && action.agent_id !== context.agent_id) return false;
|
|
76
|
+
if (action.runtime_session_id && action.runtime_session_id !== context.runtime_session_id) return false;
|
|
77
|
+
for (const envelope of [action.action_envelope, payload.contracts?.action_envelope]) {
|
|
78
|
+
if (envelope?.runtime_session_id !== undefined && envelope.runtime_session_id !== context.runtime_session_id) return false;
|
|
79
|
+
}
|
|
80
|
+
if (fingerprint) {
|
|
81
|
+
const receipts = approvalReceipts(payload).filter(receipt => ['allow', 'approved', 'approve'].includes(receipt.decision || receipt.status));
|
|
82
|
+
const fingerprints = receipts.flatMap(receipt => {
|
|
83
|
+
const scope = receipt.approval_scope || {};
|
|
84
|
+
if (scope.reusable === true || (receipt.action_id || scope.action_id) !== action.action_id) return [];
|
|
85
|
+
return [receipt.canonical_fingerprint || scope.canonical_fingerprint].filter(Boolean);
|
|
86
|
+
});
|
|
87
|
+
if (fingerprints.length ? !fingerprints.includes(fingerprint) : cavaFingerprint(payload) !== fingerprint) return false;
|
|
88
|
+
}
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function approvalTime(value) {
|
|
93
|
+
return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(value)
|
|
94
|
+
? Date.parse(value) : NaN;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function confirmedRedemption({ action, approval }) {
|
|
98
|
+
if (approval?.state !== 'approved' || approval.reused !== true || action.approval_decision !== 'allow'
|
|
99
|
+
|| typeof action.approved_by !== 'string' || !action.approved_by.trim()) return false;
|
|
100
|
+
const approvedAt = approvalTime(action.approved_at);
|
|
101
|
+
const redeemedAt = approvalTime(action.approval_redeemed_at);
|
|
102
|
+
const expiresAt = approvalTime(action.approval_expires_at);
|
|
103
|
+
const now = Date.now();
|
|
104
|
+
// A GET-shaped approval is not a redeemed grant. These are consistency checks,
|
|
105
|
+
// not independent proof of the server's atomic update or exactly-once effects.
|
|
106
|
+
if (![approvedAt, redeemedAt, expiresAt].every(Number.isFinite)
|
|
107
|
+
|| approvedAt > redeemedAt || redeemedAt > now || expiresAt <= now) return false;
|
|
108
|
+
if (approval.decided_by !== undefined && approval.decided_by !== action.approved_by) return false;
|
|
109
|
+
if (approval.decided_at !== undefined && approvalTime(approval.decided_at) !== approvedAt) return false;
|
|
110
|
+
if (approval.expires_at !== undefined && approvalTime(approval.expires_at) !== expiresAt) return false;
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function actionAdmission(payload, requestedDecision, context, expected = {}) {
|
|
115
|
+
if (!isObject(payload) || payload.error || !isObject(payload.action) || !safeId(payload.action_id)
|
|
116
|
+
|| payload.action.action_id !== payload.action_id || !matchesAction(payload, context)) return closed('action_creation_not_authorized');
|
|
117
|
+
const actionId = payload.action_id;
|
|
118
|
+
const action = payload.action;
|
|
119
|
+
const decision = payload.decision?.decision;
|
|
120
|
+
const base = { actionId, response: payload };
|
|
121
|
+
if (!DECISIONS.has(decision) || !['running', 'pending_approval'].includes(action.status)
|
|
122
|
+
|| (payload.status !== undefined && payload.status !== action.status)
|
|
123
|
+
|| action.timestamp_end != null || ['denied', 'expired'].includes(payload.approval?.state)
|
|
124
|
+
|| requestedDecision === 'block' || decision === 'block') return closed('action_creation_not_authorized', base);
|
|
125
|
+
if (action.status === 'pending_approval') return { ...base, authorized: false, decision: 'require_approval', reason: 'awaiting_approval' };
|
|
126
|
+
if (REVIEW_DECISIONS.has(decision) || REVIEW_DECISIONS.has(requestedDecision)) {
|
|
127
|
+
if (!confirmedRedemption(payload)
|
|
128
|
+
|| !matchesAction(payload, context, expected)) return closed('approval_not_confirmed', base);
|
|
129
|
+
return { ...base, authorized: true, decision: 'approved_by_reviewer' };
|
|
130
|
+
}
|
|
131
|
+
return { ...base, authorized: true, decision: decision === 'warn' || requestedDecision === 'warn' ? 'warn' : 'allow' };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function installCheck(payload, context) {
|
|
135
|
+
if (!context.health_check || payload?.approval?.state !== 'not_requested') return null;
|
|
136
|
+
if (payload.error || !safeId(payload.action_id) || payload.action?.action_id !== payload.action_id
|
|
137
|
+
|| payload.action?.status !== 'cancelled' || (payload.status !== undefined && payload.status !== 'cancelled')
|
|
138
|
+
|| !REVIEW_DECISIONS.has(payload.decision?.decision)) return closed('invalid_install_check');
|
|
139
|
+
return { authorized: false, decision: payload.decision.decision, installCheck: true, reason: 'approval_not_requested', response: payload };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(), beforeRelease = async () => true } = {}) {
|
|
143
|
+
const guard = await api.request('POST', '/api/guard', context);
|
|
144
|
+
if (!guard.ok) {
|
|
145
|
+
const failOpen = config.ruleRolloutCapability !== RULE_ROLLOUT_CAPABILITY && !config.ruleRollout?.enabled
|
|
146
|
+
&& config.guardFailureMode === 'allow' && ![401, 403, 409].includes(guard.status)
|
|
147
|
+
&& !['signing_unavailable', 'invalid_response', 'invalid_request'].includes(guard.error);
|
|
148
|
+
return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true };
|
|
149
|
+
}
|
|
150
|
+
const requestedDecision = guard.body?.decision;
|
|
151
|
+
if (!DECISIONS.has(requestedDecision)) return closed('unsupported_guard_decision');
|
|
152
|
+
const rollout = rolloutAuthority(guard.body, context, config);
|
|
153
|
+
if (!rollout.valid) return closed('rule_rollout_binding_invalid');
|
|
154
|
+
const finish = result => rollout.binding ? { ...result, observeOnly: false, ruleRolloutBinding: rollout.binding } : result;
|
|
155
|
+
if (requestedDecision === 'block') {
|
|
156
|
+
// Observation still persists the would-block result, but never calls it authority.
|
|
157
|
+
const observeOnly = config.mode === 'observe' && !rollout.binding;
|
|
158
|
+
if (observeOnly) await api.request('POST', '/api/actions', { ...context, status: 'blocked' });
|
|
159
|
+
return finish({ ...closed('policy_block'), observeOnly, response: guard.body });
|
|
160
|
+
}
|
|
161
|
+
const created = await api.request('POST', '/api/actions', {
|
|
162
|
+
...context, status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running',
|
|
163
|
+
});
|
|
164
|
+
if (!created.ok) return closed('admission_unconfirmed');
|
|
165
|
+
if (!rolloutAuthority(created.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid');
|
|
166
|
+
const diagnostic = installCheck(created.body, context);
|
|
167
|
+
if (diagnostic) return finish(diagnostic);
|
|
168
|
+
let result = finish(actionAdmission(created.body, requestedDecision, context));
|
|
169
|
+
if (result.authorized) return await beforeRelease(result.response) ? result : closed('action_evidence_changed');
|
|
170
|
+
if (result.decision !== 'require_approval') return result;
|
|
171
|
+
if (config.mode === 'observe' && !rollout.binding) return { ...result, observeOnly: true };
|
|
172
|
+
|
|
173
|
+
const expected = { actionId: result.actionId, fingerprint: cavaFingerprint(created.body) };
|
|
174
|
+
const waitMs = Math.max(0, Math.min(config.approvalWaitMs ?? 30000, 600000));
|
|
175
|
+
const deadline = now() + waitMs;
|
|
176
|
+
while (now() < deadline) {
|
|
177
|
+
await sleep(Math.min(3000, Math.max(0, deadline - now())));
|
|
178
|
+
if (rollout.binding && approvalTime(rollout.binding.expires_at) <= Date.now()) return closed('rule_rollout_expired', { actionId: expected.actionId });
|
|
179
|
+
const polled = await api.request('GET', `/api/actions/${encodeURIComponent(expected.actionId)}`, undefined, {
|
|
180
|
+
timeoutMs: Math.max(1, Math.min(2500, deadline - now())),
|
|
181
|
+
});
|
|
182
|
+
if (!polled.ok) {
|
|
183
|
+
if ([401, 403].includes(polled.status)) return closed('approval_access_rejected', { actionId: expected.actionId });
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const action = polled.body?.action || polled.body;
|
|
187
|
+
if (!matchesAction(polled.body, context, expected)) return closed('approval_binding_mismatch', { actionId: expected.actionId });
|
|
188
|
+
if (rollout.binding) {
|
|
189
|
+
const snapshots = rolloutSnapshots(polled.body);
|
|
190
|
+
if (!snapshots.length || snapshots.some(snapshot => canonicalJson(snapshot.rule_rollout_binding) !== canonicalJson(rollout.binding))) {
|
|
191
|
+
return closed('rule_rollout_binding_invalid', { actionId: expected.actionId });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (action.status === 'pending_approval') continue;
|
|
195
|
+
if (action.status !== 'running') return closed('approval_closed', { actionId: expected.actionId });
|
|
196
|
+
if (action.approval_redeemed_at != null || action.timestamp_end != null) return closed('execution_outcome_unknown', { actionId: expected.actionId });
|
|
197
|
+
if (!(action.approved_by || action.approved_at) || polled.body.approval?.state === 'denied') {
|
|
198
|
+
return closed('approval_not_confirmed', { actionId: expected.actionId });
|
|
199
|
+
}
|
|
200
|
+
// GET observes a grant. Only this fresh POST may redeem it. Never retry a lost reply.
|
|
201
|
+
const current = await api.request('POST', '/api/actions', { ...context, status: 'running' });
|
|
202
|
+
if (!current.ok) return closed('admission_unconfirmed', { actionId: expected.actionId });
|
|
203
|
+
if (!rolloutAuthority(current.body, context, config, rollout.binding).valid) return closed('rule_rollout_binding_invalid', { actionId: expected.actionId });
|
|
204
|
+
result = finish(actionAdmission(current.body, 'allow', context, expected));
|
|
205
|
+
if (result.authorized && !await beforeRelease(result.response)) return closed('action_evidence_changed', { actionId: result.actionId });
|
|
206
|
+
return result;
|
|
207
|
+
}
|
|
208
|
+
return result;
|
|
209
|
+
}
|