wulf-pulse/app/api/analyzer/itglue/applications/[id]/audit/route.ts
lorentz 1112a06afe feat: RMM Overshell, IT Glue audit/write-back, LogLift, link-aware bundles, dashboard overhaul
- RMM Overshell (migration 077): admin page, dispatch UI, executor/worker, target
  resolver, script registry (AD/DHCP/DNS/event-log/services/software/network/loglift)
- LogLift evidence pipeline (migration 078): upload webhook, B2 storage client,
  receiver/matcher, EventLogCollector PowerShell script
- IT Glue audit + write-back (migrations 075, 076): asset-audit runner, ticket
  xrefs, applications/configurations browse pages + apply/revert/audit endpoints
- Link-aware analyzer bundles (migration 073) + provider toggle (migration 074):
  link-discovery service, OpenRouter LLM provider, related-tickets/itglue-suggestion
  panels, analyze-bundle endpoint
- Endpoint data model + device-link reconciliation (migrations 079, 080): conflicts
  admin page, reconciler service, resolve endpoints
- Dashboard overhaul: integration-health service + alerts, overview/health endpoints
- Permissions: add itglue + rmm scopes; middleware: public /api/rmm/loglift route

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 07:13:18 -04:00

113 lines
3.2 KiB
TypeScript

/**
* GET /api/analyzer/itglue/applications/:id/audit
* Returns the latest audit row for the asset (or null).
*
* POST /api/analyzer/itglue/applications/:id/audit
* Body: { provider?: 'anthropic' | 'openrouter' }
* Runs a fresh audit. Cost-guarded the same way single-ticket runs are.
* Returns the new audit row.
*/
import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import { RunAssetAuditRequest } from '@/lib/types/analyzer';
import { runAssetAudit } from '@/lib/services/analyzer/asset-audit/runner';
import {
getAssetAuditById,
getLatestAssetAudit,
listAssetAudits,
} from '@/lib/services/analyzer/asset-audit/persistence';
import {
evaluateCost,
recordCostAuditDecision,
} from '@/lib/services/analyzer/cost-guard';
const PER_AUDIT_COST_USD: Record<'anthropic' | 'openrouter', number> = {
anthropic: 0.1,
openrouter: 0.01,
};
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { error } = await requireAuth();
if (error) return error;
const { id } = await params;
const url = new URL(request.url);
const includeHistory = url.searchParams.get('history') === '1';
const latest = await getLatestAssetAudit(id);
if (!includeHistory) {
return NextResponse.json({ audit: latest });
}
const history = await listAssetAudits(id, 'flexible_asset', 20);
return NextResponse.json({ audit: latest, history });
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { session, error } = await requireAuth();
if (error) return error;
const { id } = await params;
const body = await request.json().catch(() => ({}));
const parsed = RunAssetAuditRequest.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: 'Invalid request body', details: parsed.error.issues },
{ status: 400 }
);
}
const provider = parsed.data.provider;
const userId = (session?.user as { id: string } | undefined)?.id ?? null;
const evaluation = await evaluateCost({
userId,
estimatedCost: PER_AUDIT_COST_USD[provider],
confirmedCost: false,
});
await recordCostAuditDecision({
userId,
action: 'itglue_audit',
evaluation,
context: { assetId: id, provider },
});
if (evaluation.decision === 'blocked') {
return NextResponse.json(
{
error: 'Daily cost limit reached',
message: evaluation.decisionReason,
estimatedCost: evaluation.estimatedCost,
dailySpendBefore: evaluation.dailySpendBefore,
},
{ status: 403 }
);
}
// Audits are cheap enough that requires_confirmation should never trip
// the per-request threshold — but let it fall through anyway.
const result = await runAssetAudit({
assetType: 'flexible_asset',
assetId: id,
generatedByUserId: userId,
provider,
});
if (result.status === 'failed') {
return NextResponse.json(
{
error: 'Audit failed',
message: result.errorMessage,
auditId: result.auditId,
},
{ status: 500 }
);
}
const audit = await getAssetAuditById(result.auditId);
return NextResponse.json({ audit });
}