@happyvertical/smrt-secrets 0.37.2 → 0.37.3

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,1311 +0,0 @@
1
- import { a as SecretAuditLog, S as Secret, T as TenantKey, c as createAuditEntry } from "./TenantKey-Da_DXRSn.js";
2
- import { loadEnvConfig } from "@happyvertical/utils";
3
- import { getSecretStore, EnvelopeEncryption, AMKUnavailableError, TenantKeyMissingError, EncryptionError, DecryptionError } from "@happyvertical/secrets";
4
- import { requireTenantId, withTenant, getCurrentTenant } from "@happyvertical/smrt-tenancy";
5
- import { SmrtCollection } from "@happyvertical/smrt-core";
6
- class SecretAuditLogCollection extends SmrtCollection {
7
- static _itemClass = SecretAuditLog;
8
- /**
9
- * List audit logs with filtering options
10
- */
11
- async listLogs(options = {}) {
12
- const where = {};
13
- if (options.tenantId) {
14
- where.tenantId = options.tenantId;
15
- }
16
- if (options.secretName) {
17
- where.secretName = options.secretName;
18
- }
19
- if (options.userId) {
20
- where.userId = options.userId;
21
- }
22
- if (options.action) {
23
- where.action = options.action;
24
- }
25
- if (options.result) {
26
- where.result = options.result;
27
- }
28
- if (options.since) {
29
- where["created_at >"] = options.since.toISOString();
30
- }
31
- if (options.until) {
32
- where["created_at <"] = options.until.toISOString();
33
- }
34
- return this.list({
35
- where,
36
- limit: options.limit ?? 100,
37
- offset: options.offset,
38
- orderBy: "created_at DESC"
39
- });
40
- }
41
- /**
42
- * Get audit logs for a specific secret.
43
- *
44
- * @param tenantId - Scope to this tenant's audit trail, or `null` for a
45
- * cross-tenant compliance query (which must run under
46
- * `withSuperAdminBypass()` from `@happyvertical/smrt-tenancy`). Audit rows
47
- * reference secret names and must not leak across tenants (#1503).
48
- */
49
- async getSecretHistory(tenantId, secretName, limit = 50) {
50
- return this.listLogs({ tenantId: tenantId ?? void 0, secretName, limit });
51
- }
52
- /**
53
- * Get audit logs for a specific user.
54
- *
55
- * @param tenantId - Scope to this tenant's audit trail, or `null` for a
56
- * cross-tenant compliance query under `withSuperAdminBypass()` (#1503).
57
- */
58
- async getUserActivity(tenantId, userId, limit = 50) {
59
- return this.listLogs({ tenantId: tenantId ?? void 0, userId, limit });
60
- }
61
- /**
62
- * Get recent failures.
63
- *
64
- * @param tenantId - Scope to this tenant's audit trail, or `null` for a
65
- * cross-tenant compliance query under `withSuperAdminBypass()` (#1503).
66
- */
67
- async getRecentFailures(tenantId, limit = 20) {
68
- return this.listLogs({
69
- tenantId: tenantId ?? void 0,
70
- result: "failure",
71
- limit
72
- });
73
- }
74
- /**
75
- * Get recent denied access attempts.
76
- *
77
- * @param tenantId - Scope to this tenant's audit trail, or `null` for a
78
- * cross-tenant compliance query under `withSuperAdminBypass()` (#1503).
79
- */
80
- async getRecentDenials(tenantId, limit = 20) {
81
- return this.listLogs({
82
- tenantId: tenantId ?? void 0,
83
- result: "denied",
84
- limit
85
- });
86
- }
87
- /**
88
- * Count operations by action type.
89
- *
90
- * @param tenantId - Scope to this tenant's audit trail, or `null` for a
91
- * cross-tenant compliance count under `withSuperAdminBypass()` (#1503).
92
- */
93
- async countByAction(tenantId, since) {
94
- const logs = await this.listLogs({
95
- tenantId: tenantId ?? void 0,
96
- since,
97
- limit: 1e4
98
- });
99
- const counts = {
100
- create: 0,
101
- read: 0,
102
- update: 0,
103
- delete: 0,
104
- rotate_key: 0,
105
- disable: 0,
106
- enable: 0,
107
- expire: 0
108
- };
109
- for (const log of logs) {
110
- counts[log.action]++;
111
- }
112
- return counts;
113
- }
114
- /**
115
- * Count operations by result.
116
- *
117
- * @param tenantId - Scope to this tenant's audit trail, or `null` for a
118
- * cross-tenant compliance count under `withSuperAdminBypass()` (#1503).
119
- */
120
- async countByResult(tenantId, since) {
121
- const logs = await this.listLogs({
122
- tenantId: tenantId ?? void 0,
123
- since,
124
- limit: 1e4
125
- });
126
- const counts = {
127
- success: 0,
128
- failure: 0,
129
- denied: 0
130
- };
131
- for (const log of logs) {
132
- counts[log.result]++;
133
- }
134
- return counts;
135
- }
136
- /**
137
- * Delete old audit logs
138
- * @param olderThanDays Delete logs older than this many days
139
- */
140
- async cleanup(olderThanDays = 365) {
141
- const cutoffDate = /* @__PURE__ */ new Date();
142
- cutoffDate.setDate(cutoffDate.getDate() - olderThanDays);
143
- const oldLogs = await this.list({
144
- where: {
145
- "created_at <": cutoffDate.toISOString()
146
- }
147
- });
148
- let count = 0;
149
- for (const log of oldLogs) {
150
- await log.delete();
151
- count++;
152
- }
153
- return count;
154
- }
155
- }
156
- class SecretCollection extends SmrtCollection {
157
- static _itemClass = Secret;
158
- /**
159
- * Find a secret by name within the given tenant
160
- */
161
- async findByName(tenantId, name) {
162
- return this.get({ name, tenantId });
163
- }
164
- /**
165
- * List secrets for a tenant with filtering options
166
- */
167
- async listSecrets(tenantId, options = {}) {
168
- const where = { tenantId };
169
- if (options.category) {
170
- where.category = options.category;
171
- }
172
- if (options.status) {
173
- where.status = options.status;
174
- }
175
- const secrets = await this.list({
176
- where,
177
- limit: options.limit,
178
- offset: options.offset,
179
- orderBy: "name ASC"
180
- });
181
- if (!options.includeExpired) {
182
- return secrets.filter((secret) => !secret.isExpired());
183
- }
184
- return secrets;
185
- }
186
- /**
187
- * List all active secrets for a tenant
188
- */
189
- async listActive(tenantId) {
190
- return this.listSecrets(tenantId, { status: "active" });
191
- }
192
- /**
193
- * List a tenant's secrets by category
194
- */
195
- async listByCategory(tenantId, category) {
196
- return this.listSecrets(tenantId, { category, status: "active" });
197
- }
198
- /**
199
- * List a tenant's secrets that need attention (expired or about to expire)
200
- */
201
- async listExpiring(tenantId, daysAhead = 30) {
202
- const futureDate = /* @__PURE__ */ new Date();
203
- futureDate.setDate(futureDate.getDate() + daysAhead);
204
- const secrets = await this.list({
205
- where: {
206
- tenantId,
207
- status: "active",
208
- "expiresAt !=": null,
209
- "expiresAt <": futureDate.toISOString()
210
- },
211
- orderBy: "expiresAt ASC"
212
- });
213
- return secrets;
214
- }
215
- /**
216
- * Get categories used in a tenant's secrets
217
- */
218
- async getCategories(tenantId) {
219
- const secrets = await this.list({ where: { tenantId } });
220
- const categories = new Set(secrets.map((s) => s.category).filter(Boolean));
221
- return Array.from(categories).sort();
222
- }
223
- /**
224
- * Count a tenant's secrets by status
225
- */
226
- async countByStatus(tenantId) {
227
- const secrets = await this.list({ where: { tenantId } });
228
- const counts = {
229
- active: 0,
230
- disabled: 0,
231
- expired: 0
232
- };
233
- for (const secret of secrets) {
234
- if (secret.isExpired()) {
235
- counts.expired++;
236
- } else {
237
- counts[secret.status]++;
238
- }
239
- }
240
- return counts;
241
- }
242
- /**
243
- * Delete a tenant's secret by name
244
- */
245
- async deleteByName(tenantId, name) {
246
- const secret = await this.findByName(tenantId, name);
247
- if (!secret) return false;
248
- await secret.delete();
249
- return true;
250
- }
251
- }
252
- class TenantKeyCollection extends SmrtCollection {
253
- static _itemClass = TenantKey;
254
- /**
255
- * Get the active key for a tenant
256
- */
257
- async getActiveKey(tenantId) {
258
- return this.get({
259
- tenantId,
260
- status: "active"
261
- });
262
- }
263
- /**
264
- * List all key versions for a tenant
265
- */
266
- async listKeyVersions(tenantId) {
267
- return this.list({
268
- where: { tenantId },
269
- orderBy: "version DESC"
270
- });
271
- }
272
- /**
273
- * Get a specific key version for a tenant
274
- */
275
- async getKeyVersion(tenantId, version) {
276
- return this.get({
277
- tenantId,
278
- version
279
- });
280
- }
281
- /**
282
- * Find keys that need rotation
283
- */
284
- async findKeysNeedingRotation() {
285
- const now = /* @__PURE__ */ new Date();
286
- return this.list({
287
- where: {
288
- status: "active",
289
- "rotateAfter !=": null,
290
- "rotateAfter <": now.toISOString()
291
- },
292
- orderBy: "rotateAfter ASC"
293
- });
294
- }
295
- /**
296
- * List all active keys across all tenants
297
- */
298
- async listAllActiveKeys() {
299
- return this.list({
300
- where: { status: "active" },
301
- orderBy: "created_at DESC"
302
- });
303
- }
304
- /**
305
- * Count keys by status
306
- */
307
- async countByStatus() {
308
- const keys = await this.list({});
309
- const counts = {
310
- active: 0,
311
- rotating: 0,
312
- retired: 0,
313
- compromised: 0
314
- };
315
- for (const key of keys) {
316
- counts[key.status]++;
317
- }
318
- return counts;
319
- }
320
- /**
321
- * Mark a key as compromised (should trigger re-encryption)
322
- */
323
- async markCompromised(tenantId, keyId) {
324
- const key = await this.get({
325
- id: keyId,
326
- tenantId
327
- });
328
- if (!key) return false;
329
- key.markCompromised();
330
- await key.save();
331
- return true;
332
- }
333
- /**
334
- * Delete old retired keys that are no longer needed
335
- * @param olderThanDays Delete keys retired more than this many days ago
336
- */
337
- async cleanupRetiredKeys(olderThanDays = 90) {
338
- const cutoffDate = /* @__PURE__ */ new Date();
339
- cutoffDate.setDate(cutoffDate.getDate() - olderThanDays);
340
- const oldKeys = await this.list({
341
- where: {
342
- status: "retired",
343
- "retiredAt <": cutoffDate.toISOString()
344
- }
345
- });
346
- let count = 0;
347
- for (const key of oldKeys) {
348
- await key.delete();
349
- count++;
350
- }
351
- return count;
352
- }
353
- }
354
- class ConsoleLogger {
355
- constructor(level = "info") {
356
- this.level = level;
357
- }
358
- static LEVELS = [
359
- "debug",
360
- "info",
361
- "warn",
362
- "error"
363
- ];
364
- /**
365
- * Check if a log level should be output
366
- *
367
- * @param level - Log level to check
368
- * @returns True if level meets threshold
369
- */
370
- shouldLog(level) {
371
- const currentIndex = ConsoleLogger.LEVELS.indexOf(this.level);
372
- const messageIndex = ConsoleLogger.LEVELS.indexOf(level);
373
- return messageIndex >= currentIndex;
374
- }
375
- /**
376
- * Format context for console output
377
- *
378
- * @param context - Structured metadata
379
- * @returns Formatted context string
380
- */
381
- formatContext(context) {
382
- if (!context || Object.keys(context).length === 0) {
383
- return "";
384
- }
385
- return ` ${JSON.stringify(context)}`;
386
- }
387
- debug(message, context) {
388
- if (this.shouldLog("debug")) {
389
- console.debug(`[DEBUG] ${message}${this.formatContext(context)}`);
390
- }
391
- }
392
- info(message, context) {
393
- if (this.shouldLog("info")) {
394
- console.info(`[INFO] ${message}${this.formatContext(context)}`);
395
- }
396
- }
397
- warn(message, context) {
398
- if (this.shouldLog("warn")) {
399
- console.warn(`[WARN] ${message}${this.formatContext(context)}`);
400
- }
401
- }
402
- error(message, context) {
403
- if (this.shouldLog("error")) {
404
- console.error(`[ERROR] ${message}${this.formatContext(context)}`);
405
- }
406
- }
407
- }
408
- class NoopLogger {
409
- debug(_message, _context) {
410
- }
411
- info(_message, _context) {
412
- }
413
- warn(_message, _context) {
414
- }
415
- error(_message, _context) {
416
- }
417
- }
418
- function createLogger(config) {
419
- if (typeof config === "boolean") {
420
- if (!config) {
421
- return new NoopLogger();
422
- }
423
- const envConfig = loadEnvConfig(
424
- {},
425
- {
426
- packageName: "logger",
427
- schema: { level: "string" }
428
- }
429
- );
430
- return new ConsoleLogger(envConfig.level || "info");
431
- }
432
- const mergedConfig = loadEnvConfig(config, {
433
- packageName: "logger",
434
- schema: { level: "string" }
435
- });
436
- const level = mergedConfig.level || "info";
437
- return new ConsoleLogger(level);
438
- }
439
- const logger = createLogger({ level: "info" });
440
- class SecretKeyDriftError extends Error {
441
- code = "SECRET_KEY_DRIFT";
442
- tenantId;
443
- report;
444
- cause;
445
- constructor(message, tenantId, report, cause) {
446
- super(message);
447
- this.name = "SecretKeyDriftError";
448
- this.tenantId = tenantId;
449
- this.report = report;
450
- this.cause = cause;
451
- }
452
- }
453
- class SecretService {
454
- db;
455
- secretStore;
456
- secrets;
457
- tenantKeys;
458
- auditLogs;
459
- auditEnabled;
460
- amkEnvVar;
461
- amkKeyId;
462
- constructor(db, secretStore, secrets, tenantKeys, auditLogs, auditEnabled, amkEnvVar, amkKeyId) {
463
- this.db = db;
464
- this.secretStore = secretStore;
465
- this.secrets = secrets;
466
- this.tenantKeys = tenantKeys;
467
- this.auditLogs = auditLogs;
468
- this.auditEnabled = auditEnabled;
469
- this.amkEnvVar = amkEnvVar;
470
- this.amkKeyId = amkKeyId;
471
- }
472
- /**
473
- * Create a new SecretService instance
474
- */
475
- static async create(options) {
476
- const {
477
- db,
478
- amkEnvVar = "SMRT_SECRET_MASTER_KEY",
479
- amkKeyId = "smrt-amk-v1",
480
- auditEnabled = true
481
- } = options;
482
- const secretStore = await getSecretStore({
483
- type: "database",
484
- db,
485
- amk: {
486
- provider: "env",
487
- keyEnvVar: amkEnvVar,
488
- keyId: amkKeyId
489
- }
490
- });
491
- const baseOptions = { db };
492
- const secrets = await SecretCollection.create(baseOptions);
493
- const tenantKeys = await TenantKeyCollection.create(baseOptions);
494
- const auditLogs = await SecretAuditLogCollection.create(baseOptions);
495
- return new SecretService(
496
- db,
497
- secretStore,
498
- secrets,
499
- tenantKeys,
500
- auditLogs,
501
- auditEnabled,
502
- amkEnvVar,
503
- amkKeyId
504
- );
505
- }
506
- /**
507
- * Store a secret for the current tenant
508
- */
509
- async store(name, value, options = {}) {
510
- const tenantId = requireTenantId();
511
- const userId = this.getCurrentUserId();
512
- let isUpdate = false;
513
- try {
514
- let existing = await this.secrets.findByName(tenantId, name);
515
- if (existing && existing.tenantId !== tenantId) {
516
- existing = null;
517
- }
518
- isUpdate = existing !== null;
519
- const envelope = await this.secretStore.encrypt(tenantId, name, value, {
520
- metadata: options.metadata ? this.serializeMetadata(options.metadata) : void 0
521
- });
522
- if (existing) {
523
- existing.encryptedValue = JSON.stringify(envelope);
524
- existing.description = options.description ?? existing.description;
525
- existing.category = options.category ?? existing.category;
526
- existing.expiresAt = options.expiresAt ?? existing.expiresAt;
527
- existing.metadata = options.metadata ?? existing.metadata;
528
- await existing.save();
529
- await this.audit(
530
- existing.id ?? null,
531
- name,
532
- userId,
533
- "update",
534
- "success"
535
- );
536
- return existing;
537
- }
538
- const secret = await this.secrets.create({
539
- name,
540
- description: options.description ?? "",
541
- category: options.category ?? "",
542
- encryptedValue: JSON.stringify(envelope),
543
- keyVersion: 1,
544
- status: "active",
545
- expiresAt: options.expiresAt ?? null,
546
- metadata: options.metadata ?? {},
547
- context: tenantId,
548
- // Per-tenant uniqueness
549
- tenantId
550
- });
551
- await this.audit(secret.id ?? null, name, userId, "create", "success");
552
- return secret;
553
- } catch (error) {
554
- const classifiedError = await this.classifyTenantKeyFailure(
555
- tenantId,
556
- name,
557
- error
558
- );
559
- await this.audit(
560
- null,
561
- name,
562
- userId,
563
- isUpdate ? "update" : "create",
564
- "failure",
565
- {
566
- error: classifiedError.message
567
- }
568
- );
569
- throw classifiedError;
570
- }
571
- }
572
- /**
573
- * Store a secret for a specific tenant.
574
- *
575
- * This is useful for integrations that already resolved tenant ownership but
576
- * may be running outside the application's ambient tenant context.
577
- */
578
- async storeForTenant(tenantId, name, value, options = {}) {
579
- return withTenant({ tenantId }, () => this.store(name, value, options));
580
- }
581
- /**
582
- * Retrieve a secret for the current tenant
583
- */
584
- async retrieve(name) {
585
- const tenantId = requireTenantId();
586
- const userId = this.getCurrentUserId();
587
- let audited = false;
588
- try {
589
- const secret = await this.secrets.findByName(tenantId, name);
590
- if (!secret || secret.tenantId !== tenantId) {
591
- await this.audit(null, name, userId, "read", "failure", {
592
- error: "Secret not found"
593
- });
594
- audited = true;
595
- throw new Error(`Secret '${name}' not found`);
596
- }
597
- if (!secret.isUsable()) {
598
- const reason = secret.isExpired() ? "Secret expired" : "Secret disabled";
599
- await this.audit(secret.id ?? null, name, userId, "read", "failure", {
600
- error: reason
601
- });
602
- audited = true;
603
- throw new Error(reason);
604
- }
605
- const envelope = JSON.parse(secret.encryptedValue);
606
- const decrypted = await this.secretStore.decrypt(tenantId, envelope);
607
- const previousLastAccessedAt = secret.lastAccessedAt;
608
- const previousAccessCount = secret.accessCount;
609
- try {
610
- secret.recordAccess();
611
- await secret.save();
612
- } catch (trackingError) {
613
- secret.lastAccessedAt = previousLastAccessedAt;
614
- secret.accessCount = previousAccessCount;
615
- logger.error("Failed to update secret access tracking", {
616
- error: trackingError
617
- });
618
- }
619
- await this.audit(secret.id ?? null, name, userId, "read", "success");
620
- return {
621
- value: decrypted.value,
622
- name: secret.name,
623
- description: secret.description,
624
- category: secret.category,
625
- expiresAt: secret.expiresAt,
626
- createdAt: secret.created_at ?? /* @__PURE__ */ new Date(),
627
- lastAccessedAt: secret.lastAccessedAt,
628
- accessCount: secret.accessCount,
629
- metadata: secret.metadata
630
- };
631
- } catch (error) {
632
- const classifiedError = await this.classifyTenantKeyFailure(
633
- tenantId,
634
- name,
635
- error
636
- );
637
- if (!audited) {
638
- await this.audit(null, name, userId, "read", "failure", {
639
- error: classifiedError.message
640
- });
641
- }
642
- throw classifiedError;
643
- }
644
- }
645
- /**
646
- * Retrieve a secret for a specific tenant.
647
- */
648
- async retrieveForTenant(tenantId, name) {
649
- return withTenant({ tenantId }, () => this.retrieve(name));
650
- }
651
- /**
652
- * Diagnose tenant secret/key drift without exposing decrypted values.
653
- */
654
- async diagnoseTenantSecretKeyDrift(tenantId, options = {}) {
655
- const activeSecrets = await this.listActiveSecretRowsForDiagnosis(
656
- tenantId,
657
- options.secretNames
658
- );
659
- const tenantEncryptionKeys = await this.listTenantEncryptionKeyRows(tenantId);
660
- const smrtTenantKeyRows = await this.listSmrtTenantKeysForDiagnosis(tenantId);
661
- const smrtTenantKeys = smrtTenantKeyRows.keys;
662
- const issues = [];
663
- const activeTenantEncryptionKeys = tenantEncryptionKeys.filter(
664
- (key) => key.status === "active"
665
- );
666
- const activeSmrtTenantKeys = smrtTenantKeys.filter(
667
- (key) => key.status === "active"
668
- );
669
- const amk = this.getConfiguredAmkForDiagnosis();
670
- if (!amk.usable) {
671
- issues.push({
672
- code: "amk_unavailable",
673
- severity: "error",
674
- message: amk.error ?? `AMK ${this.amkEnvVar} is unavailable`,
675
- repairAction: "none",
676
- details: {
677
- amkEnvVar: this.amkEnvVar,
678
- amkKeyId: this.amkKeyId
679
- }
680
- });
681
- }
682
- if (activeSecrets.length > 0 && activeTenantEncryptionKeys.length === 0) {
683
- issues.push({
684
- code: "missing_active_tenant_encryption_key",
685
- severity: "error",
686
- message: "Active tenant secrets exist, but tenant_encryption_keys has no active key for encryption.",
687
- repairAction: "store-fresh-secret-value",
688
- sourceTable: "tenant_encryption_keys",
689
- details: {
690
- activeSecretCount: activeSecrets.length
691
- }
692
- });
693
- }
694
- if (smrtTenantKeyRows.error) {
695
- issues.push({
696
- code: "smrt_tenant_keys_query_failed",
697
- severity: "error",
698
- message: "Unable to query SMRT tenant_keys while diagnosing tenant secret key drift.",
699
- repairAction: "none",
700
- sourceTable: "tenant_keys",
701
- details: {
702
- error: smrtTenantKeyRows.error.message
703
- }
704
- });
705
- }
706
- if (activeTenantEncryptionKeys.length > 1) {
707
- issues.push({
708
- code: "multiple_active_tenant_encryption_keys",
709
- severity: "error",
710
- message: "tenant_encryption_keys has multiple active keys for this tenant; encryption may use an arbitrary active key.",
711
- repairAction: "none",
712
- sourceTable: "tenant_encryption_keys",
713
- details: {
714
- activeTenantEncryptionKeyCount: activeTenantEncryptionKeys.length
715
- }
716
- });
717
- }
718
- const activeKeyChecks = [];
719
- for (const key of tenantEncryptionKeys) {
720
- const check = amk.value ? this.checkWrappedKey(key.wrapped_key, amk.value) : { usable: false, error: amk.error };
721
- if (key.status === "active") {
722
- activeKeyChecks.push(check);
723
- }
724
- if (key.status === "active" && key.amk_key_id !== this.amkKeyId) {
725
- issues.push({
726
- code: "active_tenant_encryption_key_amk_mismatch",
727
- severity: "warning",
728
- message: "Active tenant_encryption_keys row was wrapped by a different AMK key id than this SecretService is configured to use.",
729
- repairAction: "none",
730
- keyId: key.id,
731
- sourceTable: "tenant_encryption_keys",
732
- details: {
733
- rowAmkKeyId: key.amk_key_id,
734
- configuredAmkKeyId: this.amkKeyId
735
- }
736
- });
737
- }
738
- if (key.status === "active" && !check.usable && amk.value) {
739
- issues.push({
740
- code: "active_tenant_encryption_key_unwrap_failed",
741
- severity: "error",
742
- message: "Active tenant_encryption_keys row cannot be unwrapped by the currently configured AMK.",
743
- repairAction: "delete-unusable-tenant-encryption-key",
744
- keyId: key.id,
745
- sourceTable: "tenant_encryption_keys",
746
- details: {
747
- version: key.version,
748
- error: check.error ?? null
749
- }
750
- });
751
- }
752
- }
753
- const usableActiveTenantEncryptionKeyCount = activeKeyChecks.filter(
754
- (check) => check.usable
755
- ).length;
756
- if (activeSecrets.length > 0 && usableActiveTenantEncryptionKeyCount === 0) {
757
- issues.push({
758
- code: "active_secrets_without_usable_active_key",
759
- severity: "error",
760
- message: "Active secrets exist, but no active tenant_encryption_keys row can be used with the current AMK.",
761
- repairAction: "store-fresh-secret-value",
762
- sourceTable: "tenant_encryption_keys",
763
- details: {
764
- activeSecretCount: activeSecrets.length,
765
- activeTenantEncryptionKeyCount: activeTenantEncryptionKeys.length
766
- }
767
- });
768
- }
769
- const keyFingerprintToRow = /* @__PURE__ */ new Map();
770
- for (const key of tenantEncryptionKeys) {
771
- const fingerprint = this.getWrappedKeyFingerprint(key.wrapped_key);
772
- if (fingerprint) {
773
- keyFingerprintToRow.set(fingerprint, key);
774
- }
775
- }
776
- for (const secret of activeSecrets) {
777
- const envelope = this.parseSecretEnvelopeForDiagnosis(secret, issues);
778
- if (!envelope) continue;
779
- const envelopeFingerprint = this.getWrappedKeyFingerprint(
780
- envelope.wrappedKey
781
- );
782
- const envelopeCheck = amk.value ? this.checkWrappedKey(envelope.wrappedKey, amk.value) : {
783
- usable: false,
784
- error: amk.error,
785
- fingerprint: envelopeFingerprint
786
- };
787
- if (!envelopeCheck.fingerprint) {
788
- issues.push({
789
- code: "secret_envelope_invalid_wrapped_key",
790
- severity: "error",
791
- message: "Secret encryptedValue contains an invalid wrapped key format.",
792
- repairAction: "delete-unrecoverable-secret",
793
- secretId: secret.id,
794
- secretName: secret.name,
795
- sourceTable: "secrets",
796
- details: {
797
- error: envelopeCheck.error ?? null
798
- }
799
- });
800
- continue;
801
- }
802
- const matchingKey = keyFingerprintToRow.get(envelopeCheck.fingerprint);
803
- if (!matchingKey) {
804
- issues.push({
805
- code: "secret_envelope_missing_tenant_encryption_key",
806
- severity: "error",
807
- message: "Secret envelope does not match any tenant_encryption_keys row for this tenant.",
808
- repairAction: !amk.value ? "none" : envelopeCheck.usable ? "none" : "delete-unrecoverable-secret",
809
- secretId: secret.id,
810
- secretName: secret.name,
811
- sourceTable: "secrets"
812
- });
813
- }
814
- if (!envelopeCheck.usable && amk.value) {
815
- issues.push({
816
- code: "secret_envelope_unwrap_failed",
817
- severity: "error",
818
- message: "Secret envelope cannot be unwrapped by the currently configured AMK.",
819
- repairAction: "delete-unrecoverable-secret",
820
- secretId: secret.id,
821
- secretName: secret.name,
822
- keyId: matchingKey?.id,
823
- sourceTable: "secrets",
824
- details: {
825
- error: envelopeCheck.error ?? null
826
- }
827
- });
828
- }
829
- }
830
- if (activeSecrets.length > 0 && tenantEncryptionKeys.length > 0 && smrtTenantKeys.length === 0 && !smrtTenantKeyRows.error) {
831
- issues.push({
832
- code: "smrt_tenant_keys_not_mirrored",
833
- severity: "info",
834
- message: "SMRT tenant_keys has no rows for this tenant, while the lower-level tenant_encryption_keys table does. SecretService uses tenant_encryption_keys for encryption.",
835
- repairAction: "none",
836
- sourceTable: "tenant_keys"
837
- });
838
- }
839
- return {
840
- tenantId,
841
- checkedAt: /* @__PURE__ */ new Date(),
842
- ok: !issues.some((issue) => issue.severity === "error"),
843
- summary: {
844
- activeSecretCount: activeSecrets.length,
845
- tenantEncryptionKeyCount: tenantEncryptionKeys.length,
846
- activeTenantEncryptionKeyCount: activeTenantEncryptionKeys.length,
847
- usableActiveTenantEncryptionKeyCount,
848
- smrtTenantKeyCount: smrtTenantKeys.length,
849
- activeSmrtTenantKeyCount: activeSmrtTenantKeys.length
850
- },
851
- issues
852
- };
853
- }
854
- /**
855
- * Diagnose drift for the current tenant context.
856
- */
857
- async diagnoseCurrentTenantSecretKeyDrift(options = {}) {
858
- return this.diagnoseTenantSecretKeyDrift(requireTenantId(), options);
859
- }
860
- /**
861
- * Delete unrecoverable secret/key rows identified by diagnosis.
862
- *
863
- * This never attempts to recover or expose secret values. Use dryRun first
864
- * to preview destructive changes.
865
- */
866
- async repairTenantSecretKeyDrift(tenantId, options = {}) {
867
- const dryRun = options.dryRun ?? false;
868
- const before = await this.diagnoseTenantSecretKeyDrift(tenantId, options);
869
- const secretIds = /* @__PURE__ */ new Set();
870
- const secretNames = /* @__PURE__ */ new Map();
871
- const tenantEncryptionKeyIds = /* @__PURE__ */ new Set();
872
- for (const issue of before.issues) {
873
- if (issue.repairAction === "delete-unrecoverable-secret" && issue.secretId) {
874
- secretIds.add(issue.secretId);
875
- if (issue.secretName) {
876
- secretNames.set(issue.secretId, issue.secretName);
877
- }
878
- }
879
- if (issue.repairAction === "delete-unusable-tenant-encryption-key" && issue.keyId) {
880
- tenantEncryptionKeyIds.add(issue.keyId);
881
- }
882
- }
883
- const wouldDeleteSecrets = secretIds.size;
884
- const wouldDeleteTenantEncryptionKeys = tenantEncryptionKeyIds.size;
885
- const wouldDeleteUnrecoverableData = wouldDeleteSecrets + wouldDeleteTenantEncryptionKeys > 0;
886
- if (!dryRun && wouldDeleteUnrecoverableData && !options.confirmDeleteUnrecoverableData) {
887
- throw new Error(
888
- "repairTenantSecretKeyDrift requires confirmDeleteUnrecoverableData: true before deleting encrypted secrets or tenant key rows."
889
- );
890
- }
891
- let deletedSecrets = 0;
892
- let deletedTenantEncryptionKeys = 0;
893
- if (!dryRun) {
894
- const runDeletes = async (db) => {
895
- const deletedSecretRows = await this.deleteRowsByIds(
896
- "secrets",
897
- tenantId,
898
- secretIds,
899
- db
900
- );
901
- const deletedTenantEncryptionKeyRows = await this.deleteRowsByIds(
902
- "tenant_encryption_keys",
903
- tenantId,
904
- tenantEncryptionKeyIds,
905
- db
906
- );
907
- return {
908
- deletedSecrets: deletedSecretRows,
909
- deletedTenantEncryptionKeys: deletedTenantEncryptionKeyRows
910
- };
911
- };
912
- const txDb = this.db;
913
- const deleteResult = typeof txDb.transaction === "function" ? await txDb.transaction((db) => runDeletes(db)) : await runDeletes(this.db);
914
- deletedSecrets = deleteResult.deletedSecrets;
915
- deletedTenantEncryptionKeys = deleteResult.deletedTenantEncryptionKeys;
916
- await this.auditSecretDriftRepairDeletes(
917
- tenantId,
918
- secretIds,
919
- secretNames
920
- );
921
- }
922
- const after = dryRun ? before : await this.diagnoseTenantSecretKeyDrift(tenantId, options);
923
- return {
924
- tenantId,
925
- dryRun,
926
- issuesBefore: before.issues,
927
- remainingIssues: after.issues,
928
- wouldDeleteSecrets,
929
- wouldDeleteTenantEncryptionKeys,
930
- deletedSecrets,
931
- deletedTenantEncryptionKeys,
932
- secretNames: Array.from(secretNames.values()).sort(),
933
- tenantEncryptionKeyIds: Array.from(tenantEncryptionKeyIds).sort()
934
- };
935
- }
936
- /**
937
- * List secrets for the current tenant (names only, not values)
938
- */
939
- async list(options = {}) {
940
- return this.secrets.listSecrets(requireTenantId(), {
941
- category: options.category,
942
- status: "active"
943
- });
944
- }
945
- /**
946
- * Delete a secret
947
- */
948
- async delete(name) {
949
- const tenantId = requireTenantId();
950
- const userId = this.getCurrentUserId();
951
- const secret = await this.secrets.findByName(tenantId, name);
952
- if (!secret || secret.tenantId !== tenantId) {
953
- return false;
954
- }
955
- try {
956
- await secret.delete();
957
- await this.audit(secret.id ?? null, name, userId, "delete", "success");
958
- return true;
959
- } catch (error) {
960
- await this.audit(secret.id ?? null, name, userId, "delete", "failure", {
961
- error: error.message
962
- });
963
- throw error;
964
- }
965
- }
966
- /**
967
- * Disable a secret (soft delete)
968
- */
969
- async disable(name) {
970
- const tenantId = requireTenantId();
971
- const userId = this.getCurrentUserId();
972
- const secret = await this.secrets.findByName(tenantId, name);
973
- if (!secret || secret.tenantId !== tenantId) {
974
- return false;
975
- }
976
- secret.disable();
977
- await secret.save();
978
- await this.audit(secret.id ?? null, name, userId, "disable", "success");
979
- return true;
980
- }
981
- /**
982
- * Enable a disabled secret
983
- */
984
- async enable(name) {
985
- const tenantId = requireTenantId();
986
- const userId = this.getCurrentUserId();
987
- const secret = await this.secrets.findByName(tenantId, name);
988
- if (!secret || secret.tenantId !== tenantId) {
989
- return false;
990
- }
991
- secret.enable();
992
- await secret.save();
993
- await this.audit(secret.id ?? null, name, userId, "enable", "success");
994
- return true;
995
- }
996
- /**
997
- * Rotate the tenant's encryption key
998
- *
999
- * This creates a new TDEK and marks the old one as retired.
1000
- * Existing secrets remain encrypted with the old key and can still
1001
- * be decrypted (the old key is kept in retired state).
1002
- *
1003
- * For full re-encryption, call reencryptAll() after rotation.
1004
- */
1005
- async rotateKey() {
1006
- const tenantId = requireTenantId();
1007
- const userId = this.getCurrentUserId();
1008
- try {
1009
- await this.secretStore.rotateTenantKey(tenantId);
1010
- await this.audit(null, "", userId, "rotate_key", "success", {
1011
- tenantId
1012
- });
1013
- } catch (error) {
1014
- await this.audit(null, "", userId, "rotate_key", "failure", {
1015
- tenantId,
1016
- error: error.message
1017
- });
1018
- throw error;
1019
- }
1020
- }
1021
- /**
1022
- * Re-encrypt all secrets with the current active key
1023
- *
1024
- * Call this after key rotation to ensure all secrets use the new key.
1025
- * This is optional but recommended for security.
1026
- */
1027
- async reencryptAll() {
1028
- const tenantId = requireTenantId();
1029
- const userId = this.getCurrentUserId();
1030
- const secrets = await this.secrets.list({ where: { tenantId } });
1031
- let success = 0;
1032
- let failed = 0;
1033
- for (const secret of secrets) {
1034
- try {
1035
- const envelope = JSON.parse(secret.encryptedValue);
1036
- const decrypted = await this.secretStore.decrypt(tenantId, envelope);
1037
- const newEnvelope = await this.secretStore.encrypt(
1038
- tenantId,
1039
- secret.name,
1040
- decrypted.value
1041
- );
1042
- secret.encryptedValue = JSON.stringify(newEnvelope);
1043
- await secret.save();
1044
- success++;
1045
- } catch (error) {
1046
- failed++;
1047
- await this.audit(
1048
- secret.id ?? null,
1049
- secret.name,
1050
- userId,
1051
- "update",
1052
- "failure",
1053
- {
1054
- action: "reencrypt",
1055
- error: error.message
1056
- }
1057
- );
1058
- }
1059
- }
1060
- return { success, failed };
1061
- }
1062
- /**
1063
- * Get audit logs for the current tenant
1064
- */
1065
- async getAuditLogs(options = {}) {
1066
- return this.auditLogs.listLogs({
1067
- // Scope to the current tenant (issue #1501): audit logs reference
1068
- // secret names and must not leak across tenants.
1069
- tenantId: requireTenantId(),
1070
- secretName: options.secretName,
1071
- limit: options.limit ?? 100
1072
- });
1073
- }
1074
- /**
1075
- * Get secret categories for the current tenant
1076
- */
1077
- async getCategories() {
1078
- return this.secrets.getCategories(requireTenantId());
1079
- }
1080
- /**
1081
- * Check if a secret exists for the current tenant
1082
- */
1083
- async exists(name) {
1084
- const tenantId = requireTenantId();
1085
- const secret = await this.secrets.findByName(tenantId, name);
1086
- return secret !== null && secret.tenantId === tenantId;
1087
- }
1088
- // Private methods
1089
- async listActiveSecretRowsForDiagnosis(tenantId, secretNames) {
1090
- const params = [tenantId];
1091
- let nameFilter = "";
1092
- if (secretNames && secretNames.length > 0) {
1093
- const placeholders = secretNames.map(() => "?").join(", ");
1094
- nameFilter = ` AND name IN (${placeholders})`;
1095
- params.push(...secretNames);
1096
- }
1097
- const result = await this.db.query(
1098
- `
1099
- SELECT id, name, encrypted_value, status, tenant_id
1100
- FROM "secrets"
1101
- WHERE tenant_id = ? AND status = 'active'${nameFilter}
1102
- ORDER BY name ASC
1103
- `,
1104
- ...params
1105
- );
1106
- return this.rowsFromResult(result);
1107
- }
1108
- async listTenantEncryptionKeyRows(tenantId) {
1109
- const result = await this.db.query(
1110
- `
1111
- SELECT id, tenant_id, wrapped_key, amk_key_id, status, version,
1112
- rotate_after, retired_at, created_at, updated_at
1113
- FROM "tenant_encryption_keys"
1114
- WHERE tenant_id = ?
1115
- ORDER BY version DESC
1116
- `,
1117
- tenantId
1118
- );
1119
- return this.rowsFromResult(result);
1120
- }
1121
- async listSmrtTenantKeysForDiagnosis(tenantId) {
1122
- try {
1123
- return { keys: await this.tenantKeys.listKeyVersions(tenantId) };
1124
- } catch (error) {
1125
- return { keys: [], error: this.toError(error) };
1126
- }
1127
- }
1128
- getConfiguredAmkForDiagnosis() {
1129
- const keyHex = process.env[this.amkEnvVar];
1130
- if (!keyHex) {
1131
- return {
1132
- usable: false,
1133
- error: `Application Master Key not found in environment variable: ${this.amkEnvVar}`
1134
- };
1135
- }
1136
- try {
1137
- return {
1138
- usable: true,
1139
- value: EnvelopeEncryption.parseHexKey(keyHex)
1140
- };
1141
- } catch (error) {
1142
- return {
1143
- usable: false,
1144
- error: `Invalid AMK in ${this.amkEnvVar}: ${this.toError(error).message}`
1145
- };
1146
- }
1147
- }
1148
- checkWrappedKey(wrappedKey, amk) {
1149
- const fingerprint = this.getWrappedKeyFingerprint(wrappedKey);
1150
- try {
1151
- const parsed = EnvelopeEncryption.parseWrappedKey(wrappedKey);
1152
- const dataKey = EnvelopeEncryption.unwrapKey(
1153
- parsed.wrappedKey,
1154
- parsed.iv,
1155
- parsed.authTag,
1156
- amk
1157
- );
1158
- dataKey.fill(0);
1159
- return { usable: true, fingerprint };
1160
- } catch (error) {
1161
- return {
1162
- usable: false,
1163
- fingerprint,
1164
- error: this.toError(error).message
1165
- };
1166
- }
1167
- }
1168
- getWrappedKeyFingerprint(wrappedKey) {
1169
- try {
1170
- return EnvelopeEncryption.parseWrappedKey(wrappedKey).wrappedKey;
1171
- } catch {
1172
- return void 0;
1173
- }
1174
- }
1175
- parseSecretEnvelopeForDiagnosis(secret, issues) {
1176
- try {
1177
- return JSON.parse(secret.encrypted_value);
1178
- } catch (error) {
1179
- issues.push({
1180
- code: "secret_envelope_invalid_json",
1181
- severity: "error",
1182
- message: "Secret encryptedValue is not valid EncryptedEnvelope JSON.",
1183
- repairAction: "delete-unrecoverable-secret",
1184
- secretId: secret.id,
1185
- secretName: secret.name,
1186
- sourceTable: "secrets",
1187
- details: {
1188
- error: this.toError(error).message
1189
- }
1190
- });
1191
- return null;
1192
- }
1193
- }
1194
- async deleteRowsByIds(tableName, tenantId, ids, db = this.db) {
1195
- if (ids.size === 0) return 0;
1196
- const idList = Array.from(ids);
1197
- const placeholders = idList.map(() => "?").join(", ");
1198
- const result = await db.query(
1199
- `DELETE FROM "${tableName}" WHERE tenant_id = ? AND id IN (${placeholders})`,
1200
- tenantId,
1201
- ...idList
1202
- );
1203
- return typeof result.rowCount === "number" ? result.rowCount : idList.length;
1204
- }
1205
- async auditSecretDriftRepairDeletes(tenantId, secretIds, secretNames) {
1206
- if (secretIds.size === 0) return;
1207
- const userId = this.getCurrentUserId();
1208
- await withTenant({ tenantId }, async () => {
1209
- for (const secretId of secretIds) {
1210
- await this.audit(
1211
- secretId,
1212
- secretNames.get(secretId) ?? "",
1213
- userId,
1214
- "delete",
1215
- "success",
1216
- {
1217
- action: "repairTenantSecretKeyDrift",
1218
- reason: "unrecoverable-secret-key-drift"
1219
- }
1220
- );
1221
- }
1222
- });
1223
- }
1224
- rowsFromResult(result) {
1225
- if (Array.isArray(result)) return result;
1226
- if (result && typeof result === "object" && Array.isArray(result.rows)) {
1227
- return result.rows;
1228
- }
1229
- return [];
1230
- }
1231
- async classifyTenantKeyFailure(tenantId, secretName, error) {
1232
- const normalized = this.toError(error);
1233
- if (!this.shouldClassifyTenantKeyFailure(normalized)) {
1234
- return normalized;
1235
- }
1236
- try {
1237
- const report = await this.diagnoseTenantSecretKeyDrift(tenantId, {
1238
- secretNames: [secretName]
1239
- });
1240
- const errorCodes = report.issues.filter((issue) => issue.severity === "error").map((issue) => issue.code);
1241
- if (errorCodes.length === 0) {
1242
- return normalized;
1243
- }
1244
- return new SecretKeyDriftError(
1245
- `Secret '${secretName}' for tenant '${tenantId}' failed because secret key drift was detected: ${[
1246
- ...new Set(errorCodes)
1247
- ].join(
1248
- ", "
1249
- )}. Run diagnoseTenantSecretKeyDrift() for details and repairTenantSecretKeyDrift() for explicit cleanup of unrecoverable rows.`,
1250
- tenantId,
1251
- report,
1252
- normalized
1253
- );
1254
- } catch {
1255
- return normalized;
1256
- }
1257
- }
1258
- shouldClassifyTenantKeyFailure(error) {
1259
- const code = this.getSecretErrorCode(error);
1260
- if (error instanceof AMKUnavailableError || code === "AMK_UNAVAILABLE") {
1261
- return false;
1262
- }
1263
- return error instanceof TenantKeyMissingError || error instanceof EncryptionError || error instanceof DecryptionError || code === "TENANT_KEY_MISSING" || code === "ENCRYPTION_FAILED" || code === "DECRYPTION_FAILED";
1264
- }
1265
- getSecretErrorCode(error) {
1266
- const code = error.code;
1267
- return typeof code === "string" ? code : void 0;
1268
- }
1269
- toError(error) {
1270
- return error instanceof Error ? error : new Error(String(error));
1271
- }
1272
- getCurrentUserId() {
1273
- const ctx = getCurrentTenant();
1274
- return ctx?.userId ?? "system";
1275
- }
1276
- async audit(secretId, secretName, userId, action, result, details) {
1277
- if (!this.auditEnabled) return;
1278
- try {
1279
- const tenantId = getCurrentTenant()?.tenantId ?? null;
1280
- const log = await this.auditLogs.create(
1281
- createAuditEntry({
1282
- secretId,
1283
- secretName,
1284
- userId,
1285
- action,
1286
- result,
1287
- details,
1288
- tenantId
1289
- })
1290
- );
1291
- await log.save();
1292
- } catch (error) {
1293
- logger.error("Failed to write audit log", { error });
1294
- }
1295
- }
1296
- serializeMetadata(metadata) {
1297
- const result = {};
1298
- for (const [key, value] of Object.entries(metadata)) {
1299
- result[key] = typeof value === "string" ? value : JSON.stringify(value);
1300
- }
1301
- return result;
1302
- }
1303
- }
1304
- export {
1305
- SecretAuditLogCollection as S,
1306
- TenantKeyCollection as T,
1307
- SecretCollection as a,
1308
- SecretKeyDriftError as b,
1309
- SecretService as c
1310
- };
1311
- //# sourceMappingURL=SecretService-Ty8THRAf.js.map