API ReferenceCompliance & Scanning

Compliance & Scanning API

v1.0StableLast updated: March 2026

Manage GDPR consent, data subject requests, HIPAA business associate agreements, compliance scanning rules, flagged traces, and audit logs. These endpoints support regulatory requirements across GDPR, HIPAA, and SOC 2.

Authentication

All compliance endpoints require authentication via session (dashboard) or API key (Authorization: Bearer header).

Authorization: Bearer thk_your_api_key

See Authentication for details on obtaining and managing API keys.

Some endpoints (BAA management, full compliance check details) require admin role. Non-admin users receive summary views.


Manage user consent for data processing purposes as required by GDPR Article 7.

List Consents

GET /api/v1/compliance/consents

Returns all consent records for the authenticated user.

Response:

{
  "consents": [
    {
      "id": "consent_abc123",
      "purpose": "analytics",
      "granted": true,
      "lawfulBasis": "consent",
      "grantedAt": "2026-01-15T10:00:00Z",
      "withdrawnAt": null
    }
  ]
}
POST /api/v1/compliance/consents/:purpose/grant

Grant consent for a specific processing purpose.

Path Parameters:

ParameterTypeDescription
purposestringOne of: essential, analytics, marketing, personalization, third_party

Response:

{
  "success": true,
  "purpose": "analytics",
  "granted": true
}
POST /api/v1/compliance/consents/:purpose/withdraw

Withdraw previously granted consent. Cannot withdraw essential consent.

Response:

{
  "success": true,
  "purpose": "analytics",
  "withdrawn": true
}
StatusDescription
400Invalid purpose or attempting to withdraw essential consent
404No active consent found for this purpose

Data Subject Requests (GDPR)

Submit and track data subject requests as defined by GDPR Articles 15-22. All DSRs are automatically assigned a 30-day deadline per GDPR requirements.

List DSRs

GET /api/v1/compliance/dsr

Returns all data subject requests submitted by the authenticated user.

Response:

{
  "requests": [
    {
      "id": "dsr_abc123",
      "type": "access",
      "status": "pending",
      "createdAt": "2026-02-01T12:00:00Z",
      "dueDate": "2026-03-03T12:00:00Z",
      "completedAt": null,
      "downloadUrl": null
    }
  ]
}

Create DSR

POST /api/v1/compliance/dsr

Submit a new data subject request.

Request Body:

FieldTypeRequiredDescription
requestTypestringYesOne of: access, rectification, erasure, portability, restriction, objection
requestDetailsstringNoAdditional details about the request

Response (201):

{
  "id": "dsr_def456",
  "type": "erasure",
  "status": "pending",
  "dueDate": "2026-04-09T00:00:00Z"
}

Get DSR Status

GET /api/v1/compliance/dsr/:id

Get the current status of a specific DSR. Only the requester or an admin can view the details.

Response:

{
  "id": "dsr_def456",
  "type": "erasure",
  "status": "in_progress",
  "createdAt": "2026-03-10T12:00:00Z",
  "dueDate": "2026-04-09T12:00:00Z",
  "completedAt": null,
  "completionNotes": null
}

Data Export (GDPR Article 20)

Export user data in machine-readable formats for data portability compliance.

Request Data Export

POST /api/v1/compliance/export/my-data

Generates a data export and returns a download link. Creates a DSR record automatically.

Request Body:

FieldTypeDefaultDescription
formatstring"json"Export format: json or csv
includeTracesbooleantrueInclude trace data in export
includeConsentsbooleantrueInclude consent records
redactPIIbooleanfalseRedact PII from exported data
traceLimitnumber-Max traces to export (1-100,000)

Response (201):

{
  "requestId": "dsr_exp789",
  "status": "completed",
  "downloadUrl": "/api/v1/compliance/export/download/dsr_exp789",
  "message": "Your data export is ready for download."
}

Download Export

GET /api/v1/compliance/export/download/:id

Download a completed data export. Returns the file as an attachment with the appropriate Content-Type (application/json or text/csv).


Data Erasure (GDPR Article 17)

Request Erasure

POST /api/v1/compliance/erasure/request

Submit a right-to-be-forgotten request. Requires identity verification before processing.

Request Body:

FieldTypeRequiredDescription
reasonstringNoReason for the erasure request

Response (201):

{
  "requestId": "erasure_abc123",
  "status": "awaiting_verification",
  "message": "Erasure request created. Identity verification required before processing."
}

Business Associate Agreements (HIPAA)

Manage BAAs for HIPAA compliance. All BAA endpoints require admin role.

List BAAs

GET /api/v1/compliance/baa

Response:

{
  "agreements": [
    {
      "id": "baa_abc123",
      "vendorName": "Cloud Provider Inc.",
      "status": "active",
      "agreementDate": "2025-06-01T00:00:00Z",
      "effectiveDate": "2025-07-01T00:00:00Z",
      "expirationDate": "2026-07-01T00:00:00Z",
      "vendorEmail": "legal@provider.com",
      "createdAt": "2025-06-01T09:00:00Z",
      "nextReviewDue": "2026-01-01T00:00:00Z"
    }
  ]
}

Create BAA

POST /api/v1/compliance/baa

Request Body:

FieldTypeRequiredDescription
vendorNamestringYesName of the business associate
vendorEmailstringNoVendor contact email
vendorContactstringNoVendor contact name
agreementDatestringYesDate agreement was signed (ISO 8601)
effectiveDatestringYesDate agreement takes effect (ISO 8601)
expirationDatestringNoExpiration date (ISO 8601). Review date auto-set to 6 months before.
descriptionstringNoNotes about the agreement

Response (201):

{
  "id": "baa_def456",
  "vendorName": "Cloud Provider Inc.",
  "status": "active",
  "agreementDate": "2025-06-01T00:00:00Z",
  "effectiveDate": "2025-07-01T00:00:00Z"
}

Update BAA

PUT /api/v1/compliance/baa/:id

Request Body:

FieldTypeDescription
statusstringBAA status (e.g., active, expired, terminated)
expirationDatestringUpdated expiration date (ISO 8601)
nextReviewDuestringNext review date (ISO 8601)
notesstringAdditional notes

Compliance Check (GDPR / HIPAA / SOC 2)

Run Full Check

GET /api/v1/compliance/check

Runs automated compliance checks across GDPR, HIPAA, and SOC 2 frameworks. Admin users receive full issue details; non-admin users receive a summary.

Response (admin):

{
  "overallStatus": "warning",
  "score": 82,
  "timestamp": "2026-03-10T15:30:00Z",
  "issues": [
    {
      "framework": "gdpr",
      "severity": "high",
      "check": "consent_coverage",
      "message": "3 users missing analytics consent records",
      "recommendation": "Review consent collection flow"
    }
  ],
  "checks": {
    "gdpr": {
      "status": "warning",
      "score": 75,
      "issueCount": 2,
      "criticalIssues": 0,
      "checks": [...]
    },
    "hipaa": {
      "status": "pass",
      "score": 95,
      "issueCount": 0,
      "criticalIssues": 0,
      "checks": [...]
    },
    "soc2": {
      "status": "pass",
      "score": 90,
      "issueCount": 1,
      "criticalIssues": 0,
      "checks": [...]
    }
  }
}

Response (non-admin): Same structure but with an empty issues array and a message field: "Contact your administrator for detailed issue information."

Get Summary

GET /api/v1/compliance/check/summary

Returns a simplified compliance summary accessible to all authenticated users.

Response:

{
  "status": "warning",
  "score": 82,
  "gdpr": { "status": "warning", "score": 75, "issueCount": 2 },
  "hipaa": { "status": "pass", "score": 95, "issueCount": 0 },
  "soc2": { "status": "pass", "score": 90, "issueCount": 1 },
  "lastChecked": "2026-03-10T15:30:00Z"
}

Risk Assessment (SOC 2)

Get Risk Assessment

GET /api/v1/compliance/risk

Returns the current risk assessment for the company, including risk level and overall score.

Get Risk History

GET /api/v1/compliance/risk/history

Query Parameters:

ParameterTypeDefaultDescription
limitnumber10Number of historical assessments to return

Response:

{
  "assessments": [
    {
      "riskLevel": "low",
      "overallScore": 88,
      "timestamp": "2026-03-10T12:00:00Z"
    }
  ]
}

SLA Monitoring (SOC 2)

Get SLA Report

GET /api/v1/compliance/sla

Query Parameters:

ParameterTypeDefaultDescription
daysnumber30Time period in days

Get System Health

GET /api/v1/compliance/sla/health

Returns component-level health status.

Response:

{
  "timestamp": "2026-03-10T15:00:00Z",
  "components": [
    { "name": "database", "status": "healthy", "latencyMs": 5 },
    { "name": "redis", "status": "healthy", "latencyMs": 2 }
  ],
  "healthy": true
}

Audit Logs

List Audit Logs

GET /api/v1/compliance/audit-logs

