@axiom-lattice/pg-stores 1.0.13 → 1.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
 
2
- > @axiom-lattice/pg-stores@1.0.13 build /home/runner/work/agentic/agentic/packages/pg-stores
2
+ > @axiom-lattice/pg-stores@1.0.14 build /home/runner/work/agentic/agentic/packages/pg-stores
3
3
  > tsup src/index.ts --format cjs,esm --dts --sourcemap
4
4
 
5
5
  CLI Building entry: src/index.ts
@@ -8,13 +8,13 @@
8
8
  CLI Target: es2020
9
9
  CJS Build start
10
10
  ESM Build start
11
- ESM dist/index.mjs 43.66 KB
12
- ESM dist/index.mjs.map 81.24 KB
13
- ESM ⚡️ Build success in 191ms
14
- CJS dist/index.js 45.25 KB
15
- CJS dist/index.js.map 82.54 KB
16
- CJS ⚡️ Build success in 193ms
11
+ CJS dist/index.js 66.95 KB
12
+ CJS dist/index.js.map 124.96 KB
13
+ CJS ⚡️ Build success in 229ms
14
+ ESM dist/index.mjs 64.94 KB
15
+ ESM dist/index.mjs.map 122.78 KB
16
+ ESM ⚡️ Build success in 231ms
17
17
  DTS Build start
18
- DTS ⚡️ Build success in 7129ms
19
- DTS dist/index.d.ts 11.40 KB
20
- DTS dist/index.d.mts 11.40 KB
18
+ DTS ⚡️ Build success in 10174ms
19
+ DTS dist/index.d.ts 18.81 KB
20
+ DTS dist/index.d.mts 18.81 KB
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @axiom-lattice/pg-stores
2
2
 
3
+ ## 1.0.14
4
+
5
+ ### Patch Changes
6
+
7
+ - faf1bad: update team and more
8
+ - Updated dependencies [faf1bad]
9
+ - @axiom-lattice/core@2.1.24
10
+ - @axiom-lattice/protocols@2.1.14
11
+
3
12
  ## 1.0.13
4
13
 
5
14
  ### Patch Changes
