# @geekmidas/audit 中文文档

规范地址：https://npmcn.com/package/%40geekmidas/audit/

版本：9\.6\.1
npm 元数据更新时间：2026-11-16T09:28:02.136Z
中文译文更新时间：2026-11-16T09:37:06.642Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40geekmidas/audit
原文对照：https://npmcn.com/package/%40geekmidas/audit/?lang=original
项目主页：https://github.com/geekmidas/toolbox#readme
源码仓库：https://github.com/geekmidas/toolbox

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：423 kB，89 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：knex \>=3\.0\.0 \<4\.0\.0，kysely \>=0\.28\.2 \<0\.30\.0，@geekmidas/cache ^9\.6\.1，@geekmidas/schema ^9\.6\.1
- 首次发布：2025-12-08T12:07:08.133Z
- 最新版本发布：2026-11-16T09:28:01.489Z
- 近 30 天下载量：13398（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：210（近 12 个月 210 个）

## 中文简介

> 类型安全审计记录与数据库整合,以跟踪应用程序事件和用户行动

## 安装

```sh
npm install @geekmidas/audit
```

也可以使用：`pnpm add @geekmidas/audit`、`yarn add @geekmidas/audit`、`bun add @geekmidas/audit`

## README

# @geekmidas/审计

> 类型安全审计记录与数据库整合,以跟踪应用程序事件和用户行动

## 概览

`@geekmidas/audit` 为在应用程序中记录和持续审计线索提供了一个全面的解决办法。 它支持类型安全的审计动作,交易写作,以及灵活的存储后端.

## 特征

-   **安全审计行动**: 为编译时间安全定义审计类型
-   **交易支持**: 在数据库交易中进行断层审计
-   **弹性存储**:可插件存储接口(Kysely, Knex, in- memory, 缓存)
-   **演员跟踪**: 记录执行每项行动的人(用户、服务、系统)
-   **丰富的元数据**: 附加请求上下文、实体引用和自定义数据
-   **查询支持**: 查询带有过滤器、页码和排序的审计日志

## 安装

```bash
npm install @geekmidas/audit
# or
pnpm add @geekmidas/audit
```

## 快速启动

### 1\. 界定你的审计行动

```typescript
import type { AuditableAction } from '@geekmidas/audit';

// Define type-safe audit actions
type AppAuditAction =
  | AuditableAction<'user.created', { userId: string; email: string }>
  | AuditableAction<'user.updated', { userId: string; changes: string[] }>
  | AuditableAction<'order.placed', { orderId: string; total: number }>;
```

### 2\. 设置存储

**促进发展/试验(记忆审计):**

```typescript
import { InMemoryAuditStorage } from '@geekmidas/audit/memory';

const storage = new InMemoryAuditStorage<AppAuditAction>();

// Query stored records
const records = await storage.query({ type: 'user.created' });

// Clear all records (useful in tests)
storage.clear();
```

**用于生产(Kysely AuditStorage):**

```typescript
import { KyselyAuditStorage } from '@geekmidas/audit/kysely';

// Define your database schema
interface Database {
  audit_logs: AuditLogTable;
  // ... other tables
}

const storage = new KyselyAuditStorage<Database>({
  db: kyselyDb,
  tableName: 'audit_logs',
});
```

**用于生产(KnexAuditStorage):**

```typescript
import { KnexAuditStorage } from '@geekmidas/audit/knex';

const storage = new KnexAuditStorage({
  db: knexDb,
  tableName: 'audit_logs',
});
```

### 3\. 设立审计人

```typescript
import { DefaultAuditor } from '@geekmidas/audit';

const auditor = new DefaultAuditor<AppAuditAction>({
  actor: { id: 'user-123', type: 'user' },
  storage,
  metadata: {
    requestId: 'req-456',
    endpoint: '/api/users',
  },
});
```

### 4\. 记录审计

```typescript
// Type-safe audit calls - TypeScript enforces correct payload shapes
auditor.audit('user.created', {
  userId: '789',
  email: 'test@example.com',
}); // OK

auditor.audit('user.created', {
  orderId: '123', // Type error - wrong payload shape
});

// Flush to storage
await auditor.flush();
```

## 交易审计

使用 `withAuditableTransaction` 以确保审计与数据库操作具有原子性:

```typescript
import { withAuditableTransaction } from '@geekmidas/audit/kysely';

const result = await withAuditableTransaction(
  db,
  auditor,
  async (trx) => {
    // Database operations
    const user = await trx
      .insertInto('users')
      .values({ name: 'John', email: 'john@example.com' })
      .returningAll()
      .executeTakeFirstOrThrow();

    // Audit is recorded
    auditor.audit('user.created', {
      userId: user.id,
      email: user.email,
    });

    return user;
  },
);
// Audits are automatically flushed before transaction commits
// If flush fails, the entire transaction rolls back
```

