BT San Technology

8 June 2026

Audit trail vs change history: knowing who changed what in a web app

27 min read · Websites and web apps

Illustration: a monitor showing a change-history timeline of users with clock icons and arrows, beside a binder
AI-generated illustration

Sales reports that a customer's credit limit was raised from 50,000 to 80,000 last week, but nobody admits to doing it. The edit screen shows only the current value. Nothing says what the old value was, who changed it, why, or when. What the business needs at that point is an audit trail, not just an edit-history button.

This article builds an audit trail in TypeScript that Node 24 runs directly, with the node:sqlite database that ships with Node, so there is nothing to install. It includes code you can run yourself, real output, and a demo that edits a log row directly in the database and shows the system pointing to the row that was changed. Managers can follow the explanations and tables. Engineers can run the code alongside.

The real problem: the history exists, but you cannot decide anything from it

Change history and an audit trail are often confused. Change history answers a user's question: what did this document say before? An audit trail answers an auditor's or business owner's question: who did what to important data, when, with what authority, and how far can you trust that the record was not altered afterward? The example in this article therefore focuses on three things: the record is complete, it is consistent with the real data, and you can check whether anyone has tampered with it.

Consider three hypothetical situations, not projects of any BT San customer.

  • A building materials shop that gives credit to regular customers: one customer's credit limit was raised without an approval document. When a bad debt appears, nobody can say who raised it, why, or what the limit was before.
  • A manufacturer with tiered customer prices: the price of one product was edited below cost on a Monday morning, and three quotations have already gone out. Accounting needs to know the price at the time each quotation was issued, not the price now.
  • A system where an administrator edits data on a manager's behalf: an IT staff member changes data at a manager's request. The log shows only the IT staff member's name, not on whose behalf they acted, so the real approver cannot be traced.

These three cases need different things. The first needs the before and after values with a reason. The second needs a view of the state at a given point in time. The third needs to separate the person who acted from the person they acted for. All three need a record that can be trusted not to have been edited later.

What the documentation says: what is known and what it does not answer

The conclusions below come from the documents cited at the end of the article and serve as the basis for decisions. Where the documents give no figure, such as how many years to keep a log, this article does not guess.

TopicWhat the documentation saysWhat it means for our code
What to recordThe OWASP Logging Cheat Sheet says to record when, where, who and what, identifying the user, the event time, the event type and a description, and to log use of high-risk functions such as user management and data exportAn audit row has actor, ts_utc, entity, action, changes, request_id
Preventing after-the-fact editsOWASP says to add a mechanism that detects modification or deletion of records (tamper detection) and to copy logs to read-only media as soon as possibleUse a hash chain to check, and keep the latest hash outside the database
Read accessOWASP says to restrict read access to logs, review it periodically, and record every access to the logsReading the log is itself an event that must be recorded
Data that should not be loggedOWASP says to remove, mask, sanitize, hash or encrypt data such as passwords, tokens and some kinds of personal data, for example government-issued ID numbersmask.ts masks phone numbers and ID card numbers before writing
TimeOWASP says to synchronize clocks across all machines (it does not mention UTC directly, but says to use an international time format)Store UTC and convert to Thai time when displaying
RetentionOWASP says logs should not be destroyed before the required retention period ends and should not be kept beyond it, with legal, regulatory and contractual obligations applying, but it does not specify a number of yearsRetention is a decision for the business and its legal adviser
The database can record by itselfSQLite says a trigger has OLD and NEW to reference the values before and after, can filter with WHEN, and can stop a statement with an error message using RAISE(ABORT, ...). The documentation recommends an AFTER trigger when the trigger modifies the same rowUse a trigger to block UPDATE/DELETE on audit_log; it is also an alternative shown in the example
Write locksSQLite says only one write transaction can exist at a time, and BEGIN IMMEDIATE starts a write transaction right away; if another connection holds it, you get SQLITE_BUSY at the startUse BEGIN IMMEDIATE before reading the last row of the chain, so two writers cannot extend the chain at once
Summary of the OWASP Logging Cheat Sheet and the SQLite documentation, as read on 2026-11-21. NIST SP 800-92 (Guide to Computer Security Log Management, 2006) is an overview guide to log management that NIST's web page still shows as final. Figures and requirements under Thai law must be checked with a legal adviser.

