Skip to main content
skill CX Codex

klingai-audit-logging — Claude Code skill: setup and features

klingai-audit-logging sets up tamper-evident audit logging for Kling AI API calls. It tracks video generation tasks, checks log integrity, and hashes prompts.

MIT 1 installs ★ 2,935 updated 2026-11-01

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add jeremylongshore/tons-of-skills-marketplace --skill klingai-audit-logging -a claude-code
Open on GitHub

What klingai-audit-logging does

The skill provides an append-only logging pattern for Kling AI video generation workflows. Each event writes to daily .jsonl files inside an audit directory. Every entry stores a SHA-256 digest referencing the previous record, which makes silent modifications impossible to hide.

The architecture includes AuditLogger, KlingAuditClient, and a verification function named verify_audit_chain. Instead of saving raw text prompts or API secrets, it stores a 16-character SHA-256 prompt hash alongside the character count. A built-in report function aggregates operations and actors over a specified timeframe.

What it helps with

  • Log Kling AI API operations in an append-only JSONL format
  • Verify log chain integrity with SHA-256 checksums
  • Aggregate usage reports by actor and event type
  • Protect user privacy by hashing video prompts instead of storing raw text

Example prompts for the agent

  • Set up a klingai audit log for our video generation tasks
  • Run a klingai compliance log check on recent API events
  • Generate a video generation audit trail report for the past 30 days

How to install klingai-audit-logging

1Skills CLI (Vercel)

npx skills add jeremylongshore/tons-of-skills-marketplace --skill klingai-audit-logging -a claude-code

2Manually: put the files in place

~/.claude/skills/klingai-audit-logging/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/klingai-audit-logging/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about klingai-audit-logging

How to install klingai-audit-logging in Claude Code?

Run npx skills add jeremylongshore/tons-of-skills-marketplace --skill klingai-audit-logging -a claude-code. You can also configure it manually at ~/.claude/skills/klingai-audit-logging/SKILL.md.

What does klingai-audit-logging do?

It wraps Kling AI API calls to record task submissions, status updates, and auth attempts. Each record links to the previous hash to detect log tampering.

Does it store raw user prompts?

No, it avoids storing plaintext prompts. The client hashes prompt strings with SHA-256 and records only the first 16 characters and the prompt length.

Source text

SKILL.md · MIT
---
name: klingai-audit-logging
description: 'Implement audit logging for Kling AI operations for compliance and security.
  Use when tracking

  API usage or preparing for audits. Trigger with phrases like ''klingai audit'',
  ''kling ai audit log'',

  ''klingai compliance log'', ''video generation audit trail''.

  '
allowed-tools: Read, Write, Edit, Bash(npm:*), Grep
version: 1.18.0
license: MIT
author: Jeremy Longshore <[email protected]>
tags:
- saas
- kling-ai
- audit
- compliance
- logging
compatibility: Designed for Claude Code
---
# Kling AI Audit Logging

## Overview

Compliance-grade audit logging for Kling AI API operations. Every task submission, status change, and credential usage is captured in tamper-evident structured logs.

## Audit Event Schema

```python
import json
import hashlib
import time
from datetime import datetime
from pathlib import Path

class AuditLogger:
    """Append-only audit log with integrity checksums."""

    def __init__(self, log_dir: str = "audit"):
        self.log_dir = Path(log_dir)
        self.log_dir.mkdir(exist_ok=True)
        self._prev_hash = "genesis"

    def _compute_hash(self, entry: dict) -> str:
        raw = json.dumps(entry, sort_keys=True) + self._prev_hash
        return hashlib.sha256(raw.encode()).hexdigest()[:16]

    def log(self, event_type: str, actor: str, details: dict):
        """Write a tamper-evident audit entry."""
        entry = {
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "event_type": event_type,
            "actor": actor,
            "details": details,
            "prev_hash": self._prev_hash,
        }
        entry["hash"] = self._compute_hash(entry)
        self._prev_hash = entry["hash"]

        date = datetime.utcnow().strftime("%Y-%m-%d")
        filepath = self.log_dir / f"audit-{date}.jsonl"
        with open(filepath, "a") as f:
            f.write(json.dumps(entry) + "\n")

        return entry["hash"]
```

## Audit Events for Kling AI

```python
class KlingAuditClient:
    """Kling client with full audit trail."""

    def __init__(self, base_client, audit: AuditLogger, actor: str = "system"):
        self.client = base_client
        self.audit = audit
        self.actor = actor

    def text_to_video(self, prompt: str, **kwargs):
        # Log submission
        self.audit.log("task_submitted", self.actor, {
            "action": "text_to_video",
            "model": kwargs.get("model", "kling-v2-master"),
            "duration": kwargs.get("duration", 5),
            "mode": kwargs.get("mode", "standard"),
            "prompt_hash": hashlib.sha256(prompt.encode()).hexdigest()[:16],
            "prompt_length": len(prompt),
        })

        result = self.client.text_to_video(prompt, **kwargs)

        # Log completion
        self.audit.log("task_completed", self.actor, {
            "action": "text_to_video",
            "status": "succeed",
            "video_count": len(result.get("videos", [])),
        })

        return result

    def log_auth_event(self, event: str, success: bool):
        self.audit.log("auth_event", self.actor, {
            "event": event,
            "success": success,
            "access_key_prefix": self.client.config.access_key[:8] + "...",
        })
```

## Audit Log Verification

