osuite 2.10.0 → 2.10.1

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.
@@ -0,0 +1,219 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { setTimeout as delay } from 'node:timers/promises';
3
+ import { createApiClient, isObject, safeId, sha256 } from './protocol.mjs';
4
+ import { loadRuntimeConfig } from './config.mjs';
5
+ import { createStateStore } from './state.mjs';
6
+ import { resolveRemotePosture } from './posture.mjs';
7
+ import { applyPosture, emitRuntimeEvent, openSession } from './hook.mjs';
8
+ import { buildActionContext } from './context.mjs';
9
+ import { admitAction, cavaFingerprint, matchesAction } from './admission.mjs';
10
+ import { validateGitPublication } from './git.mjs';
11
+
12
+ const COVERAGE = 'Advisory MCP governance bridge, not an execution gateway. Direct resource access and alternative tools are outside coverage.';
13
+ const string = { type: 'string' };
14
+ const tool = (name, description, properties, required = []) => ({ name, description, inputSchema: { type: 'object', properties, required } });
15
+ export const MCP_TOOLS = [
16
+ tool('osuite_begin_session', 'Open an OSuite governance session; does not execute tools.', { client_name: string, client_version: string, session_label: string }),
17
+ tool('osuite_preflight_action', 'Check current policy and request one-use admission for exactly this tool input. Does not execute it.', {
18
+ action_type: string, declared_goal: string, risk_score: { type: 'number' }, tool_name: string, tool_use_id: string,
19
+ tool_input: {}, systems_touched: { type: 'array', items: string }, reversible: { type: 'boolean' }, metadata: { type: 'object' },
20
+ }, ['action_type', 'declared_goal', 'tool_name', 'tool_input']),
21
+ tool('osuite_record_assumption', 'Record an assumption for an action opened through this bridge.', { action_id: string, assumption: string, basis: string }, ['action_id', 'assumption']),
22
+ tool('osuite_wait_for_approval', 'Observe review status. A GET is not execution authority; resubmit the exact input through preflight.', { action_id: string, timeout_seconds: { type: 'number' } }, ['action_id']),
23
+ tool('osuite_complete_action', 'Record an explicit caller-reported outcome. This is not independent host proof of completion.', {
24
+ action_id: string, status: { enum: ['completed', 'failed', 'cancelled'] }, output_summary: string,
25
+ side_effects: { type: 'array', items: {} }, artifacts_created: { type: 'array', items: {} },
26
+ }, ['action_id', 'status']),
27
+ tool('osuite_replay_link', 'Return the Studio replay URL for this action.', { action_id: string }, ['action_id']),
28
+ tool('osuite_end_session', 'Mark the bridge conversation as ended; never infer tool outcomes.', { reason: string }),
29
+ ];
30
+
31
+ function result(data, error = false) {
32
+ const payload = { effect_executed: false, ...data };
33
+ return { content: [{ type: 'text', text: JSON.stringify(payload) }], structuredContent: payload, ...(error ? { isError: true } : {}) };
34
+ }
35
+ const failure = message => result({ authorized: false, error: message }, true);
36
+
37
+ export function createMcpServer(localConfig, dependencies = {}) {
38
+ let store = dependencies.store;
39
+ let sessionId = `sess_${randomUUID()}`;
40
+ const ensureStore = () => (store ||= createStateStore(localConfig));
41
+ const baseApi = () => dependencies.api || createApiClient(localConfig);
42
+
43
+ async function current() {
44
+ const remote = await resolveRemotePosture(localConfig, { api: baseApi(), store: ensureStore(), now: Date.now() });
45
+ if (!remote.available || remote.blocked) return null;
46
+ const config = applyPosture(localConfig, remote.posture);
47
+ if (config.signatureMode === 'required' && !config.privateKeyBase64) return null;
48
+ return { config, api: dependencies.api || createApiClient(config) };
49
+ }
50
+
51
+ async function complete(args, state, { api, config }) {
52
+ if (state.authorized !== true || !['completed', 'failed', 'cancelled'].includes(args.status)) return failure('An admitted action and an explicit terminal status are required.');
53
+ if (state.outcome_report && state.outcome_report.outcome.status !== args.status) return failure('A different outcome is already pending acknowledgement; reconcile rather than replace it.');
54
+ const key = `mcp:${args.action_id}`;
55
+ const report = state.outcome_report || {
56
+ outcome: { status: args.status, timestamp_end: new Date().toISOString(),
57
+ output_summary: `MCP caller reported ${args.status}; not independently verified by a host completion event.` },
58
+ action_reported: false,
59
+ };
60
+ state.outcome_report = report;
61
+ store.write(key, state);
62
+ if (!report.action_reported) {
63
+ const response = await api.request('PATCH', `/api/actions/${encodeURIComponent(args.action_id)}`, report.outcome);
64
+ const action = response.body?.action;
65
+ if (!response.ok || response.status !== 200 || action?.action_id !== args.action_id || action?.status !== report.outcome.status || action?.timestamp_end !== report.outcome.timestamp_end) {
66
+ return result({ recorded: false, action_id: args.action_id, message: 'Outcome acknowledgement is pending. Do not repeat the side effect.' }, true);
67
+ }
68
+ report.action_reported = true; store.write(key, state);
69
+ }
70
+ const event = {
71
+ event_id: `evt_mcp_outcome_${sha256(`${args.action_id}|${report.outcome.timestamp_end}`).slice(0, 24)}`,
72
+ runtime_session_id: state.context.runtime_session_id, event_type: args.status === 'completed' ? 'tool_completed' : 'tool_failed',
73
+ action_id: args.action_id, tool_name: state.tool_name, tool_use_id: state.context.tool_use_id,
74
+ payload: { status: args.status, outcome_source: 'mcp_caller_report', hook_mode: state.mode },
75
+ };
76
+ const response = await api.request('POST', `/api/runtime-sessions/${encodeURIComponent(event.runtime_session_id)}/events`, event);
77
+ if (!response.ok || response.status !== 200 || response.body?.ok !== true || !isObject(response.body.event)
78
+ || ['runtime_session_id', 'action_id', 'tool_use_id', 'event_type'].some(field => response.body.event[field] !== event[field])
79
+ || response.body.event.payload?.status !== args.status || response.body.event.payload?.outcome_source !== 'mcp_caller_report') {
80
+ return result({ recorded: false, action_id: args.action_id, message: 'Outcome event acknowledgement is pending. Do not repeat the side effect.' }, true);
81
+ }
82
+ store.remove(key);
83
+ return result({ recorded: true, action_id: args.action_id, status: args.status, outcome_source: 'mcp_caller_report' });
84
+ }
85
+
86
+ async function callTool(name, args = {}) {
87
+ try {
88
+ if (!MCP_TOOLS.some(item => item.name === name) || !isObject(args)) return failure('Unknown tool or invalid arguments.');
89
+ if (['osuite_record_assumption', 'osuite_wait_for_approval', 'osuite_complete_action', 'osuite_replay_link'].includes(name) && !safeId(args.action_id)) return failure('A valid action_id is required.');
90
+ if (name === 'osuite_replay_link') return result({ action_id: args.action_id, replay_href: `${localConfig.baseUrl}/replay/${encodeURIComponent(args.action_id)}` });
91
+ const state = args.action_id ? ensureStore().read(`mcp:${args.action_id}`) : null;
92
+ if (args.action_id && (!isObject(state) || state.schema !== 'osuite.mcp_action.v1')) return failure('This action has no admitted or held context in this bridge. Reconcile its record in Studio.');
93
+ const active = await current();
94
+ if (!active) return failure('Verified runtime posture or required signing is unavailable; no execution is authorized.');
95
+ const { api, config } = active;
96
+ if (name === 'osuite_complete_action') return complete(args, state, active);
97
+ if (name === 'osuite_record_assumption') {
98
+ if (typeof args.assumption !== 'string' || !args.assumption.trim() || args.assumption.length > 4000) return failure('A bounded assumption is required.');
99
+ const response = await api.request('POST', '/api/assumptions', { action_id: args.action_id, assumption: args.assumption,
100
+ basis: typeof args.basis === 'string' ? args.basis.slice(0, 1000) : 'MCP caller statement', validated: false });
101
+ if (!response.ok || !isObject(response.body?.assumption)) return failure('Assumption acknowledgement is pending.');
102
+ await emitRuntimeEvent(api, config, state.context, 'assumption_recorded', args.action_id, { source: 'mcp_caller_report' });
103
+ return result({ action_id: args.action_id, recorded: true, validated: false });
104
+ }
105
+ if (name === 'osuite_wait_for_approval') {
106
+ const requested = Number(args.timeout_seconds ?? 30);
107
+ const deadline = performance.now() + (Number.isFinite(requested) ? Math.max(0, Math.min(40, requested)) * 1000 : 0);
108
+ do {
109
+ const response = await api.request('GET', `/api/actions/${encodeURIComponent(args.action_id)}`, undefined, { timeoutMs: 2000 });
110
+ if ([401, 403].includes(response.status)) return failure('Approval access was rejected.');
111
+ if (response.ok) {
112
+ const action = response.body?.action || response.body;
113
+ if (!matchesAction(response.body, state.context, { actionId: args.action_id, fingerprint: state.fingerprint })) return failure('Approval evidence no longer matches the held tool input.');
114
+ if (action.status === 'running') {
115
+ const observed = Boolean(action.approved_by || action.approved_at) && action.approval_redeemed_at == null && action.timestamp_end == null;
116
+ return result({ action_id: args.action_id, approved: false, approval_observed: observed, authorized: false, status: 'running',
117
+ message: observed ? 'Submit exactly the same tool input through osuite_preflight_action again. A GET does not redeem a grant or authorize execution.'
118
+ : 'The outcome may be unknown or already consumed. Do not retry automatically; reconcile in Studio.' });
119
+ }
120
+ if (action.status !== 'pending_approval') return result({ action_id: args.action_id, approved: false, authorized: false, status: action.status, message: 'The held request is closed. Do not retry automatically.' });
121
+ }
122
+ if (performance.now() >= deadline) break;
123
+ await delay(Math.min(3000, deadline - performance.now()));
124
+ } while (performance.now() < deadline);
125
+ return result({ action_id: args.action_id, approved: false, authorized: false, status: 'timeout', message: 'Still held; do not execute this call.' });
126
+ }
127
+ await openSession(api, config, { session_id: sessionId }, store);
128
+ if (name === 'osuite_begin_session') return result({ runtime_session_id: sessionId, runtime_adapter_id: config.runtimeId, mode: config.mode, guard_failure_mode: config.guardFailureMode, coverage: COVERAGE });
129
+ if (name === 'osuite_end_session') {
130
+ await emitRuntimeEvent(api, config, { runtime_session_id: sessionId }, 'session_ended', null, { source: 'mcp_caller_report' });
131
+ const ended = sessionId; sessionId = `sess_${randomUUID()}`;
132
+ return result({ ended_runtime_session_id: ended });
133
+ }
134
+ if (typeof args.action_type !== 'string' || !args.action_type || args.action_type.length > 128 || typeof args.declared_goal !== 'string' || !args.declared_goal || args.declared_goal.length > 2000 || !Object.hasOwn(args, 'tool_input')) return failure('A bounded action_type, declared_goal and complete tool_input are required.');
135
+ const data = { session_id: sessionId, tool_name: args.tool_name, tool_input: args.tool_input, tool_use_id: args.tool_use_id || `tool_${randomUUID()}` };
136
+ const context = buildActionContext(data, config);
137
+ if (args.tool_name !== 'Bash') context.declared_goal = args.declared_goal;
138
+ if (Number.isSafeInteger(args.risk_score) && args.risk_score >= 0 && args.risk_score <= 100) context.risk_score = Math.max(context.risk_score, args.risk_score);
139
+ if (args.reversible === false) context.reversible = false;
140
+ const eventContext = { ...context, tool_name: args.tool_name };
141
+ await emitRuntimeEvent(api, config, eventContext, 'tool_preflight', null, { tool_input_digest: context.tool_input_digest, source: 'mcp_bridge' });
142
+ const admitted = await admitAction(context, { api, config: { ...config, approvalWaitMs: 0 }, beforeRelease: response => validateGitPublication(context, response) });
143
+ if (admitted.actionId && (admitted.authorized || admitted.decision === 'require_approval')) {
144
+ const key = `mcp:${admitted.actionId}`;
145
+ const previous = store.read(key);
146
+ if (previous?.outcome_report) return failure('An outcome is already pending for this action. Reconcile before any retry.');
147
+ store.write(key, { schema: 'osuite.mcp_action.v1', authorized: admitted.authorized, context, mode: config.mode,
148
+ tool_name: args.tool_name, fingerprint: cavaFingerprint(admitted.response) });
149
+ }
150
+ const eventType = admitted.degraded ? 'governance_unavailable' : admitted.authorized ? 'tool_allowed' : admitted.decision === 'require_approval' ? 'tool_requires_approval' : 'tool_blocked';
151
+ await emitRuntimeEvent(api, config, eventContext, eventType, admitted.actionId, { decision: admitted.degraded ? 'guard_unavailable' : admitted.decision, source: 'mcp_bridge' });
152
+ return result({ decision: admitted.decision, authorized: admitted.authorized === true && config.mode !== 'observe',
153
+ action_id: admitted.actionId || null, runtime_session_id: sessionId, coverage: COVERAGE,
154
+ ...(admitted.degraded ? { degraded: true } : {}),
155
+ message: admitted.authorized ? 'Current policy admitted this exact input. This bridge did not execute it.' : 'No execution is authorized. Review the action in Studio; do not retry automatically.',
156
+ }, !admitted.authorized && admitted.decision !== 'require_approval');
157
+ } catch { return failure('The governance request could not be confirmed. No execution is authorized; do not retry a side effect automatically.'); }
158
+ }
159
+
160
+ async function handleRequest(request) {
161
+ if (!isObject(request) || request.jsonrpc !== '2.0' || typeof request.method !== 'string') return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } };
162
+ if (!Object.hasOwn(request, 'id')) return null;
163
+ const response = { jsonrpc: '2.0', id: request.id };
164
+ if (request.method === 'initialize') return { ...response, result: {
165
+ protocolVersion: ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'].includes(request.params?.protocolVersion) ? request.params.protocolVersion : '2025-11-25',
166
+ capabilities: { tools: {} }, serverInfo: { name: 'osuite_runtime_governance', version: '1.1.0-node' }, instructions: COVERAGE,
167
+ } };
168
+ if (request.method === 'ping') return { ...response, result: {} };
169
+ if (request.method === 'tools/list') return { ...response, result: { tools: MCP_TOOLS } };
170
+ if (request.method === 'tools/call') return { ...response, result: await callTool(request.params?.name, request.params?.arguments ?? {}) };
171
+ return { ...response, error: { code: -32601, message: 'Method not found' } };
172
+ }
173
+ return { callTool, handleRequest };
174
+ }
175
+
176
+ export async function runMcpCli(options = {}) {
177
+ const server = createMcpServer(loadRuntimeConfig(options));
178
+ let buffer = Buffer.alloc(0), framing = null;
179
+ const maximum = 1048576;
180
+ const write = payload => {
181
+ if (!payload) return;
182
+ const encoded = JSON.stringify(payload);
183
+ process.stdout.write(framing === 'legacy' ? `Content-Length: ${Buffer.byteLength(encoded)}\r\n\r\n${encoded}` : `${encoded}\n`);
184
+ };
185
+ try {
186
+ for await (const chunk of process.stdin) {
187
+ buffer = Buffer.concat([buffer, chunk]);
188
+ // Backpressure processes one request at a time; neither framing accepts unbounded messages.
189
+ while (buffer.length) {
190
+ if (!framing && buffer.length >= 1) framing = buffer[0] === 67 || buffer[0] === 99 ? 'legacy' : 'ndjson';
191
+ let body;
192
+ if (framing === 'legacy') {
193
+ const end = buffer.indexOf('\r\n\r\n');
194
+ if (end < 0) { if (buffer.length > 8192) throw new Error('Oversized header'); break; }
195
+ const match = buffer.subarray(0, end).toString('ascii').match(/^Content-Length: ([0-9]+)\r?$/im);
196
+ const length = match ? Number(match[1]) : NaN;
197
+ if (!Number.isSafeInteger(length) || length < 1 || length > maximum) throw new Error('Invalid frame');
198
+ if (buffer.length < end + 4 + length) break;
199
+ body = buffer.subarray(end + 4, end + 4 + length); buffer = buffer.subarray(end + 4 + length);
200
+ } else {
201
+ const end = buffer.indexOf(10);
202
+ if (end < 0) break;
203
+ if (end > maximum) throw new Error('Oversized message');
204
+ body = buffer.subarray(0, end); buffer = buffer.subarray(end + 1);
205
+ if (!body.toString('utf8').trim()) continue;
206
+ }
207
+ try {
208
+ const decoded = new TextDecoder('utf-8', { fatal: true }).decode(body);
209
+ write(await server.handleRequest(JSON.parse(decoded)));
210
+ } catch { write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
211
+ }
212
+ if (buffer.length > maximum + 8192) throw new Error('Oversized message');
213
+ }
214
+ if (buffer.length) throw new Error('Incomplete message');
215
+ } catch {
216
+ write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Invalid or oversized MCP message' } });
217
+ process.exitCode = 1;
218
+ }
219
+ }
@@ -0,0 +1,98 @@
1
+ import { canonicalJson, isObject, safeId, sha256, toolInputDigest } from './protocol.mjs';
2
+ import { deriveToolUseId } from './context.mjs';
3
+
4
+ const pending = reason => ({ recorded: false, reason });
5
+
6
+ export function terminalOutcome(config, data, now = Date.now()) {
7
+ const response = data.tool_response;
8
+ let status;
9
+ let summary;
10
+ if (config.host === 'claude' && data.hook_event_name === 'PostToolUseFailure' && typeof data.error === 'string') {
11
+ status = 'failed';
12
+ summary = 'Runtime emitted PostToolUseFailure; details omitted.';
13
+ } else if (isObject(response)) {
14
+ const structured = isObject(response.structuredContent) ? response.structuredContent : response;
15
+ const error = [response, structured].some(value => value.error || value.isError === true || value.is_error === true || value.interrupted === true);
16
+ const exitCode = Object.hasOwn(response, 'exit_code') ? response.exit_code : structured.exit_code;
17
+ if (error) {
18
+ status = 'failed';
19
+ summary = 'Runtime reported a tool error; details omitted.';
20
+ } else if (Number.isSafeInteger(exitCode)) {
21
+ status = exitCode === 0 ? 'completed' : 'failed';
22
+ summary = `Runtime reported exit_code=${exitCode}; output omitted.`;
23
+ } else if (config.host === 'claude' && data.hook_event_name === 'PostToolUse'
24
+ && !response.backgroundTaskId && !response.background_task_id && !response.session_id
25
+ && data.tool_input?.run_in_background !== true) {
26
+ status = 'completed';
27
+ summary = 'Claude Code emitted a successful PostToolUse event; output omitted.';
28
+ }
29
+ }
30
+ // Codex may return stdout verbatim. Even JSON-looking strings are not metadata.
31
+ return status ? { status, output_summary: summary, timestamp_end: new Date(now).toISOString() } : null;
32
+ }
33
+
34
+ function validReport(report, provenance) {
35
+ const outcome = report?.outcome;
36
+ return isObject(outcome) && (provenance.schema === 'osuite.diagnostic_terminal_report.v1' ? outcome.status === 'cancelled' : ['completed', 'failed'].includes(outcome.status))
37
+ && Object.keys(outcome).sort().join(',') === 'output_summary,status,timestamp_end'
38
+ && typeof outcome.output_summary === 'string' && Number.isFinite(Date.parse(outcome.timestamp_end))
39
+ && typeof report.action_reported === 'boolean'
40
+ && canonicalJson(report.provenance) === canonicalJson(provenance);
41
+ }
42
+
43
+ export async function recordOutcome(config, data, { api, store, now = Date.now } = {}) {
44
+ if (!isObject(data)) return pending('invalid_hook_input');
45
+ const toolId = deriveToolUseId(data);
46
+ if (!safeId(toolId)) return pending('invalid_tool_id');
47
+ const key = `action:${toolId}`;
48
+ let state;
49
+ try { state = store.read(key); } catch { return pending('unreadable_action_state'); }
50
+ if (state === null) return { recorded: false, reason: null };
51
+ if (!isObject(state) || state.schema !== 'osuite.node_action.v1' || !safeId(state.action_id)
52
+ || (state.runtime_session_id && !safeId(state.runtime_session_id))) return pending('invalid_action_state');
53
+ if (state.tool_use_id !== toolId || (data.session_id && data.session_id !== state.runtime_session_id)
54
+ || (data.tool_name && data.tool_name !== state.tool_name)
55
+ || (data.tool_input !== undefined && toolInputDigest(data.tool_name || state.tool_name, data.tool_input) !== state.tool_input_digest)) {
56
+ return pending('state_binding_mismatch');
57
+ }
58
+ if (state.require_signature && !config.privateKeyBase64) return pending('signing_unavailable');
59
+ const provenance = { schema: state.install_check ? 'osuite.diagnostic_terminal_report.v1' : 'osuite.structured_terminal_report.v1', action_id: state.action_id, tool_use_id: toolId };
60
+ let report = state.outcome_report;
61
+ if (report !== undefined && !validReport(report, provenance)) return pending('untrusted_outcome_state');
62
+ if (report === undefined) {
63
+ const outcome = state.install_check ? { status: 'cancelled', timestamp_end: new Date(now()).toISOString(),
64
+ output_summary: 'Inert diagnostic hook probe; the tool was not executed.' } : terminalOutcome(config, data, now());
65
+ if (!outcome) return pending('terminal_evidence_missing');
66
+ report = { outcome, action_reported: false, provenance };
67
+ state.outcome_report = report;
68
+ try { store.write(key, state); } catch { return pending('state_persistence_failed'); }
69
+ }
70
+ const outcome = report.outcome;
71
+ if (!report.action_reported) {
72
+ const response = await api.request('PATCH', `/api/actions/${encodeURIComponent(state.action_id)}`, outcome, { timeoutMs: 2000 });
73
+ const action = response.body?.action;
74
+ if (!response.ok || response.status !== 200 || !isObject(action)
75
+ || action.action_id !== state.action_id || action.status !== outcome.status || action.timestamp_end !== outcome.timestamp_end) {
76
+ return pending('outcome_acknowledgement_pending');
77
+ }
78
+ report.action_reported = true;
79
+ try { store.write(key, state); } catch { return pending('state_persistence_failed'); }
80
+ }
81
+ if (state.runtime_session_id) {
82
+ const event = {
83
+ event_id: `evt_outcome_${sha256(`${state.runtime_session_id}|${state.action_id}|${toolId}|${outcome.timestamp_end}`).slice(0, 24)}`,
84
+ runtime_session_id: state.runtime_session_id,
85
+ event_type: state.install_check ? 'turn_stopped' : outcome.status === 'completed' ? 'tool_completed' : 'tool_failed',
86
+ tool_name: state.tool_name, tool_use_id: toolId, action_id: state.action_id,
87
+ timestamp: outcome.timestamp_end,
88
+ payload: { status: outcome.status, output_summary: outcome.output_summary, ...(state.install_check ? { install_check: true } : {}) },
89
+ };
90
+ const response = await api.request('POST', `/api/runtime-sessions/${encodeURIComponent(state.runtime_session_id)}/events`, event, { timeoutMs: 2000 });
91
+ const acknowledged = response.body?.event;
92
+ if (!response.ok || response.status !== 200 || response.body?.ok !== true || !isObject(acknowledged)
93
+ || ['runtime_session_id', 'event_type', 'tool_use_id', 'action_id'].some(field => acknowledged[field] !== event[field])
94
+ || acknowledged.payload?.status !== outcome.status) return pending('event_acknowledgement_pending');
95
+ }
96
+ try { store.remove(key); } catch { return pending('state_cleanup_pending'); }
97
+ return { recorded: true };
98
+ }
@@ -0,0 +1,103 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { canonicalJson, isObject, sha256 } from './protocol.mjs';
3
+
4
+ export const POSTURE_SCHEMA = 'osuite.runtime_posture.v1';
5
+ const MAX_FRESHNESS_MS = 300000;
6
+ const MODE_STRENGTH = { observe: 0, enforce: 1, strict: 2 };
7
+
8
+ export function localPosture(config) {
9
+ return {
10
+ runtime_id: config.runtimeId,
11
+ mode: Object.hasOwn(MODE_STRENGTH, config.mode) ? config.mode : 'enforce',
12
+ on_guard_unavailable: config.guardFailureMode === 'block' || config.mode === 'strict' ? 'block' : 'allow',
13
+ require_signature: config.signatureMode === 'required',
14
+ require_assumption_capture: config.requireAssumptionCapture === true,
15
+ approval_timeout_seconds: config.approvalTimeoutSeconds || 600,
16
+ };
17
+ }
18
+
19
+ function offlinePosture(local, cached) {
20
+ if (!cached) return local;
21
+ return {
22
+ ...cached,
23
+ mode: MODE_STRENGTH[local.mode] > MODE_STRENGTH[cached.mode] ? local.mode : cached.mode,
24
+ on_guard_unavailable: local.on_guard_unavailable === 'block' || cached.on_guard_unavailable === 'block' ? 'block' : 'allow',
25
+ require_signature: local.require_signature || cached.require_signature,
26
+ require_assumption_capture: local.require_assumption_capture || cached.require_assumption_capture,
27
+ approval_timeout_seconds: Math.min(local.approval_timeout_seconds, cached.approval_timeout_seconds),
28
+ };
29
+ }
30
+
31
+ function validDocument(value, config, now, allowExpired = false) {
32
+ if (!isObject(value) || value.schema_version !== POSTURE_SCHEMA || value.runtime_id !== config.runtimeId) return false;
33
+ if (typeof value.org_id !== 'string' || !value.org_id || typeof value.credential_id !== 'string' || !value.credential_id) return false;
34
+ if (config.orgId && config.orgId !== value.org_id) return false;
35
+ if (value.credential_fingerprint !== sha256(config.apiKey || '')) return false;
36
+ if (value.targeting?.agent_id !== config.agentId || (value.targeting?.provider || null) !== (config.provider || null)) return false;
37
+ if (typeof value.revision !== 'string' || !/^[a-f0-9]{64}$/.test(value.revision)) return false;
38
+ const posture = value.posture;
39
+ if (!isObject(posture) || posture.runtime_id !== config.runtimeId || !Object.hasOwn(MODE_STRENGTH, posture.mode)) return false;
40
+ if (!['allow', 'block'].includes(posture.on_guard_unavailable)) return false;
41
+ if (typeof posture.require_signature !== 'boolean' || typeof posture.require_assumption_capture !== 'boolean') return false;
42
+ if (!Number.isSafeInteger(posture.approval_timeout_seconds) || posture.approval_timeout_seconds < 1 || posture.approval_timeout_seconds > 3600) return false;
43
+ const issued = Date.parse(value.issued_at);
44
+ const until = Date.parse(value.valid_until);
45
+ return Number.isFinite(issued) && Number.isFinite(until) && issued <= now + 30000
46
+ && until > issued && until - issued <= MAX_FRESHNESS_MS && (allowExpired || until > now);
47
+ }
48
+
49
+ function configurationOnly(document) {
50
+ return Object.fromEntries([
51
+ 'schema_version', 'runtime_id', 'org_id', 'credential_id', 'credential_fingerprint',
52
+ 'targeting', 'posture', 'revision', 'issued_at', 'valid_until',
53
+ ].map(key => [key, document[key]]));
54
+ }
55
+
56
+ function mac(document, config) {
57
+ return createHmac('sha256', config.apiKey || '').update('osuite.posture-cache.v1\n').update(canonicalJson(document)).digest('hex');
58
+ }
59
+
60
+ function cachedDocument(value, config, now) {
61
+ try {
62
+ if (!isObject(value) || !validDocument(value.document, config, now, true) || !/^[a-f0-9]{64}$/.test(value.mac)) return null;
63
+ if (!timingSafeEqual(Buffer.from(value.mac, 'hex'), Buffer.from(mac(value.document, config), 'hex'))) return null;
64
+ return value.document;
65
+ } catch { return null; }
66
+ }
67
+
68
+ function readCache(store, config, now) {
69
+ try { return cachedDocument(store.read('posture'), config, now); } catch { return null; }
70
+ }
71
+
72
+ export async function resolveRemotePosture(config, { api, store, now = Date.now() }) {
73
+ const query = new URLSearchParams({ agent_id: config.agentId });
74
+ if (config.provider) query.set('provider', config.provider);
75
+ const response = await api.request('GET', `/api/runtimes/${encodeURIComponent(config.runtimeId)}/posture?${query}`, undefined, { timeoutMs: 2000 });
76
+ let cached = readCache(store, config, now);
77
+ if (response.ok && response.status === 200 && validDocument(response.body, config, now)
78
+ && (!cached || Date.parse(response.body.issued_at) >= Date.parse(cached.issued_at))) {
79
+ const document = configurationOnly(response.body);
80
+ try {
81
+ // The comparison and replacement share a cross-process lock. A stale
82
+ // response must not replace a stronger configuration published meanwhile.
83
+ const saved = store.update('posture', value => {
84
+ const latest = cachedDocument(value, config, now);
85
+ return latest && Date.parse(latest.issued_at) > Date.parse(document.issued_at)
86
+ ? value : { document, mac: mac(document, config) };
87
+ });
88
+ cached = cachedDocument(saved, config, now);
89
+ if (cached && canonicalJson(cached) === canonicalJson(document)) {
90
+ return { available: true, blocked: false, source: 'remote', posture: document.posture, revision: document.revision };
91
+ }
92
+ } catch {
93
+ const posture = offlinePosture(offlinePosture(localPosture(config), readCache(store, config, now)?.posture), document.posture);
94
+ return { available: false, blocked: posture.mode !== 'observe', source: 'unavailable', posture, revision: cached?.revision || null };
95
+ }
96
+ }
97
+ const posture = offlinePosture(localPosture(config), cached?.posture);
98
+ // Revocation and explicit scope rejection invalidate cached authority immediately.
99
+ if (response.status !== 401 && response.status !== 403 && cached && Date.parse(cached.valid_until) > now) {
100
+ return { available: true, blocked: false, source: 'cache', posture, revision: cached.revision };
101
+ }
102
+ return { available: false, blocked: posture.mode !== 'observe', source: 'unavailable', posture, revision: cached?.revision || null };
103
+ }
@@ -0,0 +1,96 @@
1
+ import { createHash, createPrivateKey, sign } from 'node:crypto';
2
+
3
+ export const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
+ export const sha256 = value => createHash('sha256').update(value).digest('hex');
5
+ export const safeId = value => typeof value === 'string' && /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,199}$/.test(value) && !value.includes('..');
6
+
7
+ export function canonicalJson(value) {
8
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
9
+ if (isObject(value)) return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(',')}}`;
10
+ return JSON.stringify(value) ?? 'null';
11
+ }
12
+
13
+ export function toolInputDigest(toolName, toolInput) {
14
+ return sha256(canonicalJson({ tool_name: toolName || '', tool_input: toolInput ?? {} }));
15
+ }
16
+
17
+ export function validatedBaseUrl(value, { allowInsecureHttp = false } = {}) {
18
+ try {
19
+ const url = new URL(value);
20
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
21
+ if (url.username || url.password || url.search || url.hash) return null;
22
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && (loopback || allowInsecureHttp))) return null;
23
+ return url.href.replace(/\/$/, '');
24
+ } catch { return null; }
25
+ }
26
+
27
+ export function createApiClient(config, { fetchImpl = globalThis.fetch, timeoutMs = 2500, maxResponseBytes = 262144 } = {}) {
28
+ return {
29
+ async request(method, endpoint, body, options = {}) {
30
+ const baseUrl = validatedBaseUrl(config.baseUrl, config);
31
+ if (!baseUrl) return { ok: false, status: 0, error: 'invalid_base_url' };
32
+ if (!config.apiKey) return { ok: false, status: 0, error: 'not_configured' };
33
+ if (typeof endpoint !== 'string' || !endpoint.startsWith('/') || endpoint.startsWith('//')) {
34
+ return { ok: false, status: 0, error: 'invalid_endpoint' };
35
+ }
36
+ let payload;
37
+ if (body !== undefined) {
38
+ if (!isObject(body)) return { ok: false, status: 0, error: 'invalid_request' };
39
+ // Canonicalize the JSON wire shape, not properties JSON would omit.
40
+ try { payload = JSON.parse(JSON.stringify(body)); } catch {
41
+ return { ok: false, status: 0, error: 'invalid_request' };
42
+ }
43
+ if (!isObject(payload)) return { ok: false, status: 0, error: 'invalid_request' };
44
+ delete payload._signature;
45
+ if (config.privateKeyBase64) {
46
+ try {
47
+ const key = createPrivateKey(Buffer.from(config.privateKeyBase64, 'base64'));
48
+ payload._signature = sign('sha256', Buffer.from(canonicalJson(payload)), key).toString('base64');
49
+ } catch {
50
+ // A supplied but invalid key is never an instruction to send unsigned.
51
+ return { ok: false, status: 0, error: 'signing_unavailable' };
52
+ }
53
+ } else if (config.signatureMode === 'required') {
54
+ return { ok: false, status: 0, error: 'signing_unavailable' };
55
+ }
56
+ }
57
+ const controller = new AbortController();
58
+ const timer = setTimeout(() => controller.abort(), Math.max(1, Math.min(options.timeoutMs ?? timeoutMs, 30000)));
59
+ let status = 0;
60
+ try {
61
+ const response = await fetchImpl(baseUrl + endpoint, {
62
+ method, redirect: 'manual', signal: controller.signal,
63
+ headers: { 'content-type': 'application/json', 'x-api-key': config.apiKey },
64
+ ...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
65
+ });
66
+ status = response.status;
67
+ if (status < 200 || status >= 300) {
68
+ await response.body?.cancel();
69
+ return { ok: false, status, error: 'http_error' };
70
+ }
71
+ const reader = response.body?.getReader();
72
+ if (!reader) return { ok: false, status, error: 'invalid_response' };
73
+ const chunks = [];
74
+ let length = 0;
75
+ while (true) {
76
+ const { value, done } = await reader.read();
77
+ if (done) break;
78
+ length += value.byteLength;
79
+ if (length > maxResponseBytes) {
80
+ await reader.cancel();
81
+ return { ok: false, status, error: 'invalid_response' };
82
+ }
83
+ chunks.push(Buffer.from(value));
84
+ }
85
+ let parsed;
86
+ try { parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch {
87
+ return { ok: false, status, error: 'invalid_response' };
88
+ }
89
+ if (!isObject(parsed)) return { ok: false, status, error: 'invalid_response' };
90
+ return { ok: true, status, body: parsed };
91
+ } catch {
92
+ return { ok: false, status, error: controller.signal.aborted ? 'timeout' : 'transport_failure' };
93
+ } finally { clearTimeout(timer); }
94
+ },
95
+ };
96
+ }