@@ -0,0 +1,217 @@
1
+ # DatabaseConfigStore 实现说明
2
+
3
+ ## 概述
4
+
5
+ `DatabaseConfigStore` 是用于存储和管理数据库连接配置的持久化存储方案,支持多租户隔离和密码自动加密。
6
+
7
+ ## 特性
8
+
9
+ - ✅ **多租户隔离**: 基于 `tenant_id` 字段实现租户级别的数据隔离
10
+ - ✅ **密码加密存储**: 使用 AES-256-GCM 自动加密数据库密码
11
+ - ✅ **自动解密**: 读取配置时自动解密密码,调用方透明
12
+ - ✅ **两种存储实现**: InMemory(开发)和 PostgreSQL(生产)
13
+ - ✅ **集成 SqlDatabaseManager**: 可直接从 Store 加载配置到连接管理器
14
+
15
+ ## 快速开始
16
+
17
+ ### 1. 使用 InMemory 存储(默认)
18
+
19
+ ```typescript
20
+ import { storeLatticeManager } from '@axiom-lattice/core';
21
+ import type { DatabaseConfig } from '@axiom-lattice/protocols';
22
+
23
+ // 获取默认的 InMemory Store
24
+ const store = await storeLatticeManager.getStoreLattice('default', 'database').store;
25
+
26
+ // 创建配置
27
+ await store.createConfig('tenant-1', 'config-1', {
28
+ key: 'main-db',
29
+ config: {
30
+ type: 'postgres',
31
+ host: 'localhost',
32
+ port: 5432,
33
+ database: 'mydb',
34
+ user: 'admin',
35
+ password: 'secret',
36
+ },
37
+ name: 'Main Database',
38
+ });
39
+
40
+ // 获取配置
41
+ const config = await store.getConfigByKey('tenant-1', 'main-db');
42
+ console.log(config?.config.password); // 密码已自动解密
43
+ ```
44
+
45
+ ### 2. 使用 PostgreSQL 存储
46
+
47
+ ```typescript
48
+ import { PostgreSQLDatabaseConfigStore } from '@axiom-lattice/pg-stores';
49
+
50
+ const pgStore = new PostgreSQLDatabaseConfigStore({
51
+ poolConfig: process.env.DATABASE_URL,
52
+ autoMigrate: true,
53
+ });
54
+
55
+ // 使用方式与 InMemory 相同
56
+ await pgStore.createConfig('tenant-1', 'config-1', {
57
+ key: 'main-db',
58
+ config: { /* ... */ },
59
+ });
60
+ ```
61
+
62
+ ### 3. 集成到 SqlDatabaseManager
63
+
64
+ ```typescript
65
+ import { sqlDatabaseManager } from '@axiom-lattice/core';
66
+
67
+ // 从 Store 加载所有配置并注册
68
+ await sqlDatabaseManager.loadConfigsFromStore(store, 'tenant-1');
69
+
70
+ // 现在可以使用注册的数据库
71
+ const db = sqlDatabaseManager.getDatabase('main-db');
72
+ const tables = await db.listTables();
73
+ ```
74
+
75
+ ## 环境变量
76
+
77
+ ### LATTICE_ENCRYPTION_KEY(推荐设置)
78
+
79
+ 用于加密敏感数据的全局密钥。
80
+
81
+ ```bash
82
+ # .env 文件
83
+ LATTICE_ENCRYPTION_KEY="your-secret-key-at-least-32-characters-long"
84
+ ```
85
+
86
+ **注意**:
87
+ - 未设置时使用默认密钥(会输出警告)
88
+ - 生产环境**必须**设置此变量
89
+ - 密钥丢失将导致无法解密已存储的密码
90
+
91
+ ## 表结构
92
+
93
+ PostgreSQL 实现会创建以下表:
94
+
95
+ ```sql
96
+ CREATE TABLE lattice_database_configs (
97
+ id VARCHAR(255) NOT NULL,
98
+ tenant_id VARCHAR(255) NOT NULL,
99
+ key VARCHAR(255) NOT NULL,
100
+ name VARCHAR(255),
101
+ description TEXT,
102
+ config JSONB NOT NULL, -- 密码字段加密存储
103
+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
104
+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
105
+
106
+ PRIMARY KEY (tenant_id, id),
107
+ CONSTRAINT uk_lattice_database_configs_tenant_key UNIQUE (tenant_id, key)
108
+ );
109
+ ```
110
+
111
+ ## 核心接口
112
+
113
+ ### DatabaseConfigEntry
114
+
115
+ ```typescript
116
+ interface DatabaseConfigEntry {
117
+ id: string;
118
+ tenantId: string;
119
+ key: string;
120
+ config: DatabaseConfig; // 密码已解密
121
+ name?: string;
122
+ description?: string;
123
+ createdAt: Date;
124
+ updatedAt: Date;
125
+ }
126
+ ```
127
+
128
+ ### DatabaseConfigStore
129
+
130
+ ```typescript
131
+ interface DatabaseConfigStore {
132
+ getAllConfigs(tenantId: string): Promise<DatabaseConfigEntry[]>;
133
+ getConfigById(tenantId: string, id: string): Promise<DatabaseConfigEntry | null>;
134
+ getConfigByKey(tenantId: string, key: string): Promise<DatabaseConfigEntry | null>;
135
+ createConfig(tenantId: string, id: string, data: CreateDatabaseConfigRequest): Promise<DatabaseConfigEntry>;
136
+ updateConfig(tenantId: string, id: string, updates: Partial<UpdateDatabaseConfigRequest>): Promise<DatabaseConfigEntry | null>;
137
+ deleteConfig(tenantId: string, id: string): Promise<boolean>;
138
+ hasConfig(tenantId: string, id: string): Promise<boolean>;
139
+ }
140
+ ```
141
+
142
+ ## 加密方案
143
+
144
+ - **算法**: AES-256-GCM
145
+ - **密钥派生**: PBKDF2 (100,000 次迭代)
146
+ - **存储格式**: `salt:iv:ciphertext:authTag` (Base64 编码)
147
+ - **解密时机**: Store 层 `getConfig*()` 方法返回时自动解密
148
+
149
+ ## 最佳实践
150
+
151
+ ### 1. 生产环境配置
152
+
153
+ ```typescript
154
+ // 使用 PostgreSQL Store
155
+ const store = new PostgreSQLDatabaseConfigStore({
156
+ poolConfig: process.env.DATABASE_URL,
157
+ autoMigrate: true,
158
+ });
159
+
160
+ // 确保设置了加密密钥
161
+ if (!process.env.LATTICE_ENCRYPTION_KEY) {
162
+ throw new Error('LATTICE_ENCRYPTION_KEY must be set in production');
163
+ }
164
+ ```
165
+
166
+ ### 2. 应用启动时加载配置
167
+
168
+ ```typescript
169
+ async function initializeApp() {
170
+ const store = new PostgreSQLDatabaseConfigStore({ /* ... */ });
171
+
172
+ // 加载所有租户的数据库配置
173
+ const tenants = ['tenant-1', 'tenant-2'];
174
+ for (const tenantId of tenants) {
175
+ await sqlDatabaseManager.loadConfigsFromStore(store, tenantId);
176
+ }
177
+ }
178
+ ```
179
+
180
+ ### 3. 密钥管理
181
+
182
+ ```bash
183
+ # 生成安全密钥 (推荐)
184
+ openssl rand -base64 32
185
+
186
+ # 或使用 Node.js
187
+ node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
188
+ ```
189
+
190
+ ## 示例代码
191
+
192
+ 查看完整示例:`packages/pg-stores/examples/database-config-store.example.ts`
193
+
194
+ ## 文件结构
195
+
196
+ ```
197
+ packages/
198
+ ├── protocols/src/
199
+ │ └── DatabaseConfigStoreProtocol.ts # 协议接口定义
200
+ ├── core/src/
201
+ │ ├── util/encryption.ts # 通用加密工具
202
+ │ └── store_lattice/
203
+ │ ├── StoreLatticeManager.ts # Store 管理器(已添加 database 类型)
204
+ │ └── InMemoryDatabaseConfigStore.ts # InMemory 实现
205
+ └── pg-stores/src/
206
+ ├── stores/
207
+ │ └── PostgreSQLDatabaseConfigStore.ts # PostgreSQL 实现
208
+ └── migrations/
209
+ └── database_config_migrations.ts # 数据库迁移
210
+ ```
211
+
212
+ ## 注意事项
213
+
214
+ 1. **密码解密**: Store 层返回的配置中密码已解密,请妥善保管
215
+ 2. **多租户**: 所有操作都需要传入 `tenantId` 参数
216
+ 3. **唯一性**: `(tenant_id, key)` 组合必须唯一
217
+ 4. **加密密钥**: 生产环境务必设置 `LATTICE_ENCRYPTION_KEY`
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { PoolConfig, PoolClient, Pool } from 'pg';
2
- import { ThreadStore, Thread, CreateThreadRequest, AssistantStore, Assistant, CreateAssistantRequest, ScheduleStorage, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, SkillStore, Skill, CreateSkillRequest } from '@axiom-lattice/protocols';
3
- export { Assistant, AssistantStore, CreateAssistantRequest, CreateSkillRequest, CreateThreadRequest, ScheduleExecutionType, ScheduleStorage, ScheduledTaskDefinition, ScheduledTaskStatus, Skill, SkillStore, Thread, ThreadStore } from '@axiom-lattice/protocols';
2
+ import { ThreadStore, Thread, CreateThreadRequest, AssistantStore, Assistant, CreateAssistantRequest, ScheduleStorage, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, SkillStore, Skill, CreateSkillRequest, DatabaseConfigStore, DatabaseConfigEntry, CreateDatabaseConfigRequest, UpdateDatabaseConfigRequest, WorkspaceStore, Workspace, CreateWorkspaceRequest, UpdateWorkspaceRequest, ProjectStore, Project, CreateProjectRequest, UpdateProjectRequest } from '@axiom-lattice/protocols';
3
+ export { Assistant, AssistantStore, CreateAssistantRequest, CreateDatabaseConfigRequest, CreateProjectRequest, CreateSkillRequest, CreateThreadRequest, CreateWorkspaceRequest, DatabaseConfig, DatabaseConfigEntry, DatabaseConfigStore, DatabaseType, Project, ProjectStore, ScheduleExecutionType, ScheduleStorage, ScheduledTaskDefinition, ScheduledTaskStatus, Skill, SkillStore, StorageType, Thread, ThreadStore, UpdateDatabaseConfigRequest, UpdateProjectRequest, UpdateWorkspaceRequest, Workspace, WorkspaceStore } from '@axiom-lattice/protocols';
4
4
 
5
5
  /**
6
6
  * PostgreSQL implementation of ThreadStore
@@ -347,6 +347,229 @@ declare class PostgreSQLSkillStore implements SkillStore {
347
347
  getSubSkills(parentSkillName: string): Promise<Skill[]>;
348
348
  }
349
349
 
350
+ /**
351
+ * PostgreSQL implementation of DatabaseConfigStore
352
+ */
353
+
354
+ /**
355
+ * PostgreSQL DatabaseConfigStore options
356
+ */
357
+ interface PostgreSQLDatabaseConfigStoreOptions {
358
+ /**
359
+ * PostgreSQL connection pool configuration
360
+ * Can be a connection string or PoolConfig object
361
+ */
362
+ poolConfig: string | PoolConfig;
363
+ /**
364
+ * Whether to run migrations automatically on initialization
365
+ * @default true
366
+ */
367
+ autoMigrate?: boolean;
368
+ }
369
+ /**
370
+ * PostgreSQL implementation of DatabaseConfigStore
371
+ *
372
+ * Features:
373
+ * - Multi-tenant isolation via tenant_id
374
+ * - Automatic password encryption/decryption
375
+ * - Unique constraint on (tenant_id, key)
376
+ */
377
+ declare class PostgreSQLDatabaseConfigStore implements DatabaseConfigStore {
378
+ private pool;
379
+ private migrationManager;
380
+ private initialized;
381
+ private initPromise;
382
+ constructor(options: PostgreSQLDatabaseConfigStoreOptions);
383
+ /**
384
+ * Initialize the store and run migrations
385
+ * Uses a promise-based lock to prevent concurrent initialization
386
+ */
387
+ initialize(): Promise<void>;
388
+ /**
389
+ * Get all database configurations for a tenant
390
+ */
391
+ getAllConfigs(tenantId: string): Promise<DatabaseConfigEntry[]>;
392
+ /**
393
+ * Get all database configurations across all tenants
394
+ */
395
+ getAllConfigsWithoutTenant(): Promise<DatabaseConfigEntry[]>;
396
+ /**
397
+ * Get database configuration by ID
398
+ */
399
+ getConfigById(tenantId: string, id: string): Promise<DatabaseConfigEntry | null>;
400
+ /**
401
+ * Get database configuration by business key
402
+ */
403
+ getConfigByKey(tenantId: string, key: string): Promise<DatabaseConfigEntry | null>;
404
+ /**
405
+ * Create a new database configuration
406
+ */
407
+ createConfig(tenantId: string, id: string, data: CreateDatabaseConfigRequest): Promise<DatabaseConfigEntry>;
408
+ /**
409
+ * Update an existing database configuration
410
+ */
411
+ updateConfig(tenantId: string, id: string, updates: Partial<UpdateDatabaseConfigRequest>): Promise<DatabaseConfigEntry | null>;
412
+ /**
413
+ * Delete a database configuration by ID
414
+ */
415
+ deleteConfig(tenantId: string, id: string): Promise<boolean>;
416
+ /**
417
+ * Check if configuration exists
418
+ */
419
+ hasConfig(tenantId: string, id: string): Promise<boolean>;
420
+ /**
421
+ * Dispose resources and close the connection pool
422
+ */
423
+ dispose(): Promise<void>;
424
+ /**
425
+ * Ensure store is initialized
426
+ */
427
+ private ensureInitialized;
428
+ /**
429
+ * Map database row to DatabaseConfigEntry object
430
+ * Automatically decrypts password if present
431
+ */
432
+ private mapRowToEntry;
433
+ /**
434
+ * Encrypt password in config before storing
435
+ */
436
+ private encryptPasswordInConfig;
437
+ }
438
+
439
+ /**
440
+ * PostgreSQL implementation of WorkspaceStore
441
+ */
442
+
443
+ /**
444
+ * PostgreSQL WorkspaceStore options
445
+ */
446
+ interface PostgreSQLWorkspaceStoreOptions {
447
+ /**
448
+ * PostgreSQL connection pool configuration
449
+ * Can be a connection string or PoolConfig object
450
+ */
451
+ poolConfig: string | PoolConfig;
452
+ /**
453
+ * Whether to run migrations automatically on initialization
454
+ * @default true
455
+ */
456
+ autoMigrate?: boolean;
457
+ }
458
+ /**
459
+ * PostgreSQL implementation of WorkspaceStore
460
+ */
461
+ declare class PostgreSQLWorkspaceStore implements WorkspaceStore {
462
+ private pool;
463
+ private migrationManager;
464
+ private initialized;
465
+ private ownsPool;
466
+ constructor(options: PostgreSQLWorkspaceStoreOptions);
467
+ /**
468
+ * Dispose resources and close the connection pool
469
+ * Should be called when the store is no longer needed
470
+ */
471
+ dispose(): Promise<void>;
472
+ /**
473
+ * Initialize the store and run migrations
474
+ */
475
+ initialize(): Promise<void>;
476
+ /**
477
+ * Ensure store is initialized
478
+ */
479
+ private ensureInitialized;
480
+ /**
481
+ * Map database row to Workspace object
482
+ */
483
+ private mapRowToWorkspace;
484
+ /**
485
+ * Get all workspaces for a tenant
486
+ */
487
+ getAllWorkspaces(tenantId: string): Promise<Workspace[]>;
488
+ /**
489
+ * Get a workspace by ID for a specific tenant
490
+ */
491
+ getWorkspaceById(tenantId: string, id: string): Promise<Workspace | null>;
492
+ /**
493
+ * Create a new workspace
494
+ */
495
+ createWorkspace(tenantId: string, id: string, data: CreateWorkspaceRequest): Promise<Workspace>;
496
+ /**
497
+ * Update an existing workspace
498
+ */
499
+ updateWorkspace(tenantId: string, id: string, updates: UpdateWorkspaceRequest): Promise<Workspace | null>;
500
+ /**
501
+ * Delete a workspace by ID
502
+ */
503
+ deleteWorkspace(tenantId: string, id: string): Promise<boolean>;
504
+ }
505
+
506
+ /**
507
+ * PostgreSQL implementation of ProjectStore
508
+ */
509
+
510
+ /**
511
+ * PostgreSQL ProjectStore options
512
+ */
513
+ interface PostgreSQLProjectStoreOptions {
514
+ /**
515
+ * PostgreSQL connection pool configuration
516
+ * Can be a connection string or PoolConfig object
517
+ */
518
+ poolConfig: string | PoolConfig;
519
+ /**
520
+ * Whether to run migrations automatically on initialization
521
+ * @default true
522
+ */
523
+ autoMigrate?: boolean;
524
+ }
525
+ /**
526
+ * PostgreSQL implementation of ProjectStore
527
+ */
528
+ declare class PostgreSQLProjectStore implements ProjectStore {
529
+ private pool;
530
+ private migrationManager;
531
+ private initialized;
532
+ private ownsPool;
533
+ constructor(options: PostgreSQLProjectStoreOptions);
534
+ /**
535
+ * Dispose resources and close the connection pool
536
+ * Should be called when the store is no longer needed
537
+ */
538
+ dispose(): Promise<void>;
539
+ /**
540
+ * Initialize the store and run migrations
541
+ */
542
+ initialize(): Promise<void>;
543
+ /**
544
+ * Ensure store is initialized
545
+ */
546
+ private ensureInitialized;
547
+ /**
548
+ * Map database row to Project object
549
+ */
550
+ private mapRowToProject;
551
+ /**
552
+ * Get all projects for a specific workspace
553
+ */
554
+ getProjectsByWorkspace(tenantId: string, workspaceId: string): Promise<Project[]>;
555
+ /**
556
+ * Get a project by ID for a specific tenant
557
+ */
558
+ getProjectById(tenantId: string, id: string): Promise<Project | null>;
559
+ /**
560
+ * Create a new project
561
+ */
562
+ createProject(tenantId: string, workspaceId: string, id: string, data: CreateProjectRequest): Promise<Project>;
563
+ /**
564
+ * Update an existing project
565
+ */
566
+ updateProject(tenantId: string, id: string, updates: UpdateProjectRequest): Promise<Project | null>;
567
+ /**
568
+ * Delete a project by ID
569
+ */
570
+ deleteProject(tenantId: string, id: string): Promise<boolean>;
571
+ }
572
+
350
573
  /**
351
574
  * Migration system for database schema management
352
575
  */
@@ -430,4 +653,31 @@ declare const createScheduledTasksTable: Migration;
430
653
  */
431
654
  declare const createSkillsTable: Migration;
432
655
 
433
- export { type Migration, MigrationManager, PostgreSQLAssistantStore, type PostgreSQLAssistantStoreOptions, PostgreSQLScheduleStorage, type PostgreSQLScheduleStorageOptions, PostgreSQLSkillStore, type PostgreSQLSkillStoreOptions, PostgreSQLThreadStore, type PostgreSQLThreadStoreOptions, createAssistantsTable, createScheduledTasksTable, createSkillsTable, createThreadsTable };
656
+ /**
657
+ * Database configuration table migrations
658
+ */
659
+
660
+ /**
661
+ * Initial migration: Create database configs table
662
+ */
663
+ declare const createDatabaseConfigsTable: Migration;
664
+
665
+ /**
666
+ * Workspace table migrations
667
+ */
668
+
669
+ /**
670
+ * Initial migration: Create workspaces table
671
+ */
672
+ declare const createWorkspacesTable: Migration;
673
+
674
+ /**
675
+ * Project table migrations
676
+ */
677
+
678
+ /**
679
+ * Initial migration: Create projects table
680
+ */
681
+ declare const createProjectsTable: Migration;
682
+
683
+ export { type Migration, MigrationManager, PostgreSQLAssistantStore, type PostgreSQLAssistantStoreOptions, PostgreSQLDatabaseConfigStore, type PostgreSQLDatabaseConfigStoreOptions, PostgreSQLProjectStore, type PostgreSQLProjectStoreOptions, PostgreSQLScheduleStorage, type PostgreSQLScheduleStorageOptions, PostgreSQLSkillStore, type PostgreSQLSkillStoreOptions, PostgreSQLThreadStore, type PostgreSQLThreadStoreOptions, PostgreSQLWorkspaceStore, type PostgreSQLWorkspaceStoreOptions, createAssistantsTable, createDatabaseConfigsTable, createProjectsTable, createScheduledTasksTable, createSkillsTable, createThreadsTable, createWorkspacesTable };