@happyvertical/smrt-secrets

中文文档
0.62.1发布于 2026/11/17MITTypeScriptES Module近 30 天下载 2.3万

Per-tenant secret management with envelope encryption for SMRT

原始使用文档
文档目录16 节
  1. Installation
  2. Usage
  3. Encryption chain
  4. Master key from a provider
  5. Key rotation
  6. Drift diagnosis and repair
  7. Audit logging
  8. Security model
  9. API
  10. Models
  11. Collections
  12. Services
  13. Functions
  14. Error Classes (re-exported from @happyvertical/secrets )
  15. Key Types
  16. Dependencies

@happyvertical/smrt-secrets

Per-tenant secret management with envelope encryption for the s-m-r-t framework. Uses a three-layer encryption chain: Application Master Key (AMK) wraps per-tenant Data Encryption Keys (TDEK), which encrypt individual secret values.

Installation

pnpm add @happyvertical/smrt-secrets

Requires the SMRT_SECRET_MASTER_KEY environment variable (64 hex characters) as the AMK, or a masterKeyProvider (below) where the process has no environment to read it from.

Usage

import { SecretService } from '@happyvertical/smrt-secrets';
import { withTenant } from '@happyvertical/smrt-tenancy';

// Create the service (reads AMK from env by default)
const service = await SecretService.create({ db });

await withTenant({ tenantId: 'tenant-123' }, async () => {
  // Store a secret (upserts if name already exists)
  await service.store('stripe-api-key', 'sk_live_xxx', {
    category: 'api-keys',
    description: 'Stripe production key',
    expiresAt: new Date('2027-01-01'),
  });

  // Retrieve and decrypt
  const { value, accessCount } = await service.retrieve('stripe-api-key');

  // List secret names (values never included)
  const secrets = await service.list({ category: 'api-keys' });

  // Disable/enable without deleting
  await service.disable('stripe-api-key');
  await service.enable('stripe-api-key');

  // Rotate the tenant's encryption key
  await service.rotateKey();
  // Re-encrypt all secrets with the new key (separate step)
  await service.reencryptAll();

  // Query audit logs
  const logs = await service.getAuditLogs({ secretName: 'stripe-api-key' });

  // Diagnose tenant secret/key drift without exposing values
  const drift = await service.diagnoseTenantSecretKeyDrift('tenant-123');

  // Preview and then explicitly repair unrecoverable drifted rows
  await service.repairTenantSecretKeyDrift('tenant-123', { dryRun: true });
  await service.repairTenantSecretKeyDrift('tenant-123', {
    confirmDeleteUnrecoverableData: true,
  });

  // Hard delete
  await service.delete('stripe-api-key');
});

Encryption chain

AMK (env var, 256-bit)
  └─ wraps TDEK (per-tenant, auto-generated)
       └─ encrypts secret value (stored as JSON envelope)

The AMK is loaded from SMRT_SECRET_MASTER_KEY (configurable via amkEnvVar option). The environment variable always wins. Each tenant gets its own TDEK on first secret storage. TDEKs are stored in wrapped form -- they can only be unwrapped using the AMK. Secret values are encrypted by the unwrapped TDEK and persisted as EncryptedEnvelope JSON.

Master key from a provider

A local or desktop app has no environment to carry the AMK. Pass masterKeyProvider (an async function returning 64 hex characters or the 32 raw bytes) and the service asks it only when the environment variable is unset. There is no default key: with neither source, creation fails with the usual Application Master Key not found error, and a provider that returns null does the same. The provided key is never logged and never appears in an error. In an app on @happyvertical/smrt-app-runtime's local profile, pass runtime.secretMasterKey() (see that package's README); the runtime creates and keeps the key so the user never sees it.

const secrets = await SecretService.create({
  db,
  masterKeyProvider: () => runtime.secretMasterKey(),
});

Key rotation

rotateKey() creates a new TDEK version and retires the old one. Existing secrets remain readable because retired keys are kept for decryption. Call reencryptAll() separately after rotation to re-encrypt all secrets with the new key. The method returns { success, failed } counts.

TenantKey statuses: active (current encryption key), rotating (transitional), retired (kept for decryption), compromised (should not be used).