The latest Node.js documentation lists node:sqlite as a release candidate (Stability 1.2) and calls DatabaseSync a deprecated alias of Database in newer versions. This example runs on Node 24.21, which uses the name DatabaseSync and does not print an ExperimentalWarning. When you move to a newer Node release, check the class name against that release's documentation.

Overview of the example

All the code is in the folder examples/audit-trail-change-history-business-web/. It uses only Node 24 built-ins (node:sqlite, node:crypto), with no npm install. TypeScript runs directly with the node command on a .ts file. (Node only strips the types without checking them. It does not support enum, namespaces that contain code, or parameter properties, and import statements must include the .ts extension, as the Node documentation states.)

FilePurpose
schema.sqlThe customers and audit_log tables, with triggers that block UPDATE/DELETE on audit_log
audit.tssaveCustomer: the only place data can be changed; it updates the real table and writes the audit row in one transaction
diff.tsCompares before and after field by field and keeps only what changed
mask.tsMasks phone numbers and ID card numbers before logging
chain.tsA SHA-256 hash chain, and verifyChain, which points to the first bad row
history.tsasOf: rebuilds the state of a record at an earlier time from the log
trigger-alt.tsThe alternative: a database trigger
demo.ts and output.txtAn end-to-end demo and the output from a real run
audit.test.tsA node:test suite with 9 cases
Files in the example folder. All data is fictional.

Run commands: node --no-warnings demo.ts and node --no-warnings --test audit.test.ts (--no-warnings hides the MODULE_TYPELESS_PACKAGE_JSON warning because the example folder has no package.json; it does not affect the code).

Step 1: an append-only table

audit_log has a seq that always runs continuously from 1, which is used to check whether any row is missing. Each row stores prev_hash, the hash of the previous row, and its own hash. The actor is split into two columns, actor and on_behalf_of, and request_id ties together rows that come from the same request and links them to the app's own log.

schema.sql
-- ตารางธุรกิจ
CREATE TABLE customers (
  id           TEXT PRIMARY KEY,
  name         TEXT NOT NULL,
  phone        TEXT,
  national_id  TEXT,
  credit_limit INTEGER NOT NULL DEFAULT 0,
  discount_pct INTEGER NOT NULL DEFAULT 0
);

-- audit log แบบ append-only: seq ต่อเนื่อง และแต่ละแถวเก็บ hash ของแถวก่อนหน้า
CREATE TABLE audit_log (
  seq          INTEGER PRIMARY KEY,
  ts_utc       TEXT NOT NULL,
  actor        TEXT NOT NULL,
  on_behalf_of TEXT,
  request_id   TEXT NOT NULL,
  entity       TEXT NOT NULL,
  entity_id    TEXT NOT NULL,
  action       TEXT NOT NULL CHECK (action IN ('create','update','delete')),
  changes      TEXT NOT NULL,
  reason       TEXT,
  prev_hash    TEXT NOT NULL,
  hash         TEXT NOT NULL UNIQUE
);

-- ชั้นกันแรก: UPDATE/DELETE ผ่าน SQL ธรรมดาจะล้ม (คนที่มีสิทธิ์ DROP TRIGGER ยังข้ามได้ จึงต้องมี hash chain เสริม)
CREATE TRIGGER audit_log_no_update BEFORE UPDATE ON audit_log
BEGIN SELECT RAISE(ABORT, 'audit_log is append-only'); END;
CREATE TRIGGER audit_log_no_delete BEFORE DELETE ON audit_log
BEGIN SELECT RAISE(ABORT, 'audit_log is append-only'); END;
schema.sql has triggers that block editing and deleting log rows through ordinary SQL

This trigger layer guards against slips and against people who do not know better, but anyone with permission to DROP TRIGGER can remove it. That is why a hash chain is needed as a second layer, and the last row of step 5 in the output shows that the example simulates exactly this case.

Step 2: one function that changes the data and writes the audit together