## API 参考

### 核心类型

#### `AuditableAction<TType, TPayload>`

定义具有类型和有效载荷的可审计动作:

```typescript
type UserAction = AuditableAction<'user.created', { userId: string }>;
```

#### `AuditRecord`

完成所有元数据的审计记录:

```typescript
interface AuditRecord<TPayload = unknown> {
  id: string;
  type: string;
  operation: AuditOperation;
  table?: string;
  entityId?: string | Record<string, unknown>;
  oldValues?: Record<string, unknown>;
  newValues?: Record<string, unknown>;
  payload?: TPayload;
  timestamp: Date;
  actor?: AuditActor;
  metadata?: AuditMetadata;
}
```

#### `AuditActor`

代表执行行动的人:

```typescript
interface AuditActor {
  id?: string;
  type?: string;
  [key: string]: unknown;
}
```

#### `AuditMetadata`

请求上下文和补充数据:

```typescript
interface AuditMetadata {
  requestId?: string;
  endpoint?: string;
  method?: string;
  ip?: string;
  userAgent?: string;
  [key: string]: unknown;
}
```

### `Auditor` 接口

```typescript
interface Auditor<TAuditAction, TTransaction> {
  readonly actor: AuditActor;

  // Type-safe audit recording
  audit<TType extends ExtractAuditType<TAuditAction>>(
    type: TType,
    payload: ExtractAuditPayload<TAuditAction, TType>,
    options?: AuditOptions,
  ): void;

  // Raw record insertion
  record(record: Omit<AuditRecord, 'id' | 'timestamp' | 'actor'>): void;

  // Get collected records
  getRecords(): AuditRecord[];

  // Flush to storage
  flush(trx?: TTransaction): Promise<void>;

  // Clear without flushing
  clear(): void;

  // Add metadata to future records
  addMetadata(metadata: AuditMetadata): void;

  // Transaction management
  setTransaction(trx: TTransaction): void;
  getTransaction(): TTransaction | undefined;
}
```

### `AuditStorage` 接口

为自定义存储后端执行此接口 :

```typescript
interface AuditStorage<TAuditAction> {
  // Required: Write records
  write(records: AuditRecord[], trx?: unknown): Promise<void>;

  // Optional: Query records
  query?(options: AuditQueryOptions): Promise<AuditRecord[]>;

  // Optional: Count records
  count?(options: Omit<AuditQueryOptions, 'limit' | 'offset'>): Promise<number>;

  // Optional: Get database for transactions
  getDatabase?(): unknown;
}
```

### `KyselyAuditStorage`

已建 Kysely 存储执行 :

```typescript
const storage = new KyselyAuditStorage({
  db: kyselyDb,
  tableName: 'audit_logs',
  databaseServiceName: 'database', // Optional: for automatic transaction injection
  autoId: false, // Optional: let database generate IDs
});

// Query audits
const audits = await storage.query({
  type: 'user.created',
  actorId: 'user-123',
  from: new Date('2024-01-01'),
  limit: 100,
  orderBy: 'timestamp',
  orderDirection: 'desc',
});

// Count audits
const count = await storage.count({
  type: ['user.created', 'user.updated'],
  actorId: 'user-123',
});
```

### `KnexAuditStorage`

已建成的克能斯仓储实施. 镜子 `KyselyAuditStorage` - 一样 配置, 不变 `query()`编号 :`count()` 过滤器, 相同的交易语义 :

```typescript
import { KnexAuditStorage } from '@geekmidas/audit/knex';

const storage = new KnexAuditStorage({
  db: knexDb,
  tableName: 'audit_logs',
  databaseServiceName: 'database', // Optional: for automatic transaction injection
  autoId: false, // Optional: let database generate IDs
});

const audits = await storage.query({
  type: 'user.created',
  actorId: 'user-123',
  from: new Date('2024-01-01'),
  limit: 100,
  orderBy: 'timestamp',
  orderDirection: 'desc',
});

const count = await storage.count({
  type: ['user.created', 'user.updated'],
  actorId: 'user-123',
});
```

列名为骆驼Case,匹配克赛利存储. 如果您的数据库使用 蛇行 case 列, 用大小写映射器配置 Knex :

```typescript
import { knexSnakeCaseMappers } from 'objection';

const knexDb = knex({
  client: 'pg',
  connection: process.env.DATABASE_URL,
  ...knexSnakeCaseMappers(),
});
```

交易与Kysely存储相同:

```typescript
import { withAuditableTransaction } from '@geekmidas/audit/knex';

const user = await withAuditableTransaction(knexDb, auditor, async (trx) => {
  const [user] = await trx('users').insert(data).returning('*');

  auditor.audit('user.created', { userId: user.id, email: user.email });

  return user;
});
// Audits are flushed inside the transaction, before it commits
```

