Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

audit-logging

БесплатноБез исполняемых скриптовНе проверен

Builds tamper-evident audit logs for compliance (SOC 2, HIPAA, PCI DSS): an append-only PostgreSQL table with a hash chain computed inside the database, a…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub17 установок в других каталогах

Об этом скилле

Audit Logging

Overview

A compliance audit log answers: who did what to which resource, when, from where, and with what result. It must also be tamper-evident, so an auditor can check that nobody edited or removed entries.

This skill puts the whole mechanism in PostgreSQL, so every application and every language gets it for free: a trigger links each row to the previous one by SHA-256, other triggers refuse UPDATE, DELETE and TRUNCATE, and one function re-checks the chain. The SQL below was run on PostgreSQL 18, including 40 concurrent inserts.

Retention floors to design for (confirm with your auditor, they depend on scope):

Standard Typical requirement
HIPAA Documentation kept 6 years (45 CFR 164.316(b)(2))
PCI DSS v4 (req. 10.5.1) 12 months of history, the latest 3 months immediately available for analysis
SOC 2 No fixed number; 1 year is the usual auditor expectation
GDPR Only as long as the purpose needs; log IDs, not personal data

Instructions

1. Required fields

Every entry records: id, occurred_at (UTC), actor_id and actor_type, action, resource_type and resource_id, result (success, failure, denied) and the source ip_address. Add session_id, reason (the clinical or business justification HIPAA asks for) and changed_fields (names only). Never store passwords, tokens or full old values of sensitive fields: the log outlives the data and cannot be edited to remove them.

2. Append-only, hash-chained table

CREATE TABLE audit_logs (
  seq           BIGINT PRIMARY KEY,  -- chain position, assigned by the trigger
  id            UUID NOT NULL DEFAULT gen_random_uuid(),
  occurred_at   TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
  actor_id      TEXT NOT NULL,
  actor_type    TEXT NOT NULL CHECK (actor_type IN ('user','service','admin','system','anonymous')),
  action        TEXT NOT NULL,
  resource_type TEXT NOT NULL,
  resource_id   TEXT NOT NULL,
  result        TEXT NOT NULL CHECK (result IN ('success','failure','denied')),
  ip_address    INET,
  session_id    TEXT,
  reason        TEXT,
  changed_fields TEXT[],
  prev_hash     BYTEA,
  hash          BYTEA NOT NULL
);
CREATE INDEX audit_actor_idx ON audit_logs (actor_id, occurred_at DESC);
CREATE INDEX audit_resource_idx ON audit_logs (resource_type, resource_id, occurred_at DESC);

-- The digest covers every business column, so changing any of them breaks the chain.
CREATE FUNCTION audit_row_digest(r audit_logs) RETURNS BYTEA LANGUAGE sql IMMUTABLE AS $$
  SELECT sha256(convert_to(jsonb_build_array(
    r.id, to_char(r.occurred_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'),
    r.actor_id, r.actor_type, r.action, r.resource_type, r.resource_id, r.result,
    host(r.ip_address), r.session_id, r.reason, r.changed_fields,
    encode(r.prev_hash, 'hex'))::text, 'UTF8'))
$$;

-- Link each new row to the previous one. The advisory lock serialises writers,
-- otherwise two concurrent inserts would share one parent and fork the chain.
-- SECURITY DEFINER: the trigger must read the previous row, which an INSERT-only role cannot do.
CREATE FUNCTION audit_chain() RETURNS trigger LANGUAGE plpgsql
  SECURITY DEFINER SET search_path = pg_catalog, public AS $$
BEGIN
  PERFORM pg_advisory_xact_lock(hashtext('audit_logs_chain'));
  SELECT seq + 1, hash INTO NEW.seq, NEW.prev_hash FROM audit_logs ORDER BY seq DESC LIMIT 1;
  NEW.seq := COALESCE(NEW.seq, 1);
  NEW.hash := audit_row_digest(NEW);
  RETURN NEW;
END $$;
CREATE TRIGGER audit_logs_chain BEFORE INSERT ON audit_logs
  FOR EACH ROW EXECUTE FUNCTION audit_chain();

CREATE FUNCTION audit_forbid() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'audit_logs is append-only'; END $$;
CREATE TRIGGER audit_logs_no_change BEFORE UPDATE OR DELETE ON audit_logs
  FOR EACH ROW EXECUTE FUNCTION audit_forbid();
CREATE TRIGGER audit_logs_no_truncate BEFORE TRUNCATE ON audit_logs
  FOR EACH STATEMENT EXECUTE FUNCTION audit_forbid();

The application never computes a hash. It inserts the business columns; seq, prev_hash and hash are filled by the trigger.

3. Verify the chain

CREATE FUNCTION audit_verify() RETURNS TABLE (broken_seq BIGINT) LANGUAGE sql STABLE AS $$
  SELECT seq FROM (
    SELECT a.*, lag(a.hash) OVER (ORDER BY seq) AS expected_prev FROM audit_logs a
  ) t
  WHERE t.hash IS DISTINCT FROM audit_row_digest(ROW(t.seq,t.id,t.occurred_at,t.actor_id,t.actor_type,
          t.action,t.resource_type,t.resource_id,t.result,t.ip_address,t.session_id,t.reason,
          t.changed_fields,t.prev_hash,t.hash)::audit_logs)
     OR t.prev_hash IS DISTINCT FROM t.expected_prev
  ORDER BY seq LIMIT 1
$$;

SELECT * FROM audit_verify();   -- zero rows = chain intact; otherwise the first broken seq

Run it on a schedule and alert on any row. A chain inside the same database protects against edits that bypass the triggers only if the ver

Полный SKILL.md на GitHub

Установить audit-logging в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл audit-logging?

Builds tamper-evident audit logs for compliance (SOC 2, HIPAA, PCI DSS): an append-only PostgreSQL table with a hash chain computed inside the database, a verification query, and an AWS CloudTrail plus S3 Object Lock archive. Use when building compliance audit trails, tracking who did what and when, or implementing immutable event logs that satisfy regulatory retention requirements.

Как установить скилл audit-logging?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл audit-logging запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить audit-logging с