diff --git a/docs/index.html b/docs/index.html index b457606..bbb67ea 100755 --- a/docs/index.html +++ b/docs/index.html @@ -3390,6 +3390,10 @@ + +
+
Scope Receipts0 pending
+
No pending scope receipts.
+
@@ -4303,6 +4311,28 @@ + +
+
+
+
ScopeGuard
+
Scope Receipts
+
+
+ + +
+
+
+
+
+
Approval Requests
+
0 receipts
+
+
+
+
+
@@ -6022,12 +6052,18 @@ tempest.operators.spawn('scan this._eventSource.addEventListener('connected', () => { console.log('[BackendDispatch] SSE connected'); try { fetchToolApprovals(); } catch {} + try { fetchScopeReceipts(); } catch {} }); // Capability-approval gate: every gated tool decision (allow/deny) + spicy warning. this._eventSource.addEventListener('arsenal.approval', (e) => { try { pushApprovalAuditEvent(JSON.parse(e.data)); } catch {} }); + ['approval.requested', 'approval.approved', 'approval.rejected'].forEach((eventName) => { + this._eventSource.addEventListener(eventName, () => { + try { fetchScopeReceipts(); } catch {} + }); + }); this._eventSource.addEventListener('operator:spawned', (e) => { try { @@ -7238,14 +7274,115 @@ Correlating findings across agents, identifying patterns, producing actionable i } }, 3000); + const ReceiptsState = { approvals: [] }; + + function receiptStatusColor(status) { + const s = String(status || '').toLowerCase(); + if (s === 'approved') return '#00ff88'; + if (s === 'pending') return '#ffaa00'; + if (s === 'rejected' || s === 'expired') return '#ff6666'; + return 'var(--text-secondary)'; + } + + window.refreshReceiptsPage = async function refreshReceiptsPage() { + const data = await T3MP3ST_API.get('/api/approvals'); + ReceiptsState.approvals = Array.isArray(data.approvals) ? data.approvals : []; + renderReceiptsPage(); + }; + + window.approveReceipt = async function approveReceipt(id) { + const receipt = ReceiptsState.approvals.find(function(a){ return a.id === id; }); + await T3MP3ST_API.post('/api/approvals/' + id + '/approve', {}); + await window.refreshReceiptsPage(); + if (window.toast) toast('Receipt approved: ' + id, 'success'); + if (receipt?.action === 'autonomous_execution' && window.__t3mpAdmiralPendingRetry && typeof window.retryPendingAdmiralLaunch === 'function') { + window.retryPendingAdmiralLaunch(); + } + }; + + window.rejectReceipt = async function rejectReceipt(id) { + await T3MP3ST_API.post('/api/approvals/' + id + '/reject', {}); + await window.refreshReceiptsPage(); + if (window.toast) toast('Receipt rejected: ' + id, 'warning'); + }; + + window.approveAllPendingReceipts = async function approveAllPendingReceipts() { + const pending = ReceiptsState.approvals.filter(function(a){ return a.status === 'pending'; }); + await Promise.all(pending.map(function(a){ return T3MP3ST_API.post('/api/approvals/' + a.id + '/approve', {}); })); + await window.refreshReceiptsPage(); + if (window.toast) toast('Approved ' + pending.length + ' pending receipt(s)', pending.length ? 'success' : 'info'); + if (pending.some(function(a){ return a.action === 'autonomous_execution'; }) && window.__t3mpAdmiralPendingRetry && typeof window.retryPendingAdmiralLaunch === 'function') { + window.retryPendingAdmiralLaunch(); + } + }; + + function renderReceiptsPage() { + const approvals = ReceiptsState.approvals || []; + const pending = approvals.filter(function(a){ return a.status === 'pending'; }).length; + const approved = approvals.filter(function(a){ return a.status === 'approved'; }).length; + const closed = approvals.filter(function(a){ return a.status === 'expired' || a.status === 'rejected'; }).length; + const badge = document.getElementById('pendingReceiptCount'); + if (badge) { + badge.textContent = String(pending); + badge.style.background = pending ? '#ffaa00' : 'rgba(255,255,255,0.12)'; + badge.style.color = pending ? '#1b1200' : ''; + } + const summary = document.getElementById('receiptsSummary'); + if (summary) { + const cells = [ + ['Pending', pending, pending ? '#ffaa00' : 'var(--text-secondary)'], + ['Approved', approved, '#00ff88'], + ['Closed', closed, closed ? '#ff6666' : 'var(--text-secondary)'], + ['Total', approvals.length, '#00aaff'] + ]; + summary.innerHTML = cells.map(function(cell){ + return '
' + + '
' + escapeHtml(cell[0]) + '
' + + '
' + escapeHtml(cell[1]) + '
' + + '
'; + }).join(''); + } + const count = document.getElementById('receiptsCount'); + if (count) count.textContent = approvals.length + ' receipts'; + const list = document.getElementById('receiptsList'); + if (!list) return; + if (!approvals.length) { + list.innerHTML = '
No receipts yet. Live external actions will create target-scoped approval requests here.
'; + return; + } + list.innerHTML = approvals.map(function(a){ + const color = receiptStatusColor(a.status); + const pendingActions = a.status === 'pending' + ? '
' + : ''; + return '
' + + '
' + + '
' + escapeHtml(a.id) + '' + escapeHtml(a.status || 'unknown') + '
' + + '
' + escapeHtml(a.target || '-') + '
' + + '
' + escapeHtml(a.action || '-') + ' Β· ' + escapeHtml(a.requestedBy || '-') + '
' + + '
' + escapeHtml(a.reason || '') + '
' + + (a.expiresAt ? '
Expires ' + escapeHtml(new Date(a.expiresAt).toLocaleString()) + '
' : '') + + '
' + + pendingActions + + '
'; + }).join(''); + } + + setInterval(() => { + if (document.getElementById('page-receipts')?.classList.contains('active')) { + window.refreshReceiptsPage?.(); + } + }, 4000); + // Navigation function navigateTo(page) { document.querySelectorAll('.nav-item').forEach(i => i.classList.toggle('active', i.dataset.page === page)); document.querySelectorAll('.page').forEach(p => p.classList.toggle('active', p.id === `page-${page}`)); - const titles = { warroom: 'War Room', 'live-scan': 'Live Scan', operators: 'Operatives', evidence: 'Evidence Vault', arsenal: 'Arsenal', terminal: 'Terminal', benchmarks: 'Benchmarks', configs: 'Config Library', 'ctf-range': 'CTF Range', general: 'Op Admiral', selfimprove: 'Self-Improvement', settings: 'Settings', about: 'About' }; + const titles = { warroom: 'War Room', 'live-scan': 'Live Scan', receipts: 'Scope Receipts', operators: 'Operatives', evidence: 'Evidence Vault', arsenal: 'Arsenal', terminal: 'Terminal', benchmarks: 'Benchmarks', configs: 'Config Library', 'ctf-range': 'CTF Range', general: 'Op Admiral', selfimprove: 'Self-Improvement', settings: 'Settings', about: 'About' }; document.getElementById('pageTitle').textContent = titles[page] || 'War Room'; document.getElementById('sidebar').classList.remove('open'); if (page === 'live-scan') setTimeout(() => window.refreshLiveScanPage?.(), 50); + if (page === 'receipts') setTimeout(() => window.refreshReceiptsPage?.(), 50); if (page === 'operators' && typeof window.loadOperativesRoster === 'function') setTimeout(window.loadOperativesRoster, 80); if (page === 'evidence' && typeof window.hydrateFindings === 'function') setTimeout(window.hydrateFindings, 60); if (page === 'selfimprove' && typeof window.renderSelfImprove === 'function') setTimeout(window.renderSelfImprove, 60); @@ -24647,6 +24784,59 @@ Be specific and actionable. Format as structured JSON.`; if (data.audit.length) { feed.dataset.live = '1'; feed.innerHTML = ''; data.audit.slice(-40).forEach(rec => pushApprovalAuditEvent(rec, true)); } } } + async function fetchScopeReceipts() { + try { + if (!T3MP3ST_API.baseUrl) return; + const r = await fetch(`${T3MP3ST_API.baseUrl}/api/approvals`); + if (!r.ok) return; + const data = await r.json(); + renderScopeReceipts(data.approvals || []); + ReceiptsState.approvals = Array.isArray(data.approvals) ? data.approvals : []; + renderReceiptsPage(); + } catch (e) { /* offline β€” panel stays in its last known state */ } + } + function renderScopeReceipts(approvals) { + const feed = document.getElementById('scopeReceiptFeed'); + const count = document.getElementById('scopeReceiptCount'); + if (!feed) return; + const pending = (approvals || []).filter(a => a && a.status === 'pending'); + const recent = (approvals || []).slice().sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || ''))).slice(0, 12); + if (count) count.textContent = `${pending.length} pending`; + if (!recent.length) { + feed.innerHTML = 'No pending scope receipts.'; + return; + } + feed.innerHTML = recent.map(a => { + const color = receiptStatusColor(a.status); + const pendingActions = a.status === 'pending' + ? `
` + : ''; + return `
+
${escapeHtml(a.status || 'unknown')}${escapeHtml(a.id || '')}
+
${escapeHtml(a.action || '')} Β· ${escapeHtml(a.target || '')}
+
${escapeHtml(a.reason || '')}
+ ${pendingActions} +
`; + }).join(''); + } + window.approveScopeReceipt = async function approveScopeReceipt(id) { + try { + await T3MP3ST_API.post(`/api/approvals/${id}/approve`, { approvedBy: 'local-operator' }); + try { addIntel('SCOPEGUARD', `Approved receipt ${id}`, 'success'); } catch (e) {} + await fetchScopeReceipts(); + } catch (e) { + try { toast('Receipt approval failed', 'error'); } catch (err) {} + } + }; + window.rejectScopeReceipt = async function rejectScopeReceipt(id) { + try { + await T3MP3ST_API.post(`/api/approvals/${id}/reject`, {}); + try { addIntel('SCOPEGUARD', `Rejected receipt ${id}`, 'warning'); } catch (e) {} + await fetchScopeReceipts(); + } catch (e) { + try { toast('Receipt rejection failed', 'error'); } catch (err) {} + } + }; function pushApprovalAuditEvent(rec, silent) { const feed = document.getElementById('approvalAuditFeed'); if (!feed || !rec) return; @@ -24690,6 +24880,7 @@ Be specific and actionable. Format as structured JSON.`; try { addMissionLog('info', `Approval receipt requested: ${approval.id}`); } catch (e) {} try { addIntel('SCOPEGUARD', `Receipt ${approval.id} is ${approval.status}`, 'info'); } catch (e) {} try { toast(`Receipt requested: ${approval.id}`, 'success'); } catch (e) {} + try { fetchScopeReceipts(); } catch (e) {} } catch (e) { setOpsReady('approval', 'block', 'request failed'); try { addMissionLog('warning', `Approval receipt failed: ${e.message || e}`); } catch (err) {} @@ -25529,6 +25720,18 @@ Be specific and actionable. Format as structured JSON.`; if (typeof updateSitRep === 'function') updateSitRep('reconnaissance', 'βš“ Op Admiral is planning the ' + t.label + ' operation on ' + tgt + '…', 'ACTIVE'); if (typeof addIntel === 'function') addIntel('ADMIRAL', 'βš“ Brief handed to Op Admiral β€” planning ' + brief.family + ' on ' + tgt + ' (~30-90s)', 'info'); if (window.toast) toast('βš“ Op Admiral is planning the operation…', 'info'); + window.__t3mpAdmiralPendingRetry = false; + window.retryPendingAdmiralLaunch = function(){ + if (!window.__t3mpAdmiralPendingRetry) return; + window.__t3mpAdmiralPendingRetry = false; + if (typeof addIntel === 'function') addIntel('SCOPEGUARD', 'Receipt approved β€” retrying Admiral launch', 'info'); + if (window.toast) toast('Receipt approved β€” retrying Admiral launch', 'info'); + setTimeout(function(){ window.admiralLaunch(); }, 50); + }; + const admiralApiBase = (typeof getApiBase === 'function') + ? getApiBase() + : ((typeof T3MP3ST_API !== 'undefined' && T3MP3ST_API.baseUrl) || ''); + const admiralFetch = function(path, opts){ return fetch(admiralApiBase + path, opts); }; const body = function(extra){ return JSON.stringify(Object.assign({ brief: brief, confirmed: true }, bb, extra || {})); }; // Op Admiral planning is a slow LLM call, and on success the SERVER brings up a LIVE // mission. The server budgets up to 300s for planning, so the client cap MUST exceed that @@ -25538,18 +25741,31 @@ Be specific and actionable. Format as structured JSON.`; // cautious rather than declaring failure. const launchOpts = function(extra){ return { method:'POST', headers:{'Content-Type':'application/json'}, body: body(extra), signal: AbortSignal.timeout(330000) }; }; try { - let res = await fetch('/api/admiral/launch', launchOpts()); + let approvalIds = []; + let res = await admiralFetch('/api/admiral/launch', launchOpts()); let d = await res.json(); - // autonomous-execution approval receipt β€” auto-grant for loopback/lab or Autonomous mode, else require it. - // The server gates this with HTTP 403 (blockForApproval); the HOLD gate below is 409. - if (res.status === 403 && d.approval && d.approval.id) { + for (let approvalRound = 0; approvalRound < 5 && res.status === 403; approvalRound++) { + const requested = []; + if (d.approval && d.approval.id) requested.push(d.approval); + if (Array.isArray(d.approvals)) d.approvals.forEach(function(a){ if (a && a.id) requested.push(a); }); + if (!requested.length) break; + const requestedIds = requested.map(function(a){ return a.id; }).filter(Boolean); + const targets = (d.outOfScopeTargets || requested.map(function(a){ return a.target; }).filter(Boolean)).join(', '); if (isLab || autonomous) { - await fetch('/api/approvals/' + d.approval.id + '/approve', { method:'POST', headers:{'Content-Type':'application/json'}, body:'{}' }); - res = await fetch('/api/admiral/launch', launchOpts({ approvalId: d.approval.id })); + await Promise.all(requestedIds.map(function(id){ + return admiralFetch('/api/approvals/' + id + '/approve', { method:'POST', headers:{'Content-Type':'application/json'}, body:'{}' }); + })); + approvalIds = approvalIds.concat(requestedIds).filter(function(id, idx, arr){ return id && arr.indexOf(id) === idx; }); + addIntel?.('SCOPEGUARD', 'Auto-approved ' + requestedIds.length + ' receipt(s): ' + (targets || requestedIds.join(', ')), 'success'); + await window.refreshReceiptsPage?.(); + res = await admiralFetch('/api/admiral/launch', launchOpts({ approvalIds: approvalIds })); d = await res.json(); - } else { - throw new Error('Approval required for ' + tgt + ' β€” choose Autonomous mode, or approve in the receipts panel.'); + continue; } + window.__t3mpAdmiralPendingRetry = true; + addIntel?.('SCOPEGUARD', 'Approval required: ' + (targets || tgt) + ' β€” open Scope Receipts', 'warning'); + navigateTo?.('receipts'); + throw new Error((d.error || 'Approval required') + ' β€” approve ' + (targets || 'pending targets') + ' in Scope Receipts; launch will retry after approval.'); } if (res.status === 409 && d.review && d.review.status === 'hold') throw new Error('Op Admiral plan gate is HOLD β€” ' + ((d.review && d.review.reason) || 'manual review required before execution')); if (!res.ok || d.error) throw new Error(d.error || ('launch failed (' + res.status + ')')); diff --git a/src/__tests__/local-api-hardening-static.test.ts b/src/__tests__/local-api-hardening-static.test.ts index 0b3fb85..a5e5261 100644 --- a/src/__tests__/local-api-hardening-static.test.ts +++ b/src/__tests__/local-api-hardening-static.test.ts @@ -88,12 +88,40 @@ describe('local API authorization hardening invariants', () => { expect(parser).toMatch(/changes the effective network destination/); }); - it('Admiral live launch re-checks every General-produced execution target before mission bring-up', () => { + it('Admiral live launch permits expanded targets only with explicit operator approval receipts', () => { const route = routeBlock("app.post('/api/admiral/launch'", '// =============================================================================\n// BOUNTY PLATFORM INTEGRATIONS'); - expect(route).toMatch(/ensureExecTargetsWithinApprovedTarget\(execConfig\.targets, brief\.target\)/); + expect(route).toMatch(/ensureExecTargetsAuthorized\(execConfig\.targets,\s*brief\.target,\s*req\.body/); expect(route).toMatch(/outOfScopeTargets\.length/); - expect(route.indexOf('ensureExecTargetsWithinApprovedTarget(execConfig.targets, brief.target)')) + expect(route.indexOf('ensureExecTargetsAuthorized(execConfig.targets, brief.target')) .toBeLessThan(route.indexOf('bringUpMissionFromPlan(execConfig, generalConfig)')); + expect(route).toMatch(/approvals/); + expect(route).toMatch(/approvalIds/); + }); + + it('approval lookup requires explicit receipt ids and wildcard hosts require opt-in', () => { + const findApproval = routeBlock('function findApproval(', 'function createApprovalRequest'); + const approvalMatches = sourceBlock('function approvalMatches(', 'function ensureExecTargetsWithinApprovedTarget'); + + expect(findApproval).toMatch(/body\.approvalId/); + expect(findApproval).toMatch(/body\.approvalIds/); + expect(findApproval).not.toMatch(/\[\.\.\.approvalRequests\.values\(\)\]/); + expect(serverSource).toMatch(/Wildcard host approval requires explicit opt-in/); + expect(serverSource).toMatch(/body\.allowWildcard !== true/); + expect(approvalMatches.indexOf("approval.target === '*'")) + .toBeLessThan(approvalMatches.indexOf('targetUsesWildcard(approval.target) && !approval.wildcardOptIn')); + }); + + it('authorize-target only approves existing pending receipts and cannot mint broad active-action approvals', () => { + const route = routeBlock("app.post('/api/approvals/authorize-target'", "app.post('/api/approvals/:id/reject'"); + + expect(route).toMatch(/approvalId/); + expect(route).toMatch(/approvalIds/); + expect(route).toMatch(/approvalRequests\.get\(id\)/); + expect(route).toMatch(/approval\.status !== 'pending'/); + expect(route).toMatch(/Math\.min\(30/); + expect(route).not.toMatch(/createApprovalRequest/); + expect(route).not.toMatch(/allowedActions/); + expect(route).not.toMatch(/command_execution['"],\s*['"]autonomous_execution/); }); }); diff --git a/src/server.ts b/src/server.ts index 08ccad2..25952f4 100755 --- a/src/server.ts +++ b/src/server.ts @@ -607,6 +607,7 @@ interface ApprovalRequest { target: string; reason: string; status: ApprovalStatus; + wildcardOptIn?: boolean; operationId?: string; requestedBy: DraftSource | 'system'; createdAt: string; @@ -1191,10 +1192,29 @@ function approvalIsFresh(approval: ApprovalRequest): boolean { return Date.parse(approval.expiresAt) > Date.now(); } +function targetUsesWildcard(target: string): boolean { + const raw = normalizeTargetValue(target).toLowerCase(); + if (raw === '*') return true; + const withoutScheme = raw.replace(/^[a-z][a-z0-9+.-]*:\/\//, ''); + return withoutScheme.startsWith('*.') || hostFromTarget(raw).startsWith('*.'); +} + +function wildcardHostFromTarget(target: string): string { + const raw = normalizeTargetValue(target).toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//, ''); + return raw.replace(/\/.*$/, '').replace(/:\d+$/, ''); +} + function approvalMatches(approval: ApprovalRequest, action: GuardAction, target: string): boolean { if (approval.action !== action) return false; if (approval.target === '*') return action === 'model_call' || action === 'autonomous_execution'; - return hostFromTarget(approval.target) === hostFromTarget(target); + if (targetUsesWildcard(approval.target) && !approval.wildcardOptIn) return false; + const approvalHost = targetUsesWildcard(approval.target) ? wildcardHostFromTarget(approval.target) : hostFromTarget(approval.target); + const targetHost = hostFromTarget(target); + if (approvalHost.startsWith('*.')) { + const suffix = approvalHost.slice(1); + return targetHost.endsWith(suffix) && targetHost !== approvalHost.slice(2); + } + return approvalHost === targetHost; } function ensureExecTargetsWithinApprovedTarget(targets: string[], approvedTarget: string): string[] { @@ -1204,6 +1224,15 @@ function ensureExecTargetsWithinApprovedTarget(targets: string[], approvedTarget .filter(target => hostFromTarget(target) !== approvedHost); } +function ensureExecTargetsAuthorized( + targets: string[], + approvedTarget: string, + body: Record, +): string[] { + return ensureExecTargetsWithinApprovedTarget(targets, approvedTarget) + .filter(target => !findApproval(body, 'autonomous_execution', target)); +} + function approvalMatchesGateScope(approval: ApprovalRequest, action: GuardAction, operationId: string, target: string): boolean { if (!approvalMatches(approval, action, target)) return false; if (approval.operationId && operationId && approval.operationId !== operationId) return false; @@ -1211,10 +1240,17 @@ function approvalMatchesGateScope(approval: ApprovalRequest, action: GuardAction } function findApproval(body: Record, action: GuardAction, target: string): ApprovalRequest | null { - const id = typeof body.approvalId === 'string' ? body.approvalId : ''; - const approval = id ? approvalRequests.get(id) : undefined; - if (!approval || !approvalIsFresh(approval) || !approvalMatches(approval, action, target)) return null; - return approval; + const ids = [ + typeof body.approvalId === 'string' ? body.approvalId : '', + ...(Array.isArray(body.approvalIds) ? body.approvalIds.filter((id): id is string => typeof id === 'string') : []), + ].filter(Boolean); + + for (const id of ids) { + const approval = approvalRequests.get(id); + if (approval && approvalIsFresh(approval) && approvalMatches(approval, action, target)) return approval; + } + + return null; } function createApprovalRequest(action: GuardAction, target: string, reason: string, body: Record): ApprovalRequest { @@ -1225,6 +1261,7 @@ function createApprovalRequest(action: GuardAction, target: string, reason: stri target, reason, status: 'pending', + wildcardOptIn: body.allowWildcard === true && targetUsesWildcard(target), operationId: typeof operationDraft?.operation_id === 'string' ? operationDraft.operation_id : undefined, requestedBy: ['human', 'agent', 't3mp3st'].includes(String(body.source)) ? body.source as DraftSource : 'system', createdAt: nowIso(), @@ -4905,6 +4942,15 @@ app.post('/api/approvals/request', (req: Request, res: Response) => { }); return; } + if (targetUsesWildcard(target) && target !== '*' && body.allowWildcard !== true) { + res.status(400).json({ + error: 'Wildcard host approval requires explicit opt-in', + action, + target, + next: 'Send allowWildcard:true only when the operator intentionally approves the whole subdomain wildcard.', + }); + return; + } const reason = typeof body.reason === 'string' && body.reason.trim() ? body.reason.trim() : `Approval requested for ${action} against ${target}`; @@ -4928,6 +4974,68 @@ app.post('/api/approvals/:id/approve', (req: Request, res: Response) => { res.json(approval); }); +app.post('/api/approvals/authorize-target', (req: Request, res: Response) => { + const body = req.body as Record; + const target = normalizeTargetValue(body.target); + const approvalIds = [ + typeof body.approvalId === 'string' ? body.approvalId : '', + ...(Array.isArray(body.approvalIds) ? body.approvalIds.filter((id): id is string => typeof id === 'string') : []), + ].filter(Boolean); + if (!approvalIds.length) { + res.status(400).json({ + error: 'approvalId or approvalIds required', + next: 'Request a pending receipt first, then approve that exact receipt id.', + }); + return; + } + if (target === '*') { + res.status(400).json({ + error: 'Wildcard target authorization is not allowed for active actions', + next: 'Authorize one concrete host or URL so receipts remain target-scoped.', + }); + return; + } + if (targetUsesWildcard(target) && target !== '*' && body.allowWildcard !== true) { + res.status(400).json({ + error: 'Wildcard host authorization requires explicit opt-in', + next: 'Send allowWildcard:true only when the operator intentionally approves the whole subdomain wildcard.', + }); + return; + } + + const ttlMinutes = Math.max(1, Math.min(30, Number(body.ttlMinutes || 30))); + const expiresAt = new Date(Date.now() + ttlMinutes * 60_000).toISOString(); + const approvals: ApprovalRequest[] = []; + for (const id of [...new Set(approvalIds)]) { + const approval = approvalRequests.get(id); + if (!approval) { + res.status(404).json({ error: 'Approval request not found', approvalId: id }); + return; + } + if (approval.status !== 'pending') { + res.status(409).json({ error: 'Approval request is not pending', approvalId: id, status: approval.status }); + return; + } + if (target && !approvalMatches(approval, approval.action, target)) { + res.status(400).json({ + error: 'Approval target mismatch', + approvalId: id, + approvalTarget: approval.target, + target, + }); + return; + } + approval.status = 'approved'; + approval.approvedBy = typeof body.approvedBy === 'string' ? body.approvedBy : 'local-operator'; + approval.expiresAt = expiresAt; + approval.updatedAt = nowIso(); + emitContractEvent('approval.approved', { approvalId: approval.id, action: approval.action, target: approval.target }); + approvals.push(approval); + } + + res.json({ target: target || null, expiresAt, approvals }); +}); + app.post('/api/approvals/:id/reject', (req: Request, res: Response) => { const approval = approvalRequests.get(req.params.id); if (!approval) { @@ -6106,6 +6214,14 @@ app.post('/api/mission/start', async (req: Request, res: Response): Promise); if (outOfScopeTargets.length) { + const approvals = outOfScopeTargets.map(target => createApprovalRequest( + 'autonomous_execution', + target, + `Admiral plan expanded execution scope from ${brief.target} to ${target}`, + req.body as Record + )); res.status(403).json({ - error: 'Admiral LIVE plan contains targets outside the approved brief target', + error: 'Admiral LIVE plan needs approval for expanded target scope', approvedTarget: brief.target, outOfScopeTargets, + approvals, + next: 'Approve the expanded target receipts, then retry /api/admiral/launch with approvalIds.', }); return; }