通过交易作为第一个参数 重用它而不是打开一个 保存点,所以审计会随着外部交易而回滚.

### `InMemoryAuditStorage`

方便包装 `CacheAuditStorage` 与 `InMemoryCache`用于测试和开发:

```typescript
import { InMemoryAuditStorage } from '@geekmidas/audit/memory';

const storage = new InMemoryAuditStorage<AppAuditAction>();

// Query audits (same API as other storages)
const audits = await storage.query({
  type: 'user.created',
  limit: 10,
});

// Get all records (for assertions in tests)
const allRecords = await storage.getRecords();

// Clear all records (reset for next test)
await storage.clear();
```

### `CacheAuditStorage`

基于缓存的存储使用任意 `@geekmidas/cache` 执行:

```typescript
import { CacheAuditStorage } from '@geekmidas/audit/cache';
import { InMemoryCache } from '@geekmidas/cache/memory';
import { UpstashCache } from '@geekmidas/cache/upstash';

// With in-memory cache (development/testing)
const storage = new CacheAuditStorage({
  cache: new InMemoryCache(),
  ttl: 86400, // 24 hours
});

// With Upstash Redis (production - distributed systems)
const storage = new CacheAuditStorage({
  cache: new UpstashCache({
    url: process.env.UPSTASH_REDIS_URL,
    token: process.env.UPSTASH_REDIS_TOKEN,
  }),
  prefix: 'audit', // Optional key prefix
  ttl: 604800, // 7 days
});

// Query and count work the same as other storages
const audits = await storage.query({ type: 'user.created' });
const count = await storage.count({ actorId: 'user-123' });

// Clear all records
await storage.clear();
```

## 数据库Schema

创建一个 `audit_logs` 表格显示 `KyselyAuditStorage` 或者说 `KnexAuditStorage`数字 :

```sql
CREATE TABLE audit_logs (
  id VARCHAR(21) PRIMARY KEY,  -- or use gen_random_uuid() with autoId: true
  type VARCHAR(255) NOT NULL,
  operation VARCHAR(20) NOT NULL,
  "table" VARCHAR(255),
  "entityId" VARCHAR(255),
  "oldValues" JSONB,
  "newValues" JSONB,
  payload JSONB,
  timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  "actorId" VARCHAR(255),
  "actorType" VARCHAR(50),
  "actorData" JSONB,
  metadata JSONB
);

-- Recommended indexes
CREATE INDEX idx_audit_logs_type ON audit_logs(type);
CREATE INDEX idx_audit_logs_timestamp ON audit_logs(timestamp);
CREATE INDEX idx_audit_logs_actor_id ON audit_logs("actorId");
CREATE INDEX idx_audit_logs_entity_id ON audit_logs("entityId");
```

## 与 @geekmidas/ 构建

审计包与 `@geekmidas/constructs` 结束点 :

```typescript
import { e } from '@geekmidas/constructs/endpoints';

const endpoint = e
  .post('/users')
  .body(UserSchema)
  .output(UserResponseSchema)
  .audit([
    {
      type: 'user.created',
      payload: (response) => ({
        userId: response.id,
        email: response.email,
      }),
    },
  ])
  .handle(async ({ body, auditor }) => {
    // Audits are automatically recorded and flushed
    return { id: '123', ...body };
  });
```

## 最佳做法

1.  **预先界定所有审计行动**: 为您的应用程序创建所有可能的审计行动的联盟类型
2.  **使用交易**: 汇总数据库操作和交易审计,以确保一致性
3.  **包含实体引用**: 使用 `entityId` 财务报告和审定财务报表 `table` 选项以方便查询
4.  **添加请求上下文**: 在元数据中包含请求的ID,端点和IP
5.  **使用有意义的类型**: 名称具有域名背景的审计类型(例如, `order.shipped` 没有 `update`(中文(简体) )

## 许可证

麻省理工学院

## 常见问题

### @geekmidas/audit 是什么？

类型安全审计记录与数据库整合,以跟踪应用程序事件和用户行动

### 如何安装 @geekmidas/audit？

在项目目录运行 npm install @geekmidas/audit，或使用 pnpm add / yarn add / bun add。

### @geekmidas/audit 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @geekmidas/audit 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @geekmidas/audit 可以商用吗？

@geekmidas/audit 使用 未声明 许可。package\.json 没有声明许可证。没有许可证的代码默认保留全部权利，商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括，不构成法律意见，请以许可原文为准。

### @geekmidas/audit 的下载量有多少？

根据 npm 官方下载统计，@geekmidas/audit 在 2026/10/16 – 2026/11/14 这 30 天内被下载 13,398 次，日均约 447 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @geekmidas/audit 还在维护吗？

最新版本 9\.6\.1 发布于 2026/11/16（今天）；至今共发布 210 个版本，其中过去 12 个月发布了 210 个；首次发布于 2025/12/08。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