Drift diagnosis and repair

diagnoseTenantSecretKeyDrift(tenantId) reports tenant secret/key drift without returning secret values. It checks active secrets rows, lower-level tenant_encryption_keys rows used by @happyvertical/secrets, and s-m-r-t-visible tenant_keys rows so operators can distinguish missing secrets from stale or unusable key material.

repairTenantSecretKeyDrift(tenantId, { dryRun: true }) previews rows that would be deleted. A destructive repair requires confirmDeleteUnrecoverableData: true; it deletes only encrypted secret/key rows identified as unrecoverable with the currently configured AMK. After repair, store fresh secret values with storeForTenant() or store().

Audit logging

Every secret operation (create, read, update, delete, rotate_key, disable, enable) is logged to SecretAuditLog with user ID, action, result (success/failure/denied), and optional IP/user-agent. Audit logging is enabled by default; failures are logged to console rather than thrown so they do not block secret operations.

Security model

The Secret and TenantKey models have no API or MCP exposure to prevent accidental leakage. CLI access is limited to listing names. The TenantKey model is deliberately not tenant-scoped -- it tracks keys FOR tenants rather than being owned BY them.

API

Models

ExportDescription
SecretEncrypted secret record with status, expiration, and access tracking
SecretAuditLogImmutable audit trail for all secret operations
TenantKeyPer-tenant data encryption key in wrapped form

Collections

ExportDescription
SecretCollectionSecret queries with tenant filtering and category support
SecretAuditLogCollectionAudit log queries with filtering and pagination
TenantKeyCollectionKey management including retired key cleanup

Services

ExportDescription
SecretServiceHigh-level API: store, retrieve, rotate, delete, audit, diagnose and repair key drift

Functions

ExportDescription
createAuditEntryBuild an audit log entry for a secret operation

Error Classes (re-exported from @happyvertical/secrets)

SecretError, AMKUnavailableError, DecryptionError, EncryptionError, InvalidKeyFormatError, KeyNotFoundError, KeyRotationError, StoreNotInitializedError, TenantKeyMissingError

Key Types

SecretServiceOptions, SecretMasterKeyProvider, StoreSecretOptions, RetrievedSecret, DiagnoseTenantSecretKeyDriftOptions, SecretKeyDriftReport, SecretKeyDriftIssue, RepairTenantSecretKeyDriftOptions, SecretKeyDriftRepairResult, ListSecretsOptions, ListAuditLogsOptions, SecretStatus, SecretAuditAction, SecretAuditResult, TenantKeyStatus, ApplicationMasterKey, EncryptedEnvelope, TenantDataEncryptionKey, SecretStore

Dependencies

  • @happyvertical/smrt-core -- ORM and code generation
  • @happyvertical/smrt-tenancy -- tenant context for scoped operations
  • @happyvertical/secrets -- envelope encryption primitives
  • @happyvertical/sql -- database interface
  • @happyvertical/utils -- shared utilities

版本与发布记录

@happyvertical/smrt-secrets 共发布 365 个版本,首次发布于 2026/06/23;过去 12 个月发布了 365 个版本。

版本发布日期距今
0.62.1latest2026/11/17今天
0.62.02026/11/17今天
0.61.62026/11/161 天前
0.61.52026/11/161 天前
0.61.42026/11/161 天前
0.61.32026/11/152 天前

关于 @happyvertical/smrt-secrets 的常见问题

@happyvertical/smrt-secrets 是什么?

Per-tenant secret management with envelope encryption for SMRT

如何安装 @happyvertical/smrt-secrets?

在项目目录运行 npm install @happyvertical/smrt-secrets,或使用 pnpm add / yarn add / bun add。

@happyvertical/smrt-secrets 支持 TypeScript 吗?

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

@happyvertical/smrt-secrets 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@happyvertical/smrt-secrets 可以商用吗?

@happyvertical/smrt-secrets 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@happyvertical/smrt-secrets 的下载量有多少?

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

@happyvertical/smrt-secrets 还在维护吗?

最新版本 0.62.1 发布于 2026/11/17(今天);至今共发布 365 个版本,其中过去 12 个月发布了 365 个;首次发布于 2026/06/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。