feat: OpenClaw external agent sync API at /api/openclaw/*

- API key auth via x-openclaw-key header (OPENCLAW_API_KEY env var)
- GET  /api/openclaw/sync/status
- POST /api/openclaw/sync/autotask/incremental
- POST /api/openclaw/sync/autotask/full
- POST /api/openclaw/sync/autotask/entity   { entities: [...] }
- POST /api/openclaw/sync/datto-rmm          { syncType: full|incremental }
- POST /api/openclaw/sync/sentinelone
- POST /api/openclaw/sync/veeam              { syncType: full|incremental }
- POST /api/openclaw/sync/zoom
- POST /api/openclaw/sync/engagement
- POST /api/openclaw/sync/qbo                { syncType: full|incremental }
- POST /api/openclaw/sync/zabbix
- POST /api/openclaw/sync/itglue
All routes bypass Better Auth middleware, delegate to existing sync services
This commit is contained in:
lorentz 2026-03-17 23:26:44 -04:00
parent eea66de129
commit 5be7b22953
14 changed files with 450 additions and 0 deletions

View file

@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { AutotaskClient } from '@/lib/services/autotask-client';
import { createSyncService } from '@/lib/services/sync-service';
import { EntityType, SyncType } from '@/lib/types/sync';
import { isValidEntityType } from '@/lib/utils/sync-helpers';
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
try {
const body = await request.json();
const { entities, yearsBack } = body;
if (!entities || !Array.isArray(entities) || entities.length === 0) {
return NextResponse.json({ error: 'entities array is required' }, { status: 400 });
}
const validEntities: EntityType[] = [];
for (const entity of entities) {
if (isValidEntityType(entity)) {
validEntities.push(entity as EntityType);
} else {
return NextResponse.json({ error: `Invalid entity type: ${entity}` }, { status: 400 });
}
}
const autotaskClient = new AutotaskClient({
apiUrl: process.env.AUTOTASK_API_URL || '',
username: process.env.AUTOTASK_USERNAME || '',
password: process.env.AUTOTASK_SECRET || '',
apiIntegrationCode: process.env.AUTOTASK_API_INTEGRATION_CODE || '',
});
const syncService = createSyncService(autotaskClient);
if (syncService.isSyncInProgress()) {
return NextResponse.json({ error: 'A sync operation is already in progress' }, { status: 409 });
}
syncService.syncEntities(validEntities, 'entity-specific' as SyncType, 'openclaw', yearsBack).catch((err) => {
console.error('[OpenClaw] Autotask entity sync failed:', err);
});
return NextResponse.json({
message: `Autotask entity sync started for: ${validEntities.join(', ')}`,
syncId: syncService.getCurrentSyncId(),
entities: validEntities,
triggeredBy: 'openclaw',
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,40 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { AutotaskClient } from '@/lib/services/autotask-client';
import { createSyncService } from '@/lib/services/sync-service';
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
try {
const body = await request.json().catch(() => ({}));
const yearsBack = body.yearsBack;
const autotaskClient = new AutotaskClient({
apiUrl: process.env.AUTOTASK_API_URL || '',
username: process.env.AUTOTASK_USERNAME || '',
password: process.env.AUTOTASK_SECRET || '',
apiIntegrationCode: process.env.AUTOTASK_API_INTEGRATION_CODE || '',
});
const syncService = createSyncService(autotaskClient);
if (syncService.isSyncInProgress()) {
return NextResponse.json({ error: 'A sync operation is already in progress' }, { status: 409 });
}
syncService.fullSync('openclaw', yearsBack).catch((err) => {
console.error('[OpenClaw] Autotask full sync failed:', err);
});
return NextResponse.json({
message: 'Autotask full sync started',
syncId: syncService.getCurrentSyncId(),
triggeredBy: 'openclaw',
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,37 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { AutotaskClient } from '@/lib/services/autotask-client';
import { createSyncService } from '@/lib/services/sync-service';
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
try {
const autotaskClient = new AutotaskClient({
apiUrl: process.env.AUTOTASK_API_URL || '',
username: process.env.AUTOTASK_USERNAME || '',
password: process.env.AUTOTASK_SECRET || '',
apiIntegrationCode: process.env.AUTOTASK_API_INTEGRATION_CODE || '',
});
const syncService = createSyncService(autotaskClient);
if (syncService.isSyncInProgress()) {
return NextResponse.json({ error: 'A sync operation is already in progress' }, { status: 409 });
}
syncService.incrementalSync('openclaw').catch((err) => {
console.error('[OpenClaw] Autotask incremental sync failed:', err);
});
return NextResponse.json({
message: 'Autotask incremental sync started',
syncId: syncService.getCurrentSyncId(),
triggeredBy: 'openclaw',
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { DattoRMMSyncService } from '@/lib/services/datto-rmm-sync-service';
let syncServiceInstance: DattoRMMSyncService | null = null;
function getSyncService(): DattoRMMSyncService {
if (!syncServiceInstance) syncServiceInstance = new DattoRMMSyncService();
return syncServiceInstance;
}
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
try {
const syncService = getSyncService();
if (syncService.isSyncInProgress()) {
return NextResponse.json({ error: 'A Datto RMM sync is already in progress' }, { status: 409 });
}
const body = await request.json().catch(() => ({}));
const syncType = body.syncType === 'full' ? 'full' : 'incremental';
(syncType === 'full'
? syncService.fullSync('openclaw')
: syncService.incrementalSync('openclaw')
).catch((err) => console.error('[OpenClaw] Datto RMM sync failed:', err));
return NextResponse.json({
message: `Datto RMM ${syncType} sync started`,
syncType,
triggeredBy: 'openclaw',
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { getEngagementSyncService } from '@/lib/services/engagement-sync-service';
import { isMsgraphConfigured } from '@/lib/services/msgraph-factory';
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
if (!isMsgraphConfigured()) {
return NextResponse.json(
{ error: 'Microsoft Graph not configured. Set MSGRAPH_CLIENT_ID, MSGRAPH_CLIENT_SECRET, MSGRAPH_TENANT_ID.' },
{ status: 503 }
);
}
try {
const service = getEngagementSyncService();
if (service.isSyncInProgress()) {
return NextResponse.json({ error: 'Engagement sync already in progress' }, { status: 409 });
}
service.sync().catch((err) => console.error('[OpenClaw] Engagement sync failed:', err));
return NextResponse.json({
message: 'Engagement sync started',
triggeredBy: 'openclaw',
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,26 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { getITGlueSyncService } from '@/lib/services/itglue-sync-service';
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
try {
const svc = getITGlueSyncService();
if (svc.isSyncInProgress()) {
return NextResponse.json({ error: 'IT Glue sync already in progress' }, { status: 409 });
}
svc.fullSync('openclaw').catch((err) => console.error('[OpenClaw] IT Glue sync failed:', err));
return NextResponse.json({
message: 'IT Glue sync started',
triggeredBy: 'openclaw',
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,35 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { QboSyncService } from '@/lib/services/qbo-sync-service';
import { QboClient } from '@/lib/services/qbo-client';
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
try {
const body = await request.json().catch(() => ({}));
const syncType: 'full' | 'incremental' = body.syncType === 'incremental' ? 'incremental' : 'full';
const client = new QboClient();
const service = new QboSyncService(client);
if (service.isSyncInProgress()) {
return NextResponse.json({ error: 'QBO sync already in progress' }, { status: 409 });
}
(syncType === 'full'
? service.fullSync('openclaw')
: service.incrementalSync('openclaw')
).catch((err) => console.error('[OpenClaw] QBO sync failed:', err));
return NextResponse.json({
message: `QBO ${syncType} sync started`,
syncType,
triggeredBy: 'openclaw',
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,26 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { getSentinelOneSyncService } from '@/lib/services/sentinelone-sync-service';
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
try {
const svc = getSentinelOneSyncService();
if (svc.isSyncInProgress()) {
return NextResponse.json({ error: 'SentinelOne sync already in progress' }, { status: 409 });
}
svc.fullSync('openclaw').catch((err) => console.error('[OpenClaw] SentinelOne sync failed:', err));
return NextResponse.json({
message: 'SentinelOne sync started',
triggeredBy: 'openclaw',
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { AutotaskClient } from '@/lib/services/autotask-client';
import { createSyncService } from '@/lib/services/sync-service';
export async function GET(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
try {
const autotaskClient = new AutotaskClient({
apiUrl: process.env.AUTOTASK_API_URL || '',
username: process.env.AUTOTASK_USERNAME || '',
password: process.env.AUTOTASK_SECRET || '',
apiIntegrationCode: process.env.AUTOTASK_API_INTEGRATION_CODE || '',
});
const syncService = createSyncService(autotaskClient);
return NextResponse.json({
inProgress: syncService.isSyncInProgress(),
syncId: syncService.getCurrentSyncId(),
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { VeeamSyncService } from '@/lib/services/veeam-sync-service';
let syncServiceInstance: VeeamSyncService | null = null;
function getSyncService(): VeeamSyncService {
if (!syncServiceInstance) syncServiceInstance = new VeeamSyncService();
return syncServiceInstance;
}
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
try {
const syncService = getSyncService();
if (syncService.isSyncInProgress()) {
return NextResponse.json({ error: 'A Veeam sync is already in progress' }, { status: 409 });
}
const body = await request.json().catch(() => ({}));
const syncType = body.syncType === 'full' ? 'full' : 'incremental';
(syncType === 'full'
? syncService.fullSync('openclaw')
: syncService.incrementalSync('openclaw')
).catch((err) => console.error('[OpenClaw] Veeam sync failed:', err));
return NextResponse.json({
message: `Veeam ${syncType} sync started`,
syncType,
triggeredBy: 'openclaw',
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,35 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
if (!process.env.ZABBIX_API_URL || !process.env.ZABBIX_API_TOKEN) {
return NextResponse.json({ error: 'Zabbix not configured' }, { status: 503 });
}
try {
const baseUrl = process.env.NEXT_PUBLIC_BETTER_AUTH_URL || 'http://localhost:3100';
const [hostsRes, eventsRes] = await Promise.all([
fetch(`${baseUrl}/api/zabbix/sync-hosts`, { method: 'POST' }),
fetch(`${baseUrl}/api/zabbix/sync-events`, { method: 'POST' }),
]);
const [hosts, events] = await Promise.all([
hostsRes.json().catch(() => ({})),
eventsRes.json().catch(() => ({})),
]);
return NextResponse.json({
message: 'Zabbix sync completed',
triggeredBy: 'openclaw',
hosts,
events,
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,31 @@
import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { getZoomSyncService } from '@/lib/services/zoom-sync-service';
import { isZoomConfigured } from '@/lib/services/zoom-factory';
export async function POST(request: NextRequest) {
const authError = validateOpenClawKey(request);
if (authError) return authError;
if (!isZoomConfigured()) {
return NextResponse.json({ error: 'Zoom credentials not configured' }, { status: 503 });
}
try {
const service = getZoomSyncService();
if (service.isSyncInProgress()) {
return NextResponse.json({ error: 'Zoom sync already in progress' }, { status: 409 });
}
service.sync().catch((err) => console.error('[OpenClaw] Zoom sync failed:', err));
return NextResponse.json({
message: 'Zoom sync started',
triggeredBy: 'openclaw',
});
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
return NextResponse.json({ error: msg }, { status: 500 });
}
}

View file

@ -0,0 +1,22 @@
import { NextRequest, NextResponse } from 'next/server';
/**
* Validate the OpenClaw API key from the request header.
* Returns a 401 NextResponse if invalid, or null if valid.
*/
export function validateOpenClawKey(request: NextRequest): NextResponse | null {
const expectedKey = process.env.OPENCLAW_API_KEY;
if (!expectedKey) {
console.error('[OpenClaw] OPENCLAW_API_KEY is not set');
return NextResponse.json({ error: 'OpenClaw API not configured' }, { status: 500 });
}
const providedKey = request.headers.get('x-openclaw-key');
if (!providedKey || providedKey !== expectedKey) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return null;
}

View file

@ -20,6 +20,8 @@ const publicRoutes = [
"/api/integrations/status",
// Legal pages required by Intuit
"/legal",
// OpenClaw external agent API (auth via x-openclaw-key header)
"/api/openclaw",
// Sync endpoints called by scheduler
"/api/sync",
"/api/datto-rmm/sync",