Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Write audit rows and security events as JSON log lines for log drains
Claude6a0e8df734f2
diff --git a/.env.example b/.env.exampleindex d8ab9a6..6d03fcf 100644--- a/.env.example+++ b/.env.example@@ -128,3 +128,7 @@ EMAIL_DRIVER=capture# password, for when the identity provider is down.# PASSWORD_SIGN_IN=off++# Audit rows are copied to the function logs as JSON lines, for a Vercel log+# drain to send on to a SIEM. off keeps them out of the logs.+# AUDIT_LOG=offdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0d0eadf..041a7e8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,6 +34,9 @@ release says when it does.`SSO_CLIENT_SECRET`. New people get an account under the install'ssign-up rule. `PASSWORD_SIGN_IN=off` then turns password sign-in off,except for the addresses in `PASSWORD_SIGN_IN_ALLOWED_EMAILS`.+- Audit rows (site and document trails) and security events are written to+ the function logs as JSON lines once saved, so a Vercel log drain can+ deliver them to a SIEM. `AUDIT_LOG=off` stops the audit lines.This release changes the database (`20261117090000_sign_in_security.sql`,`20261117100000_session_controls.sql`), which the production build applies.diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 6d5f9d4..4acc60c 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -141,6 +141,7 @@ A deployment made with the button needs no environment variables. These are ther| `SEAL_TIMESTAMP_URL` | An RFC 3161 timestamp server that adds a trusted time to each seal, and long-term validation. See [Long-term validation](#long-term-validation). || `EIDEASY_CLIENT_ID`, `EIDEASY_SECRET` | Let senders ask for advanced or qualified signatures in the signers' own names, through eID Easy. See [Signatures in the signers' own names](#signatures-in-the-signers-own-names-eidas-ades-and-qes). || `CSC_API_URL`, `CSC_CLIENT_ID`, `CSC_CLIENT_SECRET` | The same through a trust service provider's remote signing service (CSC API v2). See [Signatures in the signers' own names](#signatures-in-the-signers-own-names-eidas-ades-and-qes). |+| `AUDIT_LOG` | `off` keeps audit rows out of the function logs. See [Send the audit trail to your SIEM](#send-the-audit-trail-to-your-siem). || `SSO_ISSUER`, `SSO_CLIENT_ID`, `SSO_CLIENT_SECRET` | Sign in through your organization's identity provider (Okta, Entra ID, Google Workspace). `PASSWORD_SIGN_IN=off` then turns passwords off. See [Single sign-on](#single-sign-on). |## Set the site up@@ -166,6 +167,17 @@ These cover the people with an account (senders and administrators). Signers who- **Wrong passwords.** Ten wrong passwords for one email address within 15 minutes stop sign-in for that address until the 15 minutes are up. This happens whether or not the address has an account, so it says nothing about which ones do. Ten wrong codes at the second step lock that step for 15 minutes in the same way.- **The site audit trail** (Settings, Organization, Sign-in security) records each sign-in and failed sign-in with the address it came from, lockouts, sign-outs, password changes and resets, two-step sign-in being turned on, off or reset, new backup codes, and changes to settings, roles, the logo, the email domain, identity confirmations and signing locks. The rows form one hash chain, so a changed or removed row shows, and the trail downloads as CSV.+### Send the audit trail to your SIEM++Every row added to the site audit trail or to a document's audit trail is also written to the function logs, once it is saved, as one line of JSON. So are refused requests and failures worth a look. A Vercel log drain (team Settings, Drains, or an observability integration from the Vercel Marketplace such as Datadog, Axiom or Better Stack) then delivers them to your SIEM as fields it can search and alert on. Log drains are a paid Vercel feature; see Vercel's pricing page for which plans have them.++Each line has `"source": "signudoc"` and a `type`:++- `"audit"`: a copy of an audit row. `trail` is `site` or `envelope`, and the line carries `event`, `actorEmail`, `actorUserId`, `ipAddress`, `userAgent`, `metadata`, `envelopeId` (for a document), `occurredAt`, and the row's `sequence` and `rowHash`. The database stays the record: the hash matches a line to its row, and a gap in `sequence` shows a line that did not arrive. A change that fails and is rolled back writes no line.+- `"security"`: a `category` and `message`, with the request's path (signing and download links are redacted), IP address and user, where known.++`AUDIT_LOG=off` stops the audit lines, if you would rather not have email and IP addresses in your function logs. The trails in the database are the same either way.+### Single sign-onPeople can sign in through your organization's identity provider instead of with a password, over OpenID Connect. That puts your provider's own rules in charge: its MFA, its conditional access, and removing someone there removes them here at their next sign-in. It works with any provider that publishes `/.well-known/openid-configuration`, which includes Okta, Microsoft Entra ID, Google Workspace, OneLogin, JumpCloud, Keycloak and Auth0. It is optional and set up by hand, because the provider is outside Vercel.diff --git a/src/lib/db/connection.ts b/src/lib/db/connection.tsindex d2f29ba..ab10f62 100644--- a/src/lib/db/connection.ts+++ b/src/lib/db/connection.ts@@ -78,18 +78,52 @@ export function replaceDbPoolForTests(pool: Pool): Pool | null {return replaced;}+// Work to do once a transaction has committed, such as writing a log line+// about a row it inserted: a line about a row that was rolled back would+// describe something that never happened.+const commitCallbacks = new WeakMap<object, (() => void)[]>();++/**+ * Runs `callback` once the transaction `database` belongs to has committed,+ * or at once when `database` is not inside one. Dropped on rollback.+ */+export function afterCommit(database: DbExecutor, callback: () => void): void {+ const pending = commitCallbacks.get(database);++ if (pending) {+ pending.push(callback);+ return;+ }++ callback();+}+export async function withTransaction<T>(run: (client: PoolClient) => Promise<T>,pool: Pool = getDb(),): Promise<T> {const client = await pool.connect();+ const pending: (() => void)[] = [];++ commitCallbacks.set(client, pending);try {await client.query("BEGIN");const result = await run(client);await client.query("COMMIT");+ commitCallbacks.delete(client);++ for (const callback of pending) {+ try {+ callback();+ } catch (error) {+ console.error("[db] A step after commit failed:", error);+ }+ }+return result;} catch (error) {+ commitCallbacks.delete(client);await client.query("ROLLBACK");throw error;} finally {diff --git a/src/lib/security/audit-log.dbtest.ts b/src/lib/security/audit-log.dbtest.tsnew file mode 100644index 0000000..ae6933f--- /dev/null+++ b/src/lib/security/audit-log.dbtest.ts@@ -0,0 +1,96 @@+import assert from "node:assert/strict";+import { after, before, beforeEach, test } from "node:test";++import type pg from "pg";++import { withTransaction } from "../db/connection.ts";+import { openTestDatabase } from "../db/test-database.ts";+import { recordSystemAuditEvent } from "../services/system-audit.ts";++// Audit rows are copied to the function logs as JSON lines once they are+// committed, and only then (logging.ts). Run with `npm run test:db`.++let database: pg.Pool;++before(async () => {+ database = await openTestDatabase();+});++beforeEach(async () => {+ await database.query("delete from public.system_audit_events");+});++after(async () => {+ await database.query("delete from public.system_audit_events");+ await database.end();+});++function auditLines(calls: { arguments: unknown[] }[]) {+ return calls+ .map((call) => call.arguments[0])+ .filter((line): line is string => typeof line === "string")+ .map((line) => JSON.parse(line) as Record<string, unknown>)+ .filter((line) => line.type === "audit");+}++test("a committed audit row is written as one JSON line that matches the row", async (t) => {+ const info = t.mock.method(console, "info", () => undefined);+ const recorded = await recordSystemAuditEvent(+ {+ actorEmail: "[email protected]",+ actorUserId: "user-1",+ event: "sign_in_succeeded",+ ipAddress: "203.0.113.7",+ metadata: { method: "password" },+ },+ database,+ );+ const [line] = auditLines(info.mock.calls);+ const { rows } = await database.query<{ row_hash: string }>(+ "select row_hash from system_audit_events where id = $1",+ [recorded.id],+ );++ assert.equal(line?.source, "signudoc");+ assert.equal(line?.trail, "site");+ assert.equal(line?.event, "sign_in_succeeded");+ assert.equal(line?.actorEmail, "[email protected]");+ assert.equal(line?.ipAddress, "203.0.113.7");+ assert.equal(line?.sequence, recorded.sequence);+ assert.equal(line?.rowHash, rows[0]?.row_hash);+ assert.deepEqual(line?.metadata, { method: "password" });+});++test("a row that is rolled back is never logged", async (t) => {+ const info = t.mock.method(console, "info", () => undefined);++ await assert.rejects(+ withTransaction(async (client) => {+ await recordSystemAuditEvent(+ { actorEmail: "[email protected]", event: "settings_changed" },+ client,+ );++ assert.equal(auditLines(info.mock.calls).length, 0, "not before commit");+ throw new Error("the change failed");+ }, database),+ );++ assert.equal(auditLines(info.mock.calls).length, 0);+});++test("AUDIT_LOG=off stops the lines", async (t) => {+ const info = t.mock.method(console, "info", () => undefined);++ process.env.AUDIT_LOG = "off";+ t.after(() => {+ delete process.env.AUDIT_LOG;+ });++ await recordSystemAuditEvent(+ { actorEmail: "[email protected]", event: "settings_changed" },+ database,+ );++ assert.equal(auditLines(info.mock.calls).length, 0);+});diff --git a/src/lib/security/logging.ts b/src/lib/security/logging.tsindex 6cfa846..0731cc2 100644--- a/src/lib/security/logging.ts+++ b/src/lib/security/logging.ts@@ -1,3 +1,21 @@+// Security events and audit records as structured log lines.+//+// Each line is one JSON object, so a Vercel log drain (Settings, Drains in+// the Vercel team) hands them to Datadog, Splunk, Elastic, Axiom, Better+// Stack or any other SIEM as fields rather than text. Every line has+// "source": "signudoc" and a "type":+//+// - "security": something worth an operator's attention (a refused request,+// a failure), from logSecurityEvent.+// - "audit": a copy of a row just committed to one of the two audit trails,+// from logAuditRecord. "trail" is "site" (system_audit_events) or+// "envelope" (audit_events). The database rows stay the record; "sequence"+// and "rowHash" match a line to its row and show a gap in what arrived.+//+// AUDIT_LOG=off stops the audit lines, for an install that does not want+// email addresses and IP addresses in its function logs. Security lines+// are always written.+type SecurityLogLevel = "error" | "info" | "warn";type SecurityLogInput = {@@ -67,15 +85,87 @@ export function logSecurityEvent(input: SecurityLogInput,): void {const consoleMethod = getConsoleMethod(level);- const payload = {- category: input.category,- ipAddress: input.ipAddress ?? null,- metadata: input.metadata ?? null,- path: input.path ? redactSensitivePath(input.path) : null,- userId: input.userId ?? null,- };-- consoleMethod(`[security] ${input.message}`, payload);++ consoleMethod(+ toLogLine({+ category: input.category,+ ipAddress: input.ipAddress ?? null,+ level,+ message: input.message,+ metadata: input.metadata ?? null,+ path: input.path ? redactSensitivePath(input.path) : null,+ type: "security",+ userId: input.userId ?? null,+ }),+ );+}++export type AuditLogRecord = {+ actorEmail: string | null;+ /** "user" for the site trail; the envelope trail's actor type otherwise. */+ actorType?: string | null;+ actorUserId?: string | null;+ /** Seconds since the epoch, as stored. */+ createdAt: number;+ envelopeId?: string | null;+ event: string;+ id: string;+ ipAddress: string | null;+ metadata: unknown;+ rowHash: string | null;+ sequence: number | null;+ targetUserId?: string | null;+ trail: "envelope" | "site";+ userAgent: string | null;+};++export function isAuditLogEnabled(+ env: Record<string, string | undefined> = process.env,+): boolean {+ return env.AUDIT_LOG?.trim().toLowerCase() !== "off";+}++/** Writes one committed audit row as a log line. Never throws. */+export function logAuditRecord(record: AuditLogRecord): void {+ if (!isAuditLogEnabled()) {+ return;+ }++ try {+ console.info(+ toLogLine({+ actorEmail: record.actorEmail,+ actorType: record.actorType ?? null,+ actorUserId: record.actorUserId ?? null,+ envelopeId: record.envelopeId ?? null,+ event: record.event,+ id: record.id,+ ipAddress: record.ipAddress,+ level: "info",+ metadata: record.metadata ?? null,+ occurredAt: new Date(record.createdAt * 1000).toISOString(),+ rowHash: record.rowHash,+ sequence: record.sequence,+ targetUserId: record.targetUserId ?? null,+ trail: record.trail,+ type: "audit",+ userAgent: record.userAgent,+ }),+ );+ } catch {+ // A log line is a copy. Failing to write one must not fail the change.+ }+}++/** One JSON object on one line, with the fields every line shares. */+export function toLogLine(+ fields: Record<string, unknown> & { level: string; type: string },+): string {+ return JSON.stringify({+ source: "signudoc",+ time: new Date().toISOString(),+ ...fields,+ });}export function logRouteError(diff --git a/src/lib/services/audit.ts b/src/lib/services/audit.tsindex 69be673..ba46dc8 100644--- a/src/lib/services/audit.ts+++ b/src/lib/services/audit.ts@@ -5,11 +5,13 @@ import {type AuditEventRecord,} from "../schemas/envelope.ts";import {+ afterCommit,type DbExecutor,getDb,queryMany,withTransaction,} from "../db/connection.ts";+import { logAuditRecord } from "../security/logging.ts";import { canonicalJson } from "../utils/canonical-json.ts";export type AuditEventMetadata = Record<string, unknown> | null;@@ -218,6 +220,7 @@ async function insertChainedAuditEvent(sequence,userAgent: input.userAgent ?? null,};+ const rowHash = computeAuditRowHash(previousHash, fields);await database.query(`@@ -248,10 +251,14 @@ async function insertChainedAuditEvent(createdAt,sequence,previousHash,- computeAuditRowHash(previousHash, fields),+ rowHash,],);+ afterCommit(database, () => {+ logAuditRecord({ ...fields, rowHash, trail: "envelope" });+ });+return auditEventRecordSchema.parse({actorEmail: fields.actorEmail,actorType: input.actorType,diff --git a/src/lib/services/system-audit.ts b/src/lib/services/system-audit.tsindex e88d32f..a7e5783 100644--- a/src/lib/services/system-audit.ts+++ b/src/lib/services/system-audit.ts@@ -1,11 +1,13 @@import { createHash, randomUUID } from "node:crypto";import {+ afterCommit,type DbExecutor,getDb,queryMany,withTransaction,} from "../db/connection.ts";+import { logAuditRecord } from "../security/logging.ts";import { canonicalJson } from "../utils/canonical-json.ts";// The install's own audit trail: changes that are not about one envelope,@@ -119,6 +121,7 @@ async function insertChained(userAgent: input.userAgent ?? null,};const previousHash = previousRow?.rowHash ?? null;+ const rowHash = computeSystemAuditRowHash(previousHash, fields);await database.query(`@@ -139,10 +142,19 @@ async function insertChained(fields.metadata,fields.createdAt,previousHash,- computeSystemAuditRowHash(previousHash, fields),+ rowHash,],);+ afterCommit(database, () => {+ logAuditRecord({+ ...fields,+ actorType: "user",+ rowHash,+ trail: "site",+ });+ });+return fields;}