The core of the system is that every way of changing data must go through saveCustomer, and only there. If the app has several places that can write to the customers table directly, there will be a day when someone forgets to write the log. The function opens a BEGIN IMMEDIATE transaction, reads the existing row and computes the diff. If nothing changed, it writes no log. If a field that requires a reason has no reason, it throws an error, so neither the business row nor the log row is created, because the whole transaction fails. Then it updates the real table, masks sensitive values, chains the hash onto the last row in the chain, and runs COMMIT.

audit.ts · lines 19–63
export function saveCustomer(db: DatabaseSync, ctx: Ctx, id: string, patch: Row, reason?: string): number | null {
  for (const k of Object.keys(patch)) if (!(FIELDS as readonly string[]).includes(k)) throw new Error(`unknown field: ${k}`);
  db.exec("BEGIN IMMEDIATE"); // ล็อกเขียนก่อนอ่านแถวท้ายของโซ่ กันสองคนต่อโซ่พร้อมกัน
  try {
    const before = (db.prepare("SELECT * FROM customers WHERE id = ?").get(id) as Row | undefined) ?? null;
    const after: Row = { ...(before ?? {}), ...patch };
    const changed = diffFields(before, after, FIELDS);
    const names = Object.keys(changed);
    if (names.length === 0) { db.exec("ROLLBACK"); return null; } // ไม่มีอะไรเปลี่ยน ไม่ลง log
    if (names.some((f) => REASON_REQUIRED.includes(f)) && !reason?.trim()) {
      throw new Error(`reason required when changing: ${names.filter((f) => REASON_REQUIRED.includes(f)).join(", ")}`);
    }
    if (before === null) {
      db.prepare("INSERT INTO customers (id, name, phone, national_id, credit_limit, discount_pct) VALUES (?, ?, ?, ?, ?, ?)")
        .run(id, String(after.name), (after.phone ?? null) as string | null, (after.national_id ?? null) as string | null, Number(after.credit_limit ?? 0), Number(after.discount_pct ?? 0));
    } else {
      const sets = names.map((f) => `${f} = ?`).join(", "); // ชื่อ field ผ่าน allowlist ด้านบนแล้ว
      db.prepare(`UPDATE customers SET ${sets} WHERE id = ?`).run(...names.map((f) => changed[f].to as string | number | null), id);
    }
    // ปิดบังก่อนเก็บ: ค่าจริงของ phone/national_id ไม่เคยเข้า log
    const masked: Record<string, unknown> = {};
    for (const f of names) masked[f] = { from: maskValue(f, changed[f].from), to: maskValue(f, changed[f].to) };
    const last = db.prepare("SELECT seq, hash FROM audit_log ORDER BY seq DESC LIMIT 1").get() as { seq: number; hash: string } | undefined;
    const row: Omit<AuditRow, "hash"> = {
      seq: (last?.seq ?? 0) + 1,
      ts_utc: (ctx.now ?? new Date()).toISOString(),
      actor: ctx.actor,
      on_behalf_of: ctx.onBehalfOf ?? null,
      request_id: ctx.requestId,
      entity: "customer",
      entity_id: id,
      action: before === null ? "create" : "update",
      changes: JSON.stringify(masked),
      reason: reason?.trim() || null,
      prev_hash: last?.hash ?? GENESIS,
    };
    db.prepare("INSERT INTO audit_log VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
      .run(row.seq, row.ts_utc, row.actor, row.on_behalf_of, row.request_id, row.entity, row.entity_id, row.action, row.changes, row.reason, row.prev_hash, rowHash(row));
    db.exec("COMMIT");
    return row.seq;
  } catch (e) {
    db.exec("ROLLBACK");
    throw e;
  }
}
audit.ts: the saveCustomer function in a single transaction

Three points to note. First, the field names in the UPDATE come from an allowlist checked on the first line of the function, and no user-supplied text is concatenated into SQL. Second, the values of phone and national_id pass through maskValue before they enter the log, so the real values exist only in the customers table. Third, ts_utc is UTC in ISO format, and Thai time is converted at display time by showBangkok at the end of the file, because a time stored in local time becomes ambiguous when the time zone changes or the server moves.

diff.ts
// เทียบก่อน/หลังทีละ field คืนเฉพาะ field ที่เปลี่ยนจริง (ฟังก์ชันล้วน ไม่แตะฐานข้อมูล)
export type Row = Record<string, unknown>;
export type Change = { from: unknown; to: unknown };

export function diffFields(before: Row | null, after: Row, fields: readonly string[]): Record<string, Change> {
  const out: Record<string, Change> = {};
  for (const f of fields) {
    const from = before?.[f] ?? null;
    const to = after[f] ?? null;
    if (from !== to) out[f] = { from, to };
  }
  return out;
}
diff.ts: a pure function that compares only the specified fields
mask.ts
// ปิดบังค่าอ่อนไหวก่อนลง log: เก็บแค่ 2 ตัวท้าย ที่เหลือเป็น x
export const MASKED_FIELDS: readonly string[] = ["phone", "national_id"];

export function maskValue(field: string, value: unknown): unknown {
  if (!MASKED_FIELDS.includes(field) || value === null || value === undefined) return value;
  const s = String(value);
  if (s.length <= 2) return "x".repeat(s.length);
  return "x".repeat(s.length - 2) + s.slice(-2);
}
mask.ts keeps the last two characters, enough to tell that the value changed to something else

Masking has a cost you should know about. When values in the log are masked, a point-in-time reconstruction returns the phone value in its masked form, and if two values differ only in the masked characters, the log shows a change but cannot show what it changed from. This is intentional. If the business needs the real values later, store them separately in a place with stricter access control, not in a log that many people can read.

Step 3: the hash chain, where an edited row gets pointed out

Each row's hash is the SHA-256 of all its fields together with prev_hash. Editing any row makes that row's hash wrong, and if an attacker recomputes that row's hash, the next row's prev_hash no longer matches, so the whole chain has to be recomputed to the end. verifyChain walks from seq 1 and reports the first bad row. It also catches a gap in the seq sequence, which means a row was deleted.

chain.ts · lines 19–42
export const GENESIS = "0".repeat(64);

export function rowHash(r: Omit<AuditRow, "hash">): string {
  // JSON array ลำดับตายตัว ไม่ใช้ object เพื่อไม่ให้ลำดับ key มีผล
  const body = JSON.stringify([r.seq, r.ts_utc, r.actor, r.on_behalf_of, r.request_id, r.entity, r.entity_id, r.action, r.changes, r.reason, r.prev_hash]);
  return createHash("sha256").update(body).digest("hex");
}

export type Verdict = { ok: true; rows: number; head: string } | { ok: false; seq: number; why: string };

// เดินโซ่จาก seq 1 ขึ้นไป บอกแถวแรกที่ผิด ถ้าส่ง anchoredHead มา จะเทียบ hash ท้ายสุดกับค่าที่เก็บไว้ที่อื่นด้วย
export function verifyChain(rows: AuditRow[], anchoredHead?: string): Verdict {
  let prev = GENESIS;
  for (const [i, r] of rows.entries()) {
    if (r.seq !== i + 1) return { ok: false, seq: i + 1, why: `ลำดับขาด: คาดว่า seq ${i + 1} แต่พบ ${r.seq} (อาจมีแถวถูกลบ)` };
    if (r.prev_hash !== prev) return { ok: false, seq: r.seq, why: "prev_hash ไม่ตรงกับ hash ของแถวก่อนหน้า" };
    if (rowHash(r) !== r.hash) return { ok: false, seq: r.seq, why: "hash ไม่ตรงกับเนื้อหาแถว (แถวถูกแก้)" };
    prev = r.hash;
  }
  if (anchoredHead !== undefined && prev !== anchoredHead) {
    return { ok: false, seq: rows.length, why: "hash ท้ายสุดไม่ตรงกับค่าที่เก็บไว้ภายนอก (โซ่ถูกเขียนใหม่หรือตัดท้าย)" };
  }
  return { ok: true, rows: rows.length, head: prev };
}
chain.ts: rowHash and verifyChain with the anchoredHead option

The anchoredHead parameter separates a meaningful check from one that fools itself. An attacker with full database access can rewrite the entire chain so the hashes link up perfectly. Without the latest hash stored somewhere else, verify will answer ok. What the chain gives you is therefore evidence that tampering happened (tamper-evident), not protection against tampering (tamper-proof).

Step 4: reconstructing the state at a point in time

The second quotation in the scenarios above needs the price at the exact second it was issued. Because the log stores every change in order, we can replay it from the first row up to the time we want. The function is small enough to read in a minute.

history.ts
import type { AuditRow } from "./chain.ts";

// สร้างสถานะของระเบียนย้อนหลัง ณ เวลาที่กำหนด โดยเล่น log ซ้ำจากแถวแรก
// ข้อจำกัด: field ที่ปิดบังไว้ (phone, national_id) จะได้กลับมาเป็นค่าที่ปิดบังเท่านั้น
export function asOf(rows: AuditRow[], entity: string, id: string, atUtc: string): Record<string, unknown> | null {
  const cutoff = Date.parse(atUtc);
  let state: Record<string, unknown> | null = null;
  for (const r of rows) {
    if (r.entity !== entity || r.entity_id !== id || Date.parse(r.ts_utc) > cutoff) continue;
    if (r.action === "delete") { state = null; continue; }
    const changes = JSON.parse(r.changes) as Record<string, { from: unknown; to: unknown }>;
    state = { ...(state ?? { id }) };
    for (const [f, c] of Object.entries(changes)) state[f] = c.to;
  }
  return state;
}
history.ts: asOf replays the log up to a given time

If there are many records or the log is long, replaying from the first row every time becomes slow. Real systems usually take snapshots periodically and replay from the latest snapshot before the requested time.

A real run: record, look back, edit a log row, then verify

demo.ts uses fixed times so the results are repeatable. The most important parts are steps 5 and 6, which simulate someone with database access quietly editing a credit limit in the log, both by changing a single row and by rewriting the whole chain.

demo.ts · lines 38–52
console.log("\n== 5 แก้แถว log ตรง ๆ ใน DB ==");
try { db.exec("UPDATE audit_log SET reason = 'x' WHERE seq = 2"); } catch (e) { console.log("trigger กันไว้:", (e as Error).message); }
db.exec("DROP TRIGGER audit_log_no_update"); // จำลองคนที่มีสิทธิ์ DBA ถอดตัวกันออก
db.exec(`UPDATE audit_log SET changes = replace(changes, '80000', '30000') WHERE seq = 2`);
const v2 = verifyChain(readLog(db), anchor);
console.log("verify:", v2.ok ? "ok" : `พบความผิดปกติที่ seq ${v2.seq}: ${v2.why}`);

console.log("\n== 6 ผู้โจมตีคำนวณ hash ใหม่ทั้งโซ่ ==");
const forged: AuditRow[] = readLog(db);
let prev = forged[0].prev_hash;
for (const r of forged) { r.prev_hash = prev; r.hash = rowHash(r); prev = r.hash; }
const v3 = verifyChain(forged);
console.log("verify (ไม่มี anchor):", v3.ok ? "ok  <- ตรวจไม่เจอ" : v3.why);
const v4 = verifyChain(forged, anchor);
console.log("verify (มี anchor):", v4.ok ? "ok" : `พบความผิดปกติ: ${v4.why}`);
demo.ts steps 5 and 6: remove the trigger, edit a log row directly, then verify without and with an anchor
output.txt
== 1 บันทึกการเปลี่ยนแปลง ==
ปฏิเสธ (ไม่ใส่เหตุผล): reason required when changing: credit_limit
แก้ซ้ำค่าเดิม ได้ seq = null

== 2 ประวัติ (แสดงเวลาไทย เก็บเป็น UTC) ==
#1 2026-11-20 09:00:00 (Asia/Bangkok) somchai req-001 create C-001
   changes={"name":{"from":null,"to":"ร้านตัวอย่างการค้า"},"phone":{"from":null,"to":"xxxxxxxx78"},"national_id":{"from":null,"to":"xxxxxxxxxxx23"},"credit_limit":{"from":null,"to":50000},"discount_pct":{"from":null,"to":0}}
   เหตุผล: เปิดบัญชีใหม่ วงเงินตามใบสมัคร
#2 2026-11-20 11:00:00 (Asia/Bangkok) svc-ops แทน malee req-003 update C-001
   changes={"credit_limit":{"from":50000,"to":80000}}
   เหตุผล: ลูกค้าสั่งซื้อเพิ่ม ผู้จัดการอนุมัติทางอีเมล
#3 2026-11-21 08:30:00 (Asia/Bangkok) somchai req-004 update C-001
   changes={"phone":{"from":"xxxxxxxx78","to":"xxxxxxxx99"}}
#4 2026-11-21 10:00:00 (Asia/Bangkok) malee req-006 update C-001
   changes={"credit_limit":{"from":80000,"to":60000},"discount_pct":{"from":0,"to":5}}
   เหตุผล: ผิดนัดชำระงวดก่อน ลดวงเงินและยกเลิกส่วนลดบางส่วน

== 3 ตรวจโซ่ hash ==
verify: ok 4 แถว
hash ท้ายสุด (ควรเก็บไว้นอกฐานข้อมูล): bff3e7216d8b9829...

== 4 ย้อนดูสถานะ ณ เวลาหนึ่ง ==
2026-11-20 10:30:00 (Asia/Bangkok) -> credit_limit=50000 discount_pct=0 phone=xxxxxxxx78
2026-11-20 12:00:00 (Asia/Bangkok) -> credit_limit=80000 discount_pct=0 phone=xxxxxxxx78
2026-11-21 11:00:00 (Asia/Bangkok) -> credit_limit=60000 discount_pct=5 phone=xxxxxxxx99

== 5 แก้แถว log ตรง ๆ ใน DB ==
trigger กันไว้: audit_log is append-only
verify: พบความผิดปกติที่ seq 2: hash ไม่ตรงกับเนื้อหาแถว (แถวถูกแก้)

== 6 ผู้โจมตีคำนวณ hash ใหม่ทั้งโซ่ ==
verify (ไม่มี anchor): ok  <- ตรวจไม่เจอ
verify (มี anchor): พบความผิดปกติ: hash ท้ายสุดไม่ตรงกับค่าที่เก็บไว้ภายนอก (โซ่ถูกเขียนใหม่หรือตัดท้าย)

== 7 ทางเลือก: trigger ในฐานข้อมูล ==
trigger log #1: C-1 50000 -> 80000 ผู้ใช้=somchai
trigger log #2: C-1 80000 -> 999999 ผู้ใช้=(ไม่ทราบ)
Output from a real run on 2026-11-21 with node --no-warnings demo.ts (Node 24.21). --no-warnings is used only to hide the MODULE_TYPELESS_PACKAGE_JSON warning.

Reading the output step by step

  1. Changing credit_limit without a reason is rejected. Saving the same value again gives a seq of null, meaning nothing is logged. Row 2 is an edit that svc-ops made on behalf of malee, with a reason, which answers the third scenario directly.
  2. The history shows Thai time (UTC+7) even though the database holds UTC, and shows the phone number changing from xxxxxxxx78 to xxxxxxxx99 with no real number in the log.
  3. verify passes for 4 rows and prints the latest hash. This is the value you should keep outside the database.
  4. Looking back at three points in time gives a credit limit of 50000 before the approval, 80000 after the approval, and 60000 with a 5 discount, according to row 4.
  5. A direct UPDATE is blocked by the trigger, but after the trigger is removed (simulating a database administrator) and the credit limit in row 2 is changed from 80000 to 30000, verify points to seq 2 and says the hash does not match the content.
  6. When the attacker recomputes the hash of the whole chain, verify without an anchor answers ok, which means it fails to detect the change. With an anchor, it detects the change because the latest hash does not match the value stored outside.
  7. Step 7, the trigger alternative: an edit through the app carries the name somchai, while a direct SQL edit is also caught, but the user shows as (ไม่ทราบ) (unknown).

The test suite

audit.test.ts has 9 cases. Running node --no-warnings --test audit.test.ts gives 9 passes. The tests cover diff; masking, by checking that the real value is nowhere in the log; the reason requirement, which must leave no row in either table; no logging when the value is unchanged; verify pointing to the position of an edited row and a missing row; a rewritten chain that passes without an anchor and fails with one; asOf before and after a record is created; and the trigger behavior. If anyone edits the code and breaks any mechanism, the tests fail.

Alternative: let the database record by itself with a trigger

Another approach is to not have the app write the audit at all, and instead put triggers on the business tables so the database records every UPDATE. The big advantage is that it catches every path, including data-repair scripts and SQL opened from a console. The drawback is that a trigger sees only the database. It does not know who the user in the app is, and it does not know the reason or the request id, so the app has to pass them in first every time.

trigger-alt.ts
import { DatabaseSync } from "node:sqlite";

// ทางเลือก: ให้ฐานข้อมูลจดเองด้วย trigger จับได้แม้แก้ด้วย SQL ตรง ๆ แต่ไม่รู้ว่าใครเป็นผู้ใช้แอป
// SQLite ไม่มีตัวแปรเซสชัน จึงใช้ตาราง app_ctx ให้แอปใส่ชื่อผู้ใช้ก่อนเขียน (Postgres ใช้ set_config / current_setting ได้)
export function triggerDemo(): string[] {
  const db = new DatabaseSync(":memory:");
  db.exec(`
    CREATE TABLE customers (id TEXT PRIMARY KEY, credit_limit INTEGER NOT NULL);
    CREATE TABLE app_ctx (k TEXT PRIMARY KEY, v TEXT);
    CREATE TABLE trg_log (n INTEGER PRIMARY KEY, id TEXT, old_limit INTEGER, new_limit INTEGER, who TEXT);
    CREATE TRIGGER customers_audit AFTER UPDATE OF credit_limit ON customers
    WHEN OLD.credit_limit IS NOT NEW.credit_limit
    BEGIN
      INSERT INTO trg_log (id, old_limit, new_limit, who)
      VALUES (NEW.id, OLD.credit_limit, NEW.credit_limit, (SELECT v FROM app_ctx WHERE k = 'user'));
    END;
    INSERT INTO customers VALUES ('C-1', 50000);
  `);
  const out: string[] = [];
  // 1) ผ่านแอป: ตั้งชื่อผู้ใช้ก่อน แก้ แล้วล้างทิ้ง
  db.exec("INSERT INTO app_ctx VALUES ('user', 'somchai')");
  db.exec("UPDATE customers SET credit_limit = 80000 WHERE id = 'C-1'");
  db.exec("DELETE FROM app_ctx");
  // 2) SQL ตรง ๆ จากคอนโซลฐานข้อมูล: trigger ยังจับได้ แต่ who ว่าง
  db.exec("UPDATE customers SET credit_limit = 999999 WHERE id = 'C-1'");
  for (const r of db.prepare("SELECT * FROM trg_log ORDER BY n").all() as Array<Record<string, unknown>>) {
    out.push(`trigger log #${r.n}: ${r.id} ${r.old_limit} -> ${r.new_limit} ผู้ใช้=${r.who ?? "(ไม่ทราบ)"}`);
  }
  db.close();
  return out;
}
trigger-alt.ts: the user is passed through the app_ctx table because SQLite has no session variables
IssueApp writes the audit itselfTrigger in the database
Knows the user, reason and request idKnows all of them, because it lives in the appThey must be passed in; if forgotten, they are empty
Edit with direct SQLNot recorded (detectable by comparing against the log)Recorded, but the user is unknown
Main riskForgetting to call the function in some placeAnyone with DDL permission can drop the trigger, and the user-passing mechanism may keep a stale value
Moving to another databaseMoves with the codeTriggers must be rewritten in the new database's dialect
A comparison based on the example code in this article. Real systems often use both approaches together: the app writes events that have business meaning, and a trigger acts as a safety net.

Hypothetical examples: applying it to three businesses

A building materials shop that gives credit

The fields that need a reason are credit_limit and the payment terms. The reason should cite an approval document number, not be pure free text. If the company has a two-level approval step, the audit should store both the requester and the approver (the article on multi-level approval explains that mechanism).

A manufacturer with a price table

A quotation should store the price on the date it was issued inside the quotation itself. Looking back with asOf is for checking and finding causes. It should not be the only way an old quotation knows its own price.

An internal document system where administrators edit on others' behalf

Use the on_behalf_of column from day one. Adding it later leaves all the old rows with a gap that cannot be explained. Also remember that the right to act on someone's behalf should be limited and auditable like any other permission (see the article on resource-based permissions).

What else to consider for real use

Keep the latest hash somewhere else

This is the core of tamper evidence. Set up a job that runs every night, reads the latest hash, and sends it to a destination that database administrators cannot edit, such as write-once storage (WORM), an email into the auditor's inbox, or a separate log system with different permissions. OWASP recommends copying logs to read-only media as soon as possible for the same reason. Do not let auditors think the chain is armor. It is a warning signal.

Log volume and partitioning

A log that only grows will grow without limit. In this example, verify reads the entire chain, which works for thousands of rows. At millions of rows you need to split it into periods, for example monthly, with each period starting from the closing hash of the previous one, and verify only the new period regularly. Verify everything only occasionally.

Logs contain personal data too, and someone must manage read access

Names, users and the changed content in a log can also be personal data, which needs a lawful basis for keeping it and a retention period. As OWASP says, do not keep logs beyond the period needed, and do not destroy them before it ends. Setting the number of years is something to agree with the company's legal team or PDPA adviser. This article is not legal advice. As for read access, give it only to auditors and managers by role, separate from system administrators who can edit data, and record every time someone opens the log in the log itself.

Time and the writing machine

The example uses the clock of the machine running the app. If there are several machines, clocks must be synchronized (OWASP states this), and the chain must have only one writer extending it at a time. The example uses SQLite's BEGIN IMMEDIATE. If you move to PostgreSQL, use an equivalent lock, such as an advisory lock or SELECT FOR UPDATE on the chain's head row. For the idea of concurrent writes racing each other, see the article on transactions and double booking.

Common mistakes and a checklist

  • Writing the audit as a separate statement after COMMIT. If the app crashes in between, the data changes but there is no log.
  • Storing only the new value and not the old one, so you cannot answer what it changed from.
  • Using an email or an editable name as the user identifier instead of an id that does not change.
  • Logging the whole JSON of the record, including ID card numbers and passwords, and letting many people in the team read it.
  • Storing time in local time without specifying the time zone.
  • Building a hash chain and storing the latest hash in the same table. An attacker can overwrite it in one statement.
  • Giving the app's account UPDATE/DELETE permission on audit_log in production when the app only needs INSERT and SELECT.
  • Not testing that verify really detects tampering. That is why this example has a case for editing a row and a case for rewriting the chain in its test suite.

Pre-release checklist

  1. Specify the fields and events that need an audit, and the fields that need a reason.
  2. Every path that changes data calls the one central function, and the change and the audit are in one transaction.
  3. The actor, the person acted for, the UTC time and the request id are all recorded.
  4. Sensitive values are masked before they enter the log, and you have checked that they do not leak into other channels.
  5. The app's account has only insert and read permission on audit_log.
  6. A scheduled verify job exists, and the latest hash is sent for storage outside the database.
  7. Read access to the log, the retention period and the deletion method at the end of the period are set together with the legal team.
  8. Rehearse editing a log row in a test system and check that the alert works.

Limitations of the example: it uses an in-memory database with a single table, has no deletion of business records, no read access control for the log, no sending of the hash out for storage, no chain partitioning, and no snapshots for asOf. It was not tested with several processes writing at once, and SQLite differs from PostgreSQL in locking and triggers. Use it for learning, not as production-ready code, and not as legal advice.

References

  1. OWASP — Logging Cheat Sheet (event attributes, tamper detection, access, data to exclude, retention) (accessed 2026-11-21)
  2. NIST SP 800-92 — Guide to Computer Security Log Management (2006, final) (accessed 2026-11-21)
  3. SQLite — CREATE TRIGGER (OLD/NEW, WHEN, UPDATE OF, RAISE) (accessed 2026-11-21)
  4. SQLite — BEGIN TRANSACTION (DEFERRED, IMMEDIATE, EXCLUSIVE) (accessed 2026-11-21)
  5. Node.js — node:sqlite (stability, DatabaseSync) (accessed 2026-11-21)
  6. Node.js — Running TypeScript natively (type stripping) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer