@axiom-lattice/local-stores 5.1.2 → 5.2.1

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.
@@ -36,6 +36,7 @@ import { LocalPlatformInvitationStore } from "./stores/LocalPlatformInvitationSt
36
36
  import { LocalOidcIdentityClaimStore } from "./stores/LocalOidcIdentityClaimStore";
37
37
  import { LocalInviteLinkStore } from "./stores/LocalInviteLinkStore";
38
38
  import { LocalPlatformSettingsStore } from "./stores/LocalPlatformSettingsStore";
39
+ import { LocalPlatformAuditStore } from "./stores/LocalPlatformAuditStore";
39
40
  import { LocalDatabaseConfigStore } from "./stores/LocalDatabaseConfigStore";
40
41
  import { LocalConnectionStore } from "./stores/LocalConnectionStore";
41
42
  import { LocalMetricsServerConfigStore } from "./stores/LocalMetricsServerConfigStore";
@@ -97,6 +98,7 @@ export async function createLocalStoreConfig(options: LocalStoreConfigOptions =
97
98
  oidcIdentityClaim: new LocalOidcIdentityClaimStore(db),
98
99
  inviteLink: new LocalInviteLinkStore(db),
99
100
  platformSettings: new LocalPlatformSettingsStore(db),
101
+ platformAudit: new LocalPlatformAuditStore(db),
100
102
  database: new LocalDatabaseConfigStore(db),
101
103
  connection: new LocalConnectionStore(db),
102
104
  metrics: new LocalMetricsServerConfigStore(db),
package/src/index.ts CHANGED
@@ -47,6 +47,7 @@ export { LocalPlatformInvitationStore } from "./stores/LocalPlatformInvitationSt
47
47
  export { LocalOidcIdentityClaimStore } from "./stores/LocalOidcIdentityClaimStore";
48
48
  export { LocalInviteLinkStore } from "./stores/LocalInviteLinkStore";
49
49
  export { LocalPlatformSettingsStore } from "./stores/LocalPlatformSettingsStore";
50
+ export { LocalPlatformAuditStore } from "./stores/LocalPlatformAuditStore";
50
51
  export { LocalDatabaseConfigStore } from "./stores/LocalDatabaseConfigStore";
51
52
  export { LocalConnectionStore } from "./stores/LocalConnectionStore";
52
53
  export { LocalMetricsServerConfigStore } from "./stores/LocalMetricsServerConfigStore";
@@ -6,6 +6,8 @@ import { DatabaseWrapper } from "../database";
6
6
  import type {
7
7
  McpServerConfigStore,
8
8
  McpServerConfigEntry,
9
+ PersonalMcpServerConfigStore,
10
+ PersonalMcpServerConfigEntry,
9
11
  CreateMcpServerConfigRequest,
10
12
  UpdateMcpServerConfigRequest,
11
13
  McpServerConfig,
@@ -29,6 +31,24 @@ CREATE TABLE IF NOT EXISTS lt_mcp_configs (
29
31
  PRIMARY KEY (tenant_id, id)
30
32
  );
31
33
  CREATE UNIQUE INDEX IF NOT EXISTS idx_lt_mcp_key ON lt_mcp_configs(tenant_id, key);
34
+
35
+ CREATE TABLE IF NOT EXISTS lt_personal_mcp_configs (
36
+ id TEXT NOT NULL,
37
+ tenant_id TEXT NOT NULL,
38
+ owner_assistant_id TEXT NOT NULL,
39
+ key TEXT NOT NULL,
40
+ name TEXT,
41
+ description TEXT,
42
+ config TEXT NOT NULL,
43
+ selected_tools TEXT DEFAULT '[]',
44
+ is_env_encrypted INTEGER NOT NULL DEFAULT 0,
45
+ status TEXT NOT NULL DEFAULT 'disconnected',
46
+ created_at TEXT NOT NULL,
47
+ updated_at TEXT NOT NULL,
48
+ PRIMARY KEY (tenant_id, owner_assistant_id, id)
49
+ );
50
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_lt_personal_mcp_key
51
+ ON lt_personal_mcp_configs(tenant_id, owner_assistant_id, key);
32
52
  `;
33
53
 
34
54
  interface ConfigRow {
@@ -45,7 +65,12 @@ interface ConfigRow {
45
65
  updated_at: string;
46
66
  }
47
67
 
48
- export class LocalMcpServerConfigStore implements McpServerConfigStore {
68
+ interface PersonalConfigRow extends ConfigRow {
69
+ owner_assistant_id: string;
70
+ }
71
+
72
+ export class LocalMcpServerConfigStore
73
+ implements McpServerConfigStore, PersonalMcpServerConfigStore {
49
74
  private db: DatabaseWrapper;
50
75
 
51
76
  constructor(db: DatabaseWrapper) {
@@ -173,6 +198,173 @@ export class LocalMcpServerConfigStore implements McpServerConfigStore {
173
198
  ).get(tenantId, id);
174
199
  return row !== undefined;
175
200
  }
201
+
202
+ async getAllConfigsForAssistant(
203
+ tenantId: string,
204
+ ownerAssistantId: string,
205
+ ): Promise<PersonalMcpServerConfigEntry[]> {
206
+ const rows = this.db.prepare(
207
+ `SELECT * FROM lt_personal_mcp_configs
208
+ WHERE tenant_id = ? AND owner_assistant_id = ?
209
+ ORDER BY created_at DESC`,
210
+ ).all(tenantId, ownerAssistantId) as unknown as PersonalConfigRow[];
211
+ return rows.map(mapPersonalRowToEntry);
212
+ }
213
+
214
+ async getAllPersonalConfigsWithoutTenant(): Promise<PersonalMcpServerConfigEntry[]> {
215
+ const rows = this.db.prepare(
216
+ `SELECT * FROM lt_personal_mcp_configs ORDER BY created_at DESC`,
217
+ ).all() as unknown as PersonalConfigRow[];
218
+ return rows.map(mapPersonalRowToEntry);
219
+ }
220
+
221
+ async getConfigByIdForAssistant(
222
+ tenantId: string,
223
+ ownerAssistantId: string,
224
+ id: string,
225
+ ): Promise<PersonalMcpServerConfigEntry | null> {
226
+ const row = this.db.prepare(
227
+ `SELECT * FROM lt_personal_mcp_configs
228
+ WHERE tenant_id = ? AND owner_assistant_id = ? AND id = ?`,
229
+ ).get(tenantId, ownerAssistantId, id) as unknown as PersonalConfigRow | undefined;
230
+ return row ? mapPersonalRowToEntry(row) : null;
231
+ }
232
+
233
+ async getConfigByKeyForAssistant(
234
+ tenantId: string,
235
+ ownerAssistantId: string,
236
+ key: string,
237
+ ): Promise<PersonalMcpServerConfigEntry | null> {
238
+ const row = this.db.prepare(
239
+ `SELECT * FROM lt_personal_mcp_configs
240
+ WHERE tenant_id = ? AND owner_assistant_id = ? AND key = ?`,
241
+ ).get(tenantId, ownerAssistantId, key) as unknown as PersonalConfigRow | undefined;
242
+ return row ? mapPersonalRowToEntry(row) : null;
243
+ }
244
+
245
+ async createConfigForAssistant(
246
+ tenantId: string,
247
+ ownerAssistantId: string,
248
+ id: string,
249
+ data: CreateMcpServerConfigRequest,
250
+ ): Promise<PersonalMcpServerConfigEntry> {
251
+ const now = nowISO();
252
+ const { config: configWithEncryptedEnv, isEnvEncrypted } =
253
+ encryptEnvInConfig(data.config);
254
+
255
+ this.db.prepare(
256
+ `INSERT INTO lt_personal_mcp_configs (id, tenant_id, owner_assistant_id, key, name, description, config, selected_tools, is_env_encrypted, status, created_at, updated_at)
257
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
258
+ ON CONFLICT(tenant_id, owner_assistant_id, id) DO UPDATE SET
259
+ key = excluded.key,
260
+ name = excluded.name,
261
+ description = excluded.description,
262
+ config = excluded.config,
263
+ selected_tools = excluded.selected_tools,
264
+ is_env_encrypted = excluded.is_env_encrypted,
265
+ status = excluded.status,
266
+ updated_at = excluded.updated_at`,
267
+ ).run(
268
+ id, tenantId, ownerAssistantId, data.key, data.name || null, data.description || null,
269
+ JSON.stringify(configWithEncryptedEnv),
270
+ JSON.stringify(data.selectedTools || []),
271
+ isEnvEncrypted ? 1 : 0, "disconnected",
272
+ now, now,
273
+ );
274
+
275
+ return {
276
+ id,
277
+ tenantId,
278
+ ownerAssistantId,
279
+ key: data.key,
280
+ config: data.config,
281
+ name: data.name,
282
+ description: data.description,
283
+ selectedTools: data.selectedTools || [],
284
+ isEnvEncrypted,
285
+ status: "disconnected",
286
+ createdAt: parseISO(now),
287
+ updatedAt: parseISO(now),
288
+ };
289
+ }
290
+
291
+ async updateConfigForAssistant(
292
+ tenantId: string,
293
+ ownerAssistantId: string,
294
+ id: string,
295
+ updates: Partial<UpdateMcpServerConfigRequest>,
296
+ ): Promise<PersonalMcpServerConfigEntry | null> {
297
+ const existing = await this.getConfigByIdForAssistant(
298
+ tenantId,
299
+ ownerAssistantId,
300
+ id,
301
+ );
302
+ if (!existing) return null;
303
+
304
+ const setClauses: string[] = [];
305
+ const values: unknown[] = [];
306
+
307
+ if (updates.key !== undefined) { setClauses.push("key = ?"); values.push(updates.key); }
308
+ if (updates.name !== undefined) { setClauses.push("name = ?"); values.push(updates.name || null); }
309
+ if (updates.description !== undefined) { setClauses.push("description = ?"); values.push(updates.description || null); }
310
+ if (updates.config !== undefined) {
311
+ const { config: configWithEncryptedEnv, isEnvEncrypted } = encryptEnvInConfig(updates.config);
312
+ setClauses.push("config = ?"); values.push(JSON.stringify(configWithEncryptedEnv));
313
+ setClauses.push("is_env_encrypted = ?"); values.push(isEnvEncrypted ? 1 : 0);
314
+ }
315
+ if (updates.selectedTools !== undefined) { setClauses.push("selected_tools = ?"); values.push(JSON.stringify(updates.selectedTools)); }
316
+ if (updates.status !== undefined) { setClauses.push("status = ?"); values.push(updates.status); }
317
+
318
+ if (setClauses.length === 0) return existing;
319
+
320
+ const now = nowISO();
321
+ setClauses.push("updated_at = ?");
322
+ values.push(now);
323
+ values.push(tenantId, ownerAssistantId, id);
324
+
325
+ this.db.prepare(
326
+ `UPDATE lt_personal_mcp_configs SET ${setClauses.join(", ")}
327
+ WHERE tenant_id = ? AND owner_assistant_id = ? AND id = ?`,
328
+ ).run(...values);
329
+
330
+ return this.getConfigByIdForAssistant(tenantId, ownerAssistantId, id);
331
+ }
332
+
333
+ async deleteConfigForAssistant(
334
+ tenantId: string,
335
+ ownerAssistantId: string,
336
+ id: string,
337
+ ): Promise<boolean> {
338
+ const result = this.db.prepare(
339
+ `DELETE FROM lt_personal_mcp_configs
340
+ WHERE tenant_id = ? AND owner_assistant_id = ? AND id = ?`,
341
+ ).run(tenantId, ownerAssistantId, id);
342
+ return result.changes > 0;
343
+ }
344
+
345
+ async deleteConfigsForAssistant(
346
+ tenantId: string,
347
+ ownerAssistantId: string,
348
+ ): Promise<number> {
349
+ const result = this.db.prepare(
350
+ `DELETE FROM lt_personal_mcp_configs
351
+ WHERE tenant_id = ? AND owner_assistant_id = ?`,
352
+ ).run(tenantId, ownerAssistantId);
353
+ return result.changes;
354
+ }
355
+
356
+ async hasConfigForAssistant(
357
+ tenantId: string,
358
+ ownerAssistantId: string,
359
+ id: string,
360
+ ): Promise<boolean> {
361
+ const row = this.db.prepare(
362
+ `SELECT 1 FROM lt_personal_mcp_configs
363
+ WHERE tenant_id = ? AND owner_assistant_id = ? AND id = ?
364
+ LIMIT 1`,
365
+ ).get(tenantId, ownerAssistantId, id);
366
+ return row !== undefined;
367
+ }
176
368
  }
177
369
 
178
370
  function mapRowToEntry(row: ConfigRow): McpServerConfigEntry {
@@ -209,6 +401,13 @@ function mapRowToEntry(row: ConfigRow): McpServerConfigEntry {
209
401
  };
210
402
  }
211
403
 
404
+ function mapPersonalRowToEntry(row: PersonalConfigRow): PersonalMcpServerConfigEntry {
405
+ return {
406
+ ...mapRowToEntry(row),
407
+ ownerAssistantId: row.owner_assistant_id,
408
+ };
409
+ }
410
+
212
411
  function encryptEnvInConfig(config: McpServerConfig): { config: McpServerConfig; isEnvEncrypted: boolean } {
213
412
  const configCopy = { ...config };
214
413
  let isEnvEncrypted = false;
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Local SQLite implementation of the platform audit store (append-only).
3
+ */
4
+
5
+ import type {
6
+ PlatformAuditAction,
7
+ PlatformAuditAppendInput,
8
+ PlatformAuditInitiator,
9
+ PlatformAuditQuery,
10
+ PlatformAuditRecord,
11
+ PlatformAuditSource,
12
+ PlatformAuditStatus,
13
+ PlatformAuditStore,
14
+ } from "@axiom-lattice/protocols";
15
+ import { randomUUID } from "node:crypto";
16
+ import { DatabaseWrapper, ensureTable, nowISO, parseISO } from "../database";
17
+
18
+ const DDL = `
19
+ CREATE TABLE IF NOT EXISTS lattice_platform_audit (
20
+ id TEXT NOT NULL PRIMARY KEY,
21
+ initiator_user_id TEXT,
22
+ initiator_role TEXT,
23
+ initiator_json TEXT NOT NULL,
24
+ source TEXT NOT NULL,
25
+ executor_json TEXT NOT NULL,
26
+ tenant_id TEXT,
27
+ action TEXT NOT NULL,
28
+ status TEXT NOT NULL,
29
+ summary_json TEXT NOT NULL,
30
+ before_json TEXT,
31
+ after_json TEXT,
32
+ error_code TEXT,
33
+ duration_ms INTEGER NOT NULL,
34
+ created_at TEXT NOT NULL
35
+ );
36
+ CREATE INDEX IF NOT EXISTS idx_lattice_platform_audit_created
37
+ ON lattice_platform_audit(created_at DESC, id DESC);
38
+ CREATE INDEX IF NOT EXISTS idx_lattice_platform_audit_initiator
39
+ ON lattice_platform_audit(initiator_user_id, created_at DESC);
40
+ CREATE INDEX IF NOT EXISTS idx_lattice_platform_audit_tenant
41
+ ON lattice_platform_audit(tenant_id, created_at DESC);
42
+ `;
43
+
44
+ interface AuditRow {
45
+ id: string;
46
+ initiator_user_id: string | null;
47
+ initiator_role: string | null;
48
+ initiator_json: string;
49
+ source: string;
50
+ executor_json: string;
51
+ tenant_id: string | null;
52
+ action: string;
53
+ status: string;
54
+ summary_json: string;
55
+ before_json: string | null;
56
+ after_json: string | null;
57
+ error_code: string | null;
58
+ duration_ms: number;
59
+ created_at: string;
60
+ }
61
+
62
+ function parseJson<T>(value: string): T {
63
+ return JSON.parse(value) as T;
64
+ }
65
+
66
+ /**
67
+ * Normalizes an optional timestamp boundary to a canonical UTC ISO string.
68
+ *
69
+ * Equivalent inputs (e.g. `2024-01-01T08:00:01+08:00`, date-only values, or
70
+ * explicit `Z`) all compare as the same instant. Empty or unparseable values
71
+ * are ignored rather than compared as raw text.
72
+ */
73
+ function normalizeBoundary(value?: string): string | undefined {
74
+ if (value === undefined) return undefined;
75
+ const trimmed = value.trim();
76
+ if (trimmed === "") return undefined;
77
+ const parsed = new Date(trimmed);
78
+ if (Number.isNaN(parsed.getTime())) return undefined;
79
+ return parsed.toISOString();
80
+ }
81
+
82
+ /**
83
+ * Normalizes a pagination value: non-finite values use the fallback, finite
84
+ * values are truncated to integers, and negatives are clamped to zero.
85
+ */
86
+ function normalizePagination(
87
+ value: number | undefined,
88
+ fallback: number,
89
+ ): number {
90
+ if (value === undefined || !Number.isFinite(value)) return fallback;
91
+ return Math.max(0, Math.trunc(value));
92
+ }
93
+
94
+ function mapRow(row: AuditRow): PlatformAuditRecord {
95
+ return {
96
+ id: row.id,
97
+ initiator: parseJson<PlatformAuditInitiator>(row.initiator_json),
98
+ source: row.source as PlatformAuditSource,
99
+ executor: parseJson<PlatformAuditRecord["executor"]>(row.executor_json),
100
+ ...(row.tenant_id !== null ? { tenantId: row.tenant_id } : {}),
101
+ action: row.action as PlatformAuditAction,
102
+ status: row.status as PlatformAuditStatus,
103
+ summary: parseJson<Record<string, unknown>>(row.summary_json),
104
+ ...(row.before_json !== null
105
+ ? { before: parseJson<Record<string, unknown>>(row.before_json) }
106
+ : {}),
107
+ ...(row.after_json !== null
108
+ ? { after: parseJson<Record<string, unknown>>(row.after_json) }
109
+ : {}),
110
+ ...(row.error_code !== null ? { errorCode: row.error_code } : {}),
111
+ durationMs: Number(row.duration_ms),
112
+ createdAt: parseISO(row.created_at),
113
+ };
114
+ }
115
+
116
+ /**
117
+ * SQLite implementation of {@link PlatformAuditStore}.
118
+ *
119
+ * Persists platform-level audit records in the local
120
+ * `lattice_platform_audit` table. Records are append-only and returned
121
+ * newest-first by `createdAt` descending, then `id` descending.
122
+ */
123
+ export class LocalPlatformAuditStore implements PlatformAuditStore {
124
+ private readonly db: DatabaseWrapper;
125
+
126
+ constructor(db: DatabaseWrapper) {
127
+ this.db = db;
128
+ ensureTable(db, DDL);
129
+ }
130
+
131
+ /** Appends a record, assigning a fresh id and creation timestamp. */
132
+ async append(record: PlatformAuditAppendInput): Promise<PlatformAuditRecord> {
133
+ const id = randomUUID();
134
+ const initiator = record.initiator;
135
+ const initiatorUserId =
136
+ initiator.type === "human" ? initiator.userId : null;
137
+ const initiatorRole = initiator.type === "human" ? initiator.role : null;
138
+ const durationMs = Number.isFinite(record.durationMs)
139
+ ? Math.max(0, Math.round(record.durationMs))
140
+ : 0;
141
+
142
+ this.db
143
+ .prepare(
144
+ `INSERT INTO lattice_platform_audit
145
+ (id, initiator_user_id, initiator_role, initiator_json, source,
146
+ executor_json, tenant_id, action, status, summary_json, before_json,
147
+ after_json, error_code, duration_ms, created_at)
148
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
149
+ )
150
+ .run(
151
+ id,
152
+ initiatorUserId,
153
+ initiatorRole,
154
+ JSON.stringify(initiator),
155
+ record.source,
156
+ JSON.stringify(record.executor),
157
+ record.tenantId ?? null,
158
+ record.action,
159
+ record.status,
160
+ JSON.stringify(record.summary),
161
+ record.before === undefined ? null : JSON.stringify(record.before),
162
+ record.after === undefined ? null : JSON.stringify(record.after),
163
+ record.errorCode ?? null,
164
+ durationMs,
165
+ nowISO(),
166
+ );
167
+
168
+ const stored = await this.get(id);
169
+ if (!stored) throw new Error("Platform audit record was not persisted");
170
+ return stored;
171
+ }
172
+
173
+ /** Returns a record by id, or null when it does not exist. */
174
+ async get(id: string): Promise<PlatformAuditRecord | null> {
175
+ const row = this.db
176
+ .prepare(`SELECT * FROM lattice_platform_audit WHERE id = ?`)
177
+ .get(id) as unknown as AuditRow | undefined;
178
+ return row ? mapRow(row) : null;
179
+ }
180
+
181
+ /**
182
+ * Returns matching records newest-first.
183
+ *
184
+ * `initiatorUserId` only matches human initiators. `from` is inclusive and
185
+ * `to` is exclusive after both are normalized to instants; invalid or empty
186
+ * boundaries are ignored. Records are ordered by `createdAt` descending,
187
+ * then by `id` descending. Results are paginated with a default limit of 100;
188
+ * non-finite `offset`/`limit` fall back to defaults, finite values are
189
+ * truncated to integers, and negatives are clamped to 0.
190
+ */
191
+ async query(params: PlatformAuditQuery): Promise<PlatformAuditRecord[]> {
192
+ const clauses: string[] = [];
193
+ const values: unknown[] = [];
194
+
195
+ if (params.initiatorUserId !== undefined) {
196
+ clauses.push("initiator_user_id = ?");
197
+ values.push(params.initiatorUserId);
198
+ }
199
+ if (params.source !== undefined) {
200
+ clauses.push("source = ?");
201
+ values.push(params.source);
202
+ }
203
+ if (params.tenantId !== undefined) {
204
+ clauses.push("tenant_id = ?");
205
+ values.push(params.tenantId);
206
+ }
207
+ if (params.action !== undefined) {
208
+ clauses.push("action = ?");
209
+ values.push(params.action);
210
+ }
211
+ if (params.status !== undefined) {
212
+ clauses.push("status = ?");
213
+ values.push(params.status);
214
+ }
215
+ const from = normalizeBoundary(params.from);
216
+ if (from !== undefined) {
217
+ clauses.push("created_at >= ?");
218
+ values.push(from);
219
+ }
220
+ const to = normalizeBoundary(params.to);
221
+ if (to !== undefined) {
222
+ clauses.push("created_at < ?");
223
+ values.push(to);
224
+ }
225
+
226
+ const limit = normalizePagination(params.limit, 100);
227
+ const offset = normalizePagination(params.offset, 0);
228
+ values.push(limit, offset);
229
+
230
+ const where = clauses.length > 0 ? ` WHERE ${clauses.join(" AND ")}` : "";
231
+ const rows = this.db
232
+ .prepare(
233
+ `SELECT * FROM lattice_platform_audit${where}
234
+ ORDER BY created_at DESC, id DESC
235
+ LIMIT ? OFFSET ?`,
236
+ )
237
+ .all(...values) as unknown as AuditRow[];
238
+
239
+ return rows.map(mapRow);
240
+ }
241
+ }
@@ -3,12 +3,13 @@
3
3
  */
4
4
 
5
5
  import { DatabaseWrapper } from "../database";
6
- import type {
7
- UserTenantLinkStore,
8
- UserTenantLink,
9
- UserTenantRole,
10
- CreateUserTenantLinkRequest,
11
- UpdateUserTenantLinkRequest,
6
+ import {
7
+ assertNotPlatformTenant,
8
+ type UserTenantLinkStore,
9
+ type UserTenantLink,
10
+ type UserTenantRole,
11
+ type CreateUserTenantLinkRequest,
12
+ type UpdateUserTenantLinkRequest,
12
13
  } from "@axiom-lattice/protocols";
13
14
  import { ensureTable, nowISO, parseISO } from "../database";
14
15
 
@@ -63,6 +64,7 @@ export class LocalUserTenantLinkStore implements UserTenantLinkStore {
63
64
  }
64
65
 
65
66
  async createLink(data: CreateUserTenantLinkRequest): Promise<UserTenantLink> {
67
+ assertNotPlatformTenant(data.tenantId);
66
68
  const now = nowISO();
67
69
  const role = data.role || "member";
68
70
  const metadata = JSON.stringify(data.metadata || {});