Paginated list of audit log entries for the company.

Query Parameters:

ParameterTypeDefaultDescription
pagenumber1Page number
limitnumber50Items per page (max 100)
actionstring-Filter by action type
outcomestring-Filter by outcome
startDatestring-Start date (ISO 8601)
endDatestring-End date (ISO 8601)

Response:

{
  "logs": [
    {
      "id": "log_abc123",
      "userId": "user_xyz",
      "action": "trace.delete",
      "resourceType": "trace",
      "resourceId": "tr_abc",
      "severity": "warning",
      "ipAddress": "192.168.1.1",
      "userAgent": "Mozilla/5.0...",
      "details": { "reason": "GDPR erasure request" },
      "timestamp": "2026-03-10T14:00:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 50,
    "total": 230,
    "totalPages": 5
  }
}

Export Audit Logs (CSV)

GET /api/v1/compliance/audit-logs/export

Downloads audit logs as a CSV file. Useful for SOC 2 audit evidence collection.

Query Parameters:

ParameterTypeDefaultDescription
daysnumber30Number of days of logs to export

Response: CSV file download with headers: Timestamp, User ID, Action, Resource Type, Resource ID, Severity, IP Address.

CSV exports include formula injection protection. Fields starting with =, +, -, or @ are prefixed with a single quote to prevent spreadsheet formula execution.


Compliance Scanning Rules

Define rules that automatically scan traces for PII and compliance violations. The scanning pipeline runs asynchronously via a background job queue.

All scanning endpoints are mounted at /api/v1/compliance/scanning.

List Scan Rules

GET /api/v1/compliance/scanning/rules

Returns all compliance scan rules for the company.

Response:

{
  "rules": [
    {
      "id": "rule_abc123",
      "name": "PII in Agent Responses",
      "description": "Detect email and SSN in agent output fields",
      "isEnabled": true,
      "piiTypes": ["email", "ssn", "credit_card"],
      "fieldsToScan": ["output", "agentResponse"],
      "minConfidence": "high",
      "autoFlag": true,
      "autoAlert": false,
      "alertSeverity": "warning",
      "createdAt": "2026-01-15T10:00:00Z"
    }
  ]
}

Create Scan Rule

POST /api/v1/compliance/scanning/rules

Request Body:

FieldTypeRequiredDescription
namestringYesRule name (1-200 characters)
descriptionstringNoHuman-readable description
isEnabledbooleanNoWhether the rule is active (default: depends on creation method)
piiTypesstring[]YesPII types to detect (e.g., email, ssn, phone, credit_card)
fieldsToScanstring[]NoTrace fields to scan (e.g., input, output, agentResponse)
minConfidencestringNoMinimum confidence threshold (e.g., low, medium, high)
autoFlagbooleanNoAutomatically flag traces with violations
autoAlertbooleanNoSend alerts on violation detection
alertSeveritystringNoAlert severity: info, warning, error, critical

Response (201):

{
  "rule": {
    "id": "rule_new123",
    "name": "PII in Agent Responses",
    "isEnabled": true,
    "piiTypes": ["email", "ssn"],
    "autoFlag": true,
    "createdAt": "2026-03-10T12:00:00Z"
  }
}

Update Scan Rule

PUT /api/v1/compliance/scanning/rules/:id

All fields from the create schema are accepted and optional.

Response:

{
  "rule": { ... }
}

Delete Scan Rule

DELETE /api/v1/compliance/scanning/rules/:id

Response:

{
  "success": true
}

Seed Default Rules

POST /api/v1/compliance/scanning/rules/seed

Creates a set of pre-configured scan rules (all disabled by default). Useful for onboarding.

Response:

{
  "rules": [
    { "id": "rule_1", "name": "Email Detection", "isEnabled": false, ... },
    { "id": "rule_2", "name": "SSN Detection", "isEnabled": false, ... }
  ]
}

Compliance Violations

Violations are created when the scanning pipeline detects PII or policy violations in traces.

List Violations

GET /api/v1/compliance/scanning/violations

Query Parameters:

ParameterTypeDefaultDescription
statusstring-Filter: open, acknowledged, resolved, false_positive
ruleIdstring-Filter by scan rule ID
agentIdstring-Filter by agent ID
piiTypestring-Filter by PII type
startDatestring-Start date (ISO 8601)
endDatestring-End date (ISO 8601)
limitnumber50Items per page (1-100)
offsetnumber0Pagination offset

Response:

{
  "violations": [
    {
      "id": "viol_abc123",
      "ruleId": "rule_abc123",
      "ruleName": "PII in Agent Responses",
      "traceId": "tr_xyz789",
      "agentId": "agent_abc",
      "piiType": "email",
      "status": "open",
      "detectedAt": "2026-03-10T14:30:00Z"
    }
  ],
  "total": 42
}

Get Violation Detail

GET /api/v1/compliance/scanning/violations/:id

Get Violations by Trace

GET /api/v1/compliance/scanning/violations/by-trace/:traceId

Returns all violations found for a specific trace.

Violation Statistics

GET /api/v1/compliance/scanning/violations/stats

Query Parameters:

ParameterTypeDescription
agentIdstringOptional agent filter

Response:

{
  "stats": {
    "total": 150,
    "byStatus": {
      "open": 42,
      "acknowledged": 30,
      "resolved": 70,
      "false_positive": 8
    },
    "byPiiType": {
      "email": 60,
      "phone": 40,
      "ssn": 30,
      "credit_card": 20
    }
  }
}

Update Violation Status

PUT /api/v1/compliance/scanning/violations/:id

Request Body:

FieldTypeRequiredDescription
statusstringYesNew status: open, acknowledged, resolved, false_positive
notesstringNoResolution or review notes

Bulk Update Violations

POST /api/v1/compliance/scanning/violations/bulk

Request Body:

FieldTypeRequiredDescription
idsstring[]YesViolation IDs to update (max 100)
statusstringYesNew status: open, acknowledged, resolved, false_positive

Response:

{
  "updated": 15
}

Backfill Scan

POST /api/v1/compliance/scanning/backfill

Enqueue compliance scans for existing traces. Requires at least one enabled scan rule.

Query Parameters:

ParameterTypeDefaultDescription
limitnumber200Max traces to scan (up to 500)

Response:

{
  "total": 200,
  "enqueued": 198
}

Scanning Health

GET /api/v1/compliance/scanning/health

Returns the health status of the compliance scanning pipeline.

Response:

{
  "active": true,
  "redis": true,
  "workerInitialized": true,
  "complianceQueue": { "waiting": 5, "active": 2, "completed": 1500, "failed": 3 }
}

Flagged Traces

Flag traces for human review when issues are detected — whether by automated compliance scanning, guardrail violations, or manual observation.

All flagged trace endpoints are mounted at /api/flagged-traces.

List Flagged Traces

GET /api/flagged-traces

Returns flagged traces with filtering, pagination, and aggregate statistics.

Query Parameters:

ParameterTypeDefaultDescription
statusstring-Filter: open, in_review, resolved
reasonstring-Filter: hallucination, poor_quality, compliance_concern, unexpected_behavior, customer_complaint, other
assignedTostring-Filter by assigned user ID
agentIdstring-Filter by agent ID
limitnumber20Items per page (1-100)
offsetnumber0Pagination offset
sortstring"newest"Sort order: newest or oldest

Response:

{
  "data": [
    {
      "id": "flag_abc123",
      "traceId": "tr_xyz789",
      "agentId": "agent_abc",
      "reason": "compliance_concern",
      "status": "open",
      "notes": "PII detected in agent response",
      "flaggedBy": "user_123",
      "assignedTo": "user_456",
      "createdAt": "2026-03-10T14:00:00Z"
    }
  ],
  "total": 25,
  "stats": {
    "open": 10,
    "in_review": 8,
    "resolved": 7
  },
  "pagination": {
    "limit": 20,
    "offset": 0,
    "hasMore": true
  }
}

Flag a Trace

POST /api/flagged-traces

Request Body:

FieldTypeRequiredDescription
traceIdstringYesID of the trace to flag
agentIdstringYesID of the agent that produced the trace
reasonstringYesFlag reason: hallucination, poor_quality, compliance_concern, unexpected_behavior, customer_complaint, other
assignedTostringNoUser ID to assign for review (must belong to your team)
notesstringNoAdditional context (max 2,000 characters)
⚠️

A trace can only have one active flag (status open or in_review). Attempting to flag an already-flagged trace returns a 409 Conflict with the existing flag ID.

Response (201):

{
  "id": "flag_new123",
  "traceId": "tr_xyz789",
  "agentId": "agent_abc",
  "reason": "compliance_concern",
  "status": "open",
  "flaggedBy": "user_123",
  "assignedTo": "user_456",
  "createdAt": "2026-03-10T15:00:00Z"
}

Get Flag Detail

GET /api/flagged-traces/:flagId

Returns the full flag record including review history.

Check if Trace is Flagged

GET /api/flagged-traces/by-trace/:traceId

Returns the active flag for a trace, or 404 if the trace is not flagged.

Update Flag

PATCH /api/flagged-traces/:flagId

Update the status or assignment of a flagged trace.

Request Body:

FieldTypeDescription
statusstringNew status: open, in_review, resolved
assignedTostring | nullReassign or unassign a reviewer
resolutionNotesstringResolution details (max 5,000 characters)

Delete Flag

DELETE /api/flagged-traces/:flagId

Remove a flag. Only the user who created the flag can delete it.

StatusDescription
200Flag deleted successfully
403You are not authorized to delete this flag
404Flag not found

Add Comment

POST /api/flagged-traces/:flagId/comments

Add a comment to a flagged trace for collaborative review.

Request Body:

FieldTypeRequiredDescription
contentstringYesComment text (1-5,000 characters)

Response (201):

{
  "id": "comment_abc123",
  "flagId": "flag_abc123",
  "userId": "user_123",
  "content": "Confirmed PII leak in the response. Needs guardrail update.",
  "createdAt": "2026-03-10T15:30:00Z"
}

GDPR Compliance Features

ThinkHive provides comprehensive GDPR support through the endpoints above:

GDPR ArticleFeatureEndpoint
Article 7Consent managementGET/POST /compliance/consents
Article 15Right of accessPOST /compliance/dsr (type: access)
Article 16Right to rectificationPOST /compliance/dsr (type: rectification)
Article 17Right to erasurePOST /compliance/erasure/request
Article 18Right to restrictionPOST /compliance/dsr (type: restriction)
Article 20Data portabilityPOST /compliance/export/my-data
Article 21Right to objectPOST /compliance/dsr (type: objection)

All DSRs are automatically assigned a 30-day completion deadline per GDPR requirements. ThinkHive tracks status and due dates to help you stay compliant.


HIPAA Considerations

For organizations handling protected health information (PHI):

  • BAA Management — Track business associate agreements through the /compliance/baa endpoints with automatic review date scheduling (6 months before expiration).
  • PII Redaction — Use the Guardrails API PII scanner with HIPAA-specific entity types (medical_record_number, health_plan_id, npi) to redact PHI before storage.
  • Audit Logging — Every data access, modification, and deletion is recorded in the audit log, exportable as CSV for compliance evidence.
  • Compliance Scanning — Configure scan rules targeting PHI-specific PII types to automatically detect violations in trace data.
⚠️

ThinkHive can sign a BAA for enterprise customers. Contact sales@thinkhive.ai to execute a BAA before processing any PHI.


SOC 2 Audit Support

ThinkHive includes built-in SOC 2 readiness through:

  • Automated Compliance Checks — The /compliance/check endpoint validates controls across all three frameworks and produces a scored report.
  • Risk Assessment — The /compliance/risk endpoint provides current risk posture with historical trending via /compliance/risk/history.
  • SLA Monitoring — The /compliance/sla endpoint generates availability and performance reports. The /compliance/sla/health endpoint provides real-time component status.
  • Audit Log Export — CSV export of all audit events via /compliance/audit-logs/export for evidence collection during SOC 2 audits.

Guardrails Integration

Flagged traces connect directly to the Guardrails system:

  1. Automated Flagging — When a compliance scan rule has autoFlag: true, traces with violations are automatically flagged with reason compliance_concern.
  2. Guardrail-to-Flag Pipeline — When a guardrail scan returns block or flag actions, the trace can be flagged for human review.
  3. Review Workflow — Team members can review flagged traces, add comments, update guardrail policies based on findings, and resolve flags.
  4. Violation Correlation — Use GET /compliance/scanning/violations/by-trace/:traceId alongside GET /flagged-traces/by-trace/:traceId to see both automated detections and human flags for the same trace.

Rate Limits

Endpoint GroupRate Limit
Flagged traces (create)30 per 15 minutes
Flagged trace comments60 per 15 minutes
Compliance scanningStandard API rate limits
Data export10 per hour

Error Codes

StatusCodeDescription
400BAD_REQUESTInvalid request body or parameters
401UNAUTHORIZEDMissing or invalid authentication
403FORBIDDENInsufficient permissions (e.g., non-admin accessing BAA endpoints)
404NOT_FOUNDResource not found or not accessible
409CONFLICTTrace already flagged
429RATE_LIMIT_EXCEEDEDToo many requests
503SERVICE_UNAVAILABLEDatabase or scanning pipeline unavailable

Next Steps