```python
def verify_audit_chain(log_file: str) -> bool:
    """Verify tamper-evidence of audit log chain."""
    prev_hash = "genesis"
    entries = []

    with open(log_file) as f:
        for line_num, line in enumerate(f, 1):
            entry = json.loads(line)
            entries.append(entry)

            if entry["prev_hash"] != prev_hash:
                print(f"Chain broken at line {line_num}: "
                      f"expected prev_hash={prev_hash}, got {entry['prev_hash']}")
                return False

            # Recompute hash
            check_entry = {k: v for k, v in entry.items() if k != "hash"}
            raw = json.dumps(check_entry, sort_keys=True) + prev_hash
            expected_hash = hashlib.sha256(raw.encode()).hexdigest()[:16]

            if entry["hash"] != expected_hash:
                print(f"Hash mismatch at line {line_num}")
                return False

            prev_hash = entry["hash"]

    print(f"Verified {len(entries)} entries -- chain intact")
    return True
```

## Audit Report Generator

```python
def generate_audit_report(log_dir: str = "audit", days: int = 30) -> dict:
    """Generate compliance audit report."""
    from collections import Counter
    from datetime import timedelta

    log_path = Path(log_dir)
    events = []

    cutoff = datetime.utcnow() - timedelta(days=days)
    for filepath in sorted(log_path.glob("audit-*.jsonl")):
        with open(filepath) as f:
            for line in f:
                entry = json.loads(line)
                if entry["timestamp"] >= cutoff.isoformat():
                    events.append(entry)

    event_types = Counter(e["event_type"] for e in events)
    actors = Counter(e["actor"] for e in events)

    report = {
        "period_days": days,
        "total_events": len(events),
        "event_types": dict(event_types),
        "unique_actors": len(actors),
        "actors": dict(actors),
        "first_event": events[0]["timestamp"] if events else None,
        "last_event": events[-1]["timestamp"] if events else None,
    }

    print(f"\n=== Audit Report ({days} days) ===")
    print(f"Total events: {report['total_events']}")
    for event_type, count in event_types.most_common():
        print(f"  {event_type}: {count}")
    print(f"Actors: {', '.join(actors.keys())}")

    return report
```

## Compliance Checklist

- [ ] All API calls logged with timestamp, actor, action
- [ ] Prompts stored as hashes (not plaintext) for privacy
- [ ] Audit chain integrity verifiable
- [ ] Logs retained for required period (typically 1-7 years)
- [ ] Log access restricted to authorized personnel
- [ ] Regular verification of chain integrity

## Prerequisites

- An approved audit schema, authorized workspace, redaction standard, retention schedule, least-privilege reader roles, synthetic test event, and an incident/rollback owner.

## Instructions

1. Emit append-only, aggregate or hashed audit events; never store prompts, asset URLs, identities beyond approved pseudonymous references, or credentials.
2. Validate chain integrity, access controls, retention, deletion, policy/rights review, and draft-only workflow events using a sandbox fixture.
3. Halt exports or access changes on integrity, scope, policy, or retention drift; revoke temporary roles and restore the prior audit configuration.
4. Promote only after owner approval and retain a redacted verification receipt for the approved window.

## Output

Produce an audit receipt with environment, event classes, integrity/access checks, redaction and retention/deletion outcomes, policy/rights and draft-only assertions, owner approval, and rollback reference. Exclude event payloads, prompts, assets, and secrets.

## Error Handling

| Condition | Response |
|---|---|
| Integrity or access control fails | Stop audit delivery, revoke temporary access, and restore the last verified configuration. |
| Sensitive data reaches the log | Quarantine and delete the affected record, correct redaction, and document only the redacted incident. |

## Examples

`env=staging; events=hashed-aggregate; integrity=pass; access=least-privilege; retention=30d; draft-only=pass; rollback=available` is a valid audit check.

## Resources

- [Developer Portal](https://app.klingai.com/global/dev)
- [OWASP Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html)

© Jeremy Longshore · MIT · jeremylongshore/tons-of-skills-marketplace

Similar skills

All skills for Security →

From the same set139

The whole set →
coderabbit-incident-runbook coderabbit-incident-runbook — a skill that walks an operator through a CodeRabbit incident: a review outage, a burst of bad suggestions, lost access or a broken merge policy. It keeps the response ordered while the cause is still unclear. CX Codex +1 1installs sentry-prod-checklist sentry-prod-checklist is a Claude Code skill that audits Sentry before production, checking DSN secrets, sample rates, source map pipelines, and PII filtering. CX Codex +1 1installs sentry-policy-guardrails The sentry-policy-guardrails skill outlines shared Sentry rules across services, including event scrubbing, trace-rate caps, and CI checks for configuration drift. CX Codex +1 1installs gc-log-analyzer A skill for reading garbage collector logs in performance testing work. It turns on by itself when the request mentions gc log analyzer. CX Codex +1 1installs openrouter-audit-logging The openrouter-audit-logging skill adds an audit trail for OpenRouter calls, recording request metadata, cost, and a prompt hash. Use it to investigate errors or track model usage. CX Codex +1 1installs monitoring-whale-activity The monitoring-whale-activity skill monitors large cryptocurrency transactions and whale wallet movements across multiple blockchains in real-time. Triggers on phrases like "track whales", "monitor large transfers", "check whale activity". CX Codex +1 1installs lokalise-observability lokalise-observability sets up metrics, webhook tracking, and rate limit checks for Lokalise pipelines. Useful for tracking translation progress and API health. CX Codex +1 1installs model-evaluation-metrics The model-evaluation-metrics skill supports model evaluation work in ML Training by generating code, configurations, guidance, and checks for the results. CX Codex +1 1installs

Project sponsors

Companies that keep this analytics open