@digilogiclabs/platform-core 1.3.0 → 1.4.0

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.
package/dist/index.js CHANGED
@@ -409,10 +409,11 @@ var init_IAI = __esm({
409
409
  });
410
410
 
411
411
  // src/interfaces/IRAG.ts
412
- var ChunkingPresets, MemoryRAG;
412
+ var import_crypto13, ChunkingPresets, MemoryRAG;
413
413
  var init_IRAG = __esm({
414
414
  "src/interfaces/IRAG.ts"() {
415
415
  "use strict";
416
+ import_crypto13 = require("crypto");
416
417
  ChunkingPresets = {
417
418
  default: {
418
419
  strategy: "recursive",
@@ -538,7 +539,7 @@ var init_IRAG = __esm({
538
539
  }
539
540
  async ingestOne(collection, document, options) {
540
541
  const startTime = Date.now();
541
- const docId = `doc_${Date.now()}_${Math.random().toString(36).substring(7)}`;
542
+ const docId = `doc_${Date.now()}_${(0, import_crypto13.randomBytes)(4).toString("hex")}`;
542
543
  const now = /* @__PURE__ */ new Date();
543
544
  try {
544
545
  const col = await this.getCollection(collection);
@@ -1107,10 +1108,11 @@ function toPoolConfig(config) {
1107
1108
  }
1108
1109
  return poolConfig;
1109
1110
  }
1110
- var PostgresDatabase, TransactionDatabase, PostgresQueryBuilder;
1111
+ var import_crypto22, PostgresDatabase, TransactionDatabase, PostgresQueryBuilder;
1111
1112
  var init_PostgresDatabase = __esm({
1112
1113
  "src/adapters/postgres/PostgresDatabase.ts"() {
1113
1114
  "use strict";
1115
+ import_crypto22 = require("crypto");
1114
1116
  PostgresDatabase = class _PostgresDatabase {
1115
1117
  pool;
1116
1118
  config;
@@ -1231,7 +1233,7 @@ var init_PostgresDatabase = __esm({
1231
1233
  }
1232
1234
  }
1233
1235
  async transaction(fn) {
1234
- const savepointName = `sp_${Date.now()}_${Math.random().toString(36).slice(2)}`;
1236
+ const savepointName = `sp_${Date.now()}_${(0, import_crypto22.randomBytes)(4).toString("hex")}`;
1235
1237
  try {
1236
1238
  await this.client.query(`SAVEPOINT ${savepointName}`);
1237
1239
  const result = await fn(this);
@@ -5470,11 +5472,12 @@ __export(PineconeRAG_exports, {
5470
5472
  function createPineconeRAG(config) {
5471
5473
  return new PineconeRAG(config);
5472
5474
  }
5473
- var PineconeRAG;
5475
+ var import_crypto23, PineconeRAG;
5474
5476
  var init_PineconeRAG = __esm({
5475
5477
  "src/adapters/pinecone/PineconeRAG.ts"() {
5476
5478
  "use strict";
5477
5479
  init_IRAG();
5480
+ import_crypto23 = require("crypto");
5478
5481
  PineconeRAG = class {
5479
5482
  client = null;
5480
5483
  index = null;
@@ -5624,7 +5627,7 @@ var init_PineconeRAG = __esm({
5624
5627
  throw new Error(`Collection ${collection} not found`);
5625
5628
  }
5626
5629
  const now = /* @__PURE__ */ new Date();
5627
- const documentId = `doc_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
5630
+ const documentId = `doc_${Date.now()}_${(0, import_crypto23.randomBytes)(4).toString("hex")}`;
5628
5631
  const doc = {
5629
5632
  id: documentId,
5630
5633
  source: document.source,
@@ -6191,11 +6194,12 @@ __export(WeaviateRAG_exports, {
6191
6194
  function createWeaviateRAG(config) {
6192
6195
  return new WeaviateRAG(config);
6193
6196
  }
6194
- var WeaviateRAG;
6197
+ var import_crypto24, WeaviateRAG;
6195
6198
  var init_WeaviateRAG = __esm({
6196
6199
  "src/adapters/weaviate/WeaviateRAG.ts"() {
6197
6200
  "use strict";
6198
6201
  init_IRAG();
6202
+ import_crypto24 = require("crypto");
6199
6203
  WeaviateRAG = class {
6200
6204
  client = null;
6201
6205
  config;
@@ -6382,7 +6386,7 @@ var init_WeaviateRAG = __esm({
6382
6386
  const client = await this.getClient();
6383
6387
  const className = this.getClassName(collection);
6384
6388
  const now = /* @__PURE__ */ new Date();
6385
- const documentId = `doc_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
6389
+ const documentId = `doc_${Date.now()}_${(0, import_crypto24.randomBytes)(4).toString("hex")}`;
6386
6390
  const doc = {
6387
6391
  id: documentId,
6388
6392
  source: document.source,
@@ -6957,6 +6961,177 @@ var init_WeaviateRAG = __esm({
6957
6961
  }
6958
6962
  });
6959
6963
 
6964
+ // src/adapters/node-crypto/NodeCrypto.ts
6965
+ var NodeCrypto_exports = {};
6966
+ __export(NodeCrypto_exports, {
6967
+ NodeCrypto: () => NodeCrypto
6968
+ });
6969
+ var import_crypto25, NodeCrypto;
6970
+ var init_NodeCrypto = __esm({
6971
+ "src/adapters/node-crypto/NodeCrypto.ts"() {
6972
+ "use strict";
6973
+ import_crypto25 = require("crypto");
6974
+ NodeCrypto = class {
6975
+ masterKey;
6976
+ hmacKey;
6977
+ keys = /* @__PURE__ */ new Map();
6978
+ activeKeyId;
6979
+ keyCounter = 0;
6980
+ constructor(config) {
6981
+ if (!config.masterKey || config.masterKey.length < 64) {
6982
+ throw new Error(
6983
+ "NodeCrypto requires a 256-bit master key (64 hex characters)"
6984
+ );
6985
+ }
6986
+ this.masterKey = Buffer.from(config.masterKey, "hex");
6987
+ this.hmacKey = config.hmacKey ? Buffer.from(config.hmacKey, "hex") : Buffer.from(
6988
+ (0, import_crypto25.hkdfSync)("sha256", this.masterKey, "", "hmac-key", 32)
6989
+ );
6990
+ const keyId = this.generateKeyId();
6991
+ const dek = this.deriveDEK(keyId);
6992
+ this.keys.set(keyId, {
6993
+ id: keyId,
6994
+ dek,
6995
+ status: "active",
6996
+ createdAt: /* @__PURE__ */ new Date()
6997
+ });
6998
+ this.activeKeyId = keyId;
6999
+ }
7000
+ async encrypt(plaintext, options) {
7001
+ const keyId = options?.keyId || this.activeKeyId;
7002
+ const stored = this.keys.get(keyId);
7003
+ if (!stored) {
7004
+ throw new Error(`Key not found: ${keyId}`);
7005
+ }
7006
+ if (stored.status === "retired") {
7007
+ throw new Error(`Key is retired and cannot encrypt: ${keyId}`);
7008
+ }
7009
+ if (stored.status === "decrypt-only" && !options?.keyId) {
7010
+ throw new Error(`Key is decrypt-only: ${keyId}`);
7011
+ }
7012
+ const iv = (0, import_crypto25.randomBytes)(12);
7013
+ const cipher = (0, import_crypto25.createCipheriv)("aes-256-gcm", stored.dek, iv);
7014
+ if (options?.aad) {
7015
+ cipher.setAAD(Buffer.from(options.aad, "utf8"));
7016
+ }
7017
+ const encrypted = Buffer.concat([
7018
+ cipher.update(plaintext, "utf8"),
7019
+ cipher.final()
7020
+ ]);
7021
+ const tag = cipher.getAuthTag();
7022
+ return {
7023
+ ciphertext: encrypted.toString("base64"),
7024
+ iv: iv.toString("base64"),
7025
+ tag: tag.toString("base64"),
7026
+ keyId,
7027
+ algorithm: "aes-256-gcm",
7028
+ version: 1
7029
+ };
7030
+ }
7031
+ async decrypt(field, options) {
7032
+ const stored = this.keys.get(field.keyId);
7033
+ if (!stored) {
7034
+ throw new Error(`Key not found: ${field.keyId}`);
7035
+ }
7036
+ if (stored.status === "retired") {
7037
+ throw new Error(`Key is retired and cannot decrypt: ${field.keyId}`);
7038
+ }
7039
+ const decipher = (0, import_crypto25.createDecipheriv)(
7040
+ "aes-256-gcm",
7041
+ stored.dek,
7042
+ Buffer.from(field.iv, "base64")
7043
+ );
7044
+ decipher.setAuthTag(Buffer.from(field.tag, "base64"));
7045
+ if (options?.aad) {
7046
+ decipher.setAAD(Buffer.from(options.aad, "utf8"));
7047
+ }
7048
+ const decrypted = Buffer.concat([
7049
+ decipher.update(Buffer.from(field.ciphertext, "base64")),
7050
+ decipher.final()
7051
+ ]);
7052
+ return decrypted.toString("utf8");
7053
+ }
7054
+ async encryptDeterministic(plaintext, options) {
7055
+ const hash = await this.computeHash(plaintext);
7056
+ const encrypted = await this.encrypt(plaintext, options);
7057
+ return { hash, encrypted };
7058
+ }
7059
+ async computeHash(plaintext) {
7060
+ return (0, import_crypto25.createHmac)("sha256", this.hmacKey).update(plaintext, "utf8").digest("hex");
7061
+ }
7062
+ async encryptBatch(fields, options) {
7063
+ const result = {};
7064
+ for (const [key, value] of Object.entries(fields)) {
7065
+ result[key] = await this.encrypt(value, options);
7066
+ }
7067
+ return result;
7068
+ }
7069
+ async decryptBatch(fields, options) {
7070
+ const result = {};
7071
+ for (const [key, value] of Object.entries(fields)) {
7072
+ result[key] = await this.decrypt(value, options);
7073
+ }
7074
+ return result;
7075
+ }
7076
+ async rotateKey() {
7077
+ const previousKeyId = this.activeKeyId;
7078
+ const currentKey = this.keys.get(previousKeyId);
7079
+ if (currentKey) {
7080
+ currentKey.status = "decrypt-only";
7081
+ }
7082
+ const newKeyId = this.generateKeyId();
7083
+ const dek = this.deriveDEK(newKeyId);
7084
+ this.keys.set(newKeyId, {
7085
+ id: newKeyId,
7086
+ dek,
7087
+ status: "active",
7088
+ createdAt: /* @__PURE__ */ new Date()
7089
+ });
7090
+ this.activeKeyId = newKeyId;
7091
+ return { newKeyId, previousKeyId };
7092
+ }
7093
+ async reEncrypt(field, options) {
7094
+ const plaintext = await this.decrypt(field);
7095
+ return this.encrypt(plaintext, options);
7096
+ }
7097
+ async listKeys() {
7098
+ return Array.from(this.keys.values()).map((k) => ({
7099
+ keyId: k.id,
7100
+ createdAt: k.createdAt,
7101
+ status: k.status
7102
+ }));
7103
+ }
7104
+ async getActiveKeyId() {
7105
+ return this.activeKeyId;
7106
+ }
7107
+ async healthCheck() {
7108
+ try {
7109
+ const testPlain = "health-check-" + (0, import_crypto25.randomBytes)(4).toString("hex");
7110
+ const encrypted = await this.encrypt(testPlain);
7111
+ const decrypted = await this.decrypt(encrypted);
7112
+ return decrypted === testPlain;
7113
+ } catch {
7114
+ return false;
7115
+ }
7116
+ }
7117
+ /**
7118
+ * Derive a Data Encryption Key from the master key using HKDF.
7119
+ */
7120
+ deriveDEK(keyId) {
7121
+ return Buffer.from(
7122
+ (0, import_crypto25.hkdfSync)("sha256", this.masterKey, keyId, "dek-derivation", 32)
7123
+ );
7124
+ }
7125
+ generateKeyId() {
7126
+ this.keyCounter++;
7127
+ const timestamp = Date.now().toString(36);
7128
+ const random = (0, import_crypto25.randomBytes)(4).toString("hex");
7129
+ return `dek_${timestamp}_${random}_${this.keyCounter}`;
7130
+ }
7131
+ };
7132
+ }
7133
+ });
7134
+
6960
7135
  // src/index.ts
6961
7136
  var src_exports = {};
6962
7137
  __export(src_exports, {
@@ -6984,6 +7159,7 @@ __export(src_exports, {
6984
7159
  ConsoleEmail: () => ConsoleEmail,
6985
7160
  ConsoleLogger: () => ConsoleLogger,
6986
7161
  CronPresets: () => CronPresets,
7162
+ CryptoConfigSchema: () => CryptoConfigSchema,
6987
7163
  DEFAULT_BULKHEAD_OPTIONS: () => DEFAULT_BULKHEAD_OPTIONS,
6988
7164
  DEFAULT_CIRCUIT_BREAKER_OPTIONS: () => DEFAULT_CIRCUIT_BREAKER_OPTIONS,
6989
7165
  DEFAULT_RETRY_OPTIONS: () => DEFAULT_RETRY_OPTIONS,
@@ -7015,6 +7191,7 @@ __export(src_exports, {
7015
7191
  MemoryBilling: () => MemoryBilling,
7016
7192
  MemoryCache: () => MemoryCache,
7017
7193
  MemoryCompliance: () => MemoryCompliance,
7194
+ MemoryCrypto: () => MemoryCrypto,
7018
7195
  MemoryDatabase: () => MemoryDatabase,
7019
7196
  MemoryDevPortal: () => MemoryDevPortal,
7020
7197
  MemoryDevice: () => MemoryDevice,
@@ -7036,6 +7213,7 @@ __export(src_exports, {
7036
7213
  MetricsConfigSchema: () => MetricsConfigSchema,
7037
7214
  MiddlewareConfigSchema: () => MiddlewareConfigSchema,
7038
7215
  Migrator: () => Migrator,
7216
+ NodeCrypto: () => NodeCrypto,
7039
7217
  NoopLogger: () => NoopLogger,
7040
7218
  NoopMetrics: () => NoopMetrics,
7041
7219
  NoopTracing: () => NoopTracing,
@@ -7063,6 +7241,8 @@ __export(src_exports, {
7063
7241
  RetryPredicates: () => RetryPredicates,
7064
7242
  S3Storage: () => S3Storage,
7065
7243
  SQL: () => SQL,
7244
+ SecurityConfigSchema: () => SecurityConfigSchema,
7245
+ SecurityHeaderPresets: () => SecurityHeaderPresets,
7066
7246
  SmtpEmail: () => SmtpEmail,
7067
7247
  StorageConfigSchema: () => StorageConfigSchema,
7068
7248
  StorageProviderSchema: () => StorageProviderSchema,
@@ -7152,6 +7332,7 @@ __export(src_exports, {
7152
7332
  generatePaymentId: () => generatePaymentId,
7153
7333
  generateScheduleId: () => generateScheduleId,
7154
7334
  generateSecureToken: () => generateSecureToken,
7335
+ generateSecurityHeaders: () => generateSecurityHeaders,
7155
7336
  generateVersion: () => generateVersion,
7156
7337
  generateWebhookId: () => generateWebhookId,
7157
7338
  generateWebhookSecret: () => generateWebhookSecret,
@@ -7199,6 +7380,7 @@ __export(src_exports, {
7199
7380
  module.exports = __toCommonJS(src_exports);
7200
7381
 
7201
7382
  // src/interfaces/IQueue.ts
7383
+ var import_crypto = require("crypto");
7202
7384
  function calculateBackoff(attempt, options) {
7203
7385
  if (options.type === "fixed") {
7204
7386
  return options.delay;
@@ -7209,7 +7391,7 @@ function calculateBackoff(attempt, options) {
7209
7391
  }
7210
7392
  function generateJobId() {
7211
7393
  const timestamp = Date.now().toString(36);
7212
- const random = Math.random().toString(36).substring(2, 10);
7394
+ const random = (0, import_crypto.randomBytes)(4).toString("hex");
7213
7395
  return `job_${timestamp}_${random}`;
7214
7396
  }
7215
7397
 
@@ -7560,6 +7742,7 @@ function createScopedMetrics(metrics, prefix, defaultTags = {}) {
7560
7742
  }
7561
7743
 
7562
7744
  // src/interfaces/ISecrets.ts
7745
+ var import_crypto2 = require("crypto");
7563
7746
  var EnvSecrets = class {
7564
7747
  prefix;
7565
7748
  cache = /* @__PURE__ */ new Map();
@@ -7760,12 +7943,7 @@ var MemorySecrets = class {
7760
7943
  return true;
7761
7944
  }
7762
7945
  generateSecureValue(length = 32) {
7763
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
7764
- let result = "";
7765
- for (let i = 0; i < length; i++) {
7766
- result += chars[Math.floor(Math.random() * chars.length)];
7767
- }
7768
- return result;
7946
+ return (0, import_crypto2.randomBytes)(length).toString("base64url").slice(0, length);
7769
7947
  }
7770
7948
  /**
7771
7949
  * Clear all secrets (for testing)
@@ -7783,6 +7961,7 @@ var MemorySecrets = class {
7783
7961
  };
7784
7962
 
7785
7963
  // src/interfaces/ITracing.ts
7964
+ var import_crypto3 = require("crypto");
7786
7965
  var MemorySpan = class {
7787
7966
  name;
7788
7967
  context;
@@ -7802,7 +7981,7 @@ var MemorySpan = class {
7802
7981
  };
7803
7982
  }
7804
7983
  generateSpanId() {
7805
- return Math.random().toString(16).substring(2, 18).padStart(16, "0");
7984
+ return (0, import_crypto3.randomBytes)(8).toString("hex");
7806
7985
  }
7807
7986
  setAttribute(key, value) {
7808
7987
  this._attributes[key] = value;
@@ -7862,7 +8041,7 @@ var MemoryTracing = class {
7862
8041
  this.traceId = this.generateTraceId();
7863
8042
  }
7864
8043
  generateTraceId() {
7865
- return Math.random().toString(16).substring(2, 34).padStart(32, "0");
8044
+ return (0, import_crypto3.randomBytes)(16).toString("hex");
7866
8045
  }
7867
8046
  startSpan(name, options) {
7868
8047
  const span = new MemorySpan(
@@ -8015,9 +8194,10 @@ var NoopTracing = class {
8015
8194
  };
8016
8195
 
8017
8196
  // src/interfaces/IErrorReporter.ts
8197
+ var import_crypto4 = require("crypto");
8018
8198
  function generateErrorId() {
8019
8199
  const timestamp = Date.now().toString(36);
8020
- const random = Math.random().toString(36).substring(2, 10);
8200
+ const random = (0, import_crypto4.randomBytes)(4).toString("hex");
8021
8201
  return `err_${timestamp}_${random}`;
8022
8202
  }
8023
8203
  function generateFingerprint(error) {
@@ -8061,9 +8241,10 @@ function createErrorReport(error, context, options) {
8061
8241
  }
8062
8242
 
8063
8243
  // src/interfaces/IAuditLog.ts
8244
+ var import_crypto5 = require("crypto");
8064
8245
  function generateAuditId() {
8065
8246
  const timestamp = Date.now().toString(36);
8066
- const random = Math.random().toString(36).substring(2, 10);
8247
+ const random = (0, import_crypto5.randomBytes)(4).toString("hex");
8067
8248
  return `aud_${timestamp}${random}`;
8068
8249
  }
8069
8250
  function generateChecksum(event) {
@@ -8229,9 +8410,10 @@ var AuditEvents = {
8229
8410
  };
8230
8411
 
8231
8412
  // src/interfaces/IScheduler.ts
8413
+ var import_crypto6 = require("crypto");
8232
8414
  function generateScheduleId() {
8233
8415
  const timestamp = Date.now().toString(36);
8234
- const random = Math.random().toString(36).substring(2, 8);
8416
+ const random = (0, import_crypto6.randomBytes)(4).toString("hex");
8235
8417
  return `sch_${timestamp}${random}`;
8236
8418
  }
8237
8419
  function getNextCronRun(cron, after = /* @__PURE__ */ new Date(), timezone) {
@@ -8290,28 +8472,24 @@ function describeCron(cron) {
8290
8472
  }
8291
8473
 
8292
8474
  // src/interfaces/IWebhook.ts
8475
+ var import_crypto7 = require("crypto");
8293
8476
  function generateWebhookId() {
8294
8477
  const timestamp = Date.now().toString(36);
8295
- const random = Math.random().toString(36).substring(2, 10);
8478
+ const random = (0, import_crypto7.randomBytes)(6).toString("hex");
8296
8479
  return `wh_${timestamp}${random}`;
8297
8480
  }
8298
8481
  function generateDeliveryId() {
8299
8482
  const timestamp = Date.now().toString(36);
8300
- const random = Math.random().toString(36).substring(2, 10);
8483
+ const random = (0, import_crypto7.randomBytes)(6).toString("hex");
8301
8484
  return `del_${timestamp}${random}`;
8302
8485
  }
8303
8486
  function generateEventId() {
8304
8487
  const timestamp = Date.now().toString(36);
8305
- const random = Math.random().toString(36).substring(2, 10);
8488
+ const random = (0, import_crypto7.randomBytes)(6).toString("hex");
8306
8489
  return `evt_${timestamp}${random}`;
8307
8490
  }
8308
8491
  function generateWebhookSecret(length = 32) {
8309
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
8310
- let secret = "whsec_";
8311
- for (let i = 0; i < length; i++) {
8312
- secret += chars.charAt(Math.floor(Math.random() * chars.length));
8313
- }
8314
- return secret;
8492
+ return `whsec_${(0, import_crypto7.randomBytes)(length).toString("base64url").slice(0, length)}`;
8315
8493
  }
8316
8494
  function matchEventType(eventType, pattern) {
8317
8495
  if (eventType === pattern || pattern === "*" || pattern === "**") {
@@ -8388,9 +8566,10 @@ var WebhookEventTypes = {
8388
8566
  };
8389
8567
 
8390
8568
  // src/interfaces/INotification.ts
8569
+ var import_crypto8 = require("crypto");
8391
8570
  function generateNotificationId() {
8392
8571
  const timestamp = Date.now().toString(36);
8393
- const random = Math.random().toString(36).substring(2, 10);
8572
+ const random = (0, import_crypto8.randomBytes)(4).toString("hex");
8394
8573
  return `notif_${timestamp}${random}`;
8395
8574
  }
8396
8575
  function isInQuietHours(preferences) {
@@ -8880,6 +9059,7 @@ var MemoryAuth = class {
8880
9059
  };
8881
9060
 
8882
9061
  // src/interfaces/IPayment.ts
9062
+ var import_crypto9 = require("crypto");
8883
9063
  function createPaymentError(code, message, originalError) {
8884
9064
  return { code, message, originalError };
8885
9065
  }
@@ -8911,7 +9091,7 @@ function formatAmount(amount, currency, locale = "en-US") {
8911
9091
  }
8912
9092
  function generatePaymentId(prefix = "pi") {
8913
9093
  const timestamp = Date.now().toString(36);
8914
- const random = Math.random().toString(36).substring(2, 10);
9094
+ const random = (0, import_crypto9.randomBytes)(8).toString("hex");
8915
9095
  return `${prefix}_${timestamp}${random}`;
8916
9096
  }
8917
9097
  var MemoryPayment = class {
@@ -8969,7 +9149,7 @@ var MemoryPayment = class {
8969
9149
  amount: options.amount,
8970
9150
  currency: options.currency,
8971
9151
  status: options.paymentMethodId ? "requires_confirmation" : "requires_payment_method",
8972
- clientSecret: `${id}_secret_${Math.random().toString(36).substring(2, 15)}`,
9152
+ clientSecret: `${id}_secret_${(0, import_crypto9.randomBytes)(16).toString("base64url")}`,
8973
9153
  metadata: options.metadata,
8974
9154
  description: options.description,
8975
9155
  receiptEmail: options.receiptEmail,
@@ -9284,6 +9464,7 @@ var MemoryPayment = class {
9284
9464
  };
9285
9465
 
9286
9466
  // src/interfaces/IAuthSSO.ts
9467
+ var import_crypto10 = require("crypto");
9287
9468
  var MemoryAuthSSO = class {
9288
9469
  samlConfigs = /* @__PURE__ */ new Map();
9289
9470
  oidcConfigs = /* @__PURE__ */ new Map();
@@ -9315,7 +9496,7 @@ var MemoryAuthSSO = class {
9315
9496
  if (!config) {
9316
9497
  throw new Error("SAML not configured for tenant");
9317
9498
  }
9318
- const id = `_${Math.random().toString(36).substring(2)}`;
9499
+ const id = `_${(0, import_crypto10.randomBytes)(8).toString("hex")}`;
9319
9500
  return {
9320
9501
  id,
9321
9502
  redirectUrl: `${config.ssoUrl}?SAMLRequest=mock_request&RelayState=${options.relayState ?? ""}`,
@@ -9327,7 +9508,7 @@ var MemoryAuthSSO = class {
9327
9508
  }
9328
9509
  async processSamlResponse(_samlResponse, _relayState) {
9329
9510
  const user = {
9330
- id: `saml_${Math.random().toString(36).substring(2)}`,
9511
+ id: `saml_${(0, import_crypto10.randomBytes)(8).toString("hex")}`,
9331
9512
  email: "saml.user@example.com",
9332
9513
  emailVerified: true,
9333
9514
  metadata: { ssoProvider: "saml" },
@@ -9337,7 +9518,7 @@ var MemoryAuthSSO = class {
9337
9518
  success: true,
9338
9519
  user,
9339
9520
  session: {
9340
- accessToken: `saml_token_${Math.random().toString(36)}`,
9521
+ accessToken: `saml_token_${(0, import_crypto10.randomBytes)(8).toString("hex")}`,
9341
9522
  expiresAt: new Date(Date.now() + 36e5),
9342
9523
  user
9343
9524
  },
@@ -9374,8 +9555,8 @@ var MemoryAuthSSO = class {
9374
9555
  }
9375
9556
  // OIDC Authentication
9376
9557
  async initiateOidcLogin(options) {
9377
- const state = options.state ?? Math.random().toString(36).substring(2);
9378
- const nonce = Math.random().toString(36).substring(2);
9558
+ const state = options.state ?? (0, import_crypto10.randomBytes)(8).toString("hex");
9559
+ const nonce = (0, import_crypto10.randomBytes)(8).toString("hex");
9379
9560
  return {
9380
9561
  state,
9381
9562
  redirectUrl: `https://idp.example.com/authorize?client_id=mock&redirect_uri=${encodeURIComponent(options.redirectUri)}&state=${state}`,
@@ -9386,7 +9567,7 @@ var MemoryAuthSSO = class {
9386
9567
  }
9387
9568
  async processOidcCallback(_code, _state, _codeVerifier) {
9388
9569
  const user = {
9389
- id: `oidc_${Math.random().toString(36).substring(2)}`,
9570
+ id: `oidc_${(0, import_crypto10.randomBytes)(8).toString("hex")}`,
9390
9571
  email: "oidc.user@example.com",
9391
9572
  emailVerified: true,
9392
9573
  metadata: { ssoProvider: "oidc" },
@@ -9396,7 +9577,7 @@ var MemoryAuthSSO = class {
9396
9577
  success: true,
9397
9578
  user,
9398
9579
  session: {
9399
- accessToken: `oidc_token_${Math.random().toString(36)}`,
9580
+ accessToken: `oidc_token_${(0, import_crypto10.randomBytes)(8).toString("hex")}`,
9400
9581
  expiresAt: new Date(Date.now() + 36e5),
9401
9582
  user
9402
9583
  },
@@ -9405,7 +9586,7 @@ var MemoryAuthSSO = class {
9405
9586
  }
9406
9587
  async refreshOidcTokens(_refreshToken, _tenantId) {
9407
9588
  return {
9408
- accessToken: `refreshed_token_${Math.random().toString(36)}`,
9589
+ accessToken: `refreshed_token_${(0, import_crypto10.randomBytes)(8).toString("hex")}`,
9409
9590
  expiresIn: 3600
9410
9591
  };
9411
9592
  }
@@ -9435,7 +9616,7 @@ var MemoryAuthSSO = class {
9435
9616
  }
9436
9617
  // SCIM
9437
9618
  async configureScim(config) {
9438
- const token = `scim_token_${Math.random().toString(36)}`;
9619
+ const token = `scim_token_${(0, import_crypto10.randomBytes)(8).toString("hex")}`;
9439
9620
  this.scimConfigs.set(config.tenantId, { ...config, bearerToken: token });
9440
9621
  return { bearerToken: token };
9441
9622
  }
@@ -9448,7 +9629,7 @@ var MemoryAuthSSO = class {
9448
9629
  async regenerateScimToken(tenantId) {
9449
9630
  const config = this.scimConfigs.get(tenantId);
9450
9631
  if (!config) throw new Error("SCIM not configured");
9451
- const token = `scim_token_${Math.random().toString(36)}`;
9632
+ const token = `scim_token_${(0, import_crypto10.randomBytes)(8).toString("hex")}`;
9452
9633
  config.bearerToken = token;
9453
9634
  return { bearerToken: token };
9454
9635
  }
@@ -9457,7 +9638,7 @@ var MemoryAuthSSO = class {
9457
9638
  }
9458
9639
  // Domain Verification
9459
9640
  async initiateDomainVerification(tenantId, domain) {
9460
- const token = `dll-verify-${Math.random().toString(36).substring(2)}`;
9641
+ const token = `dll-verify-${(0, import_crypto10.randomBytes)(8).toString("hex")}`;
9461
9642
  this.pendingVerifications.set(`${tenantId}:${domain}`, { domain, token });
9462
9643
  return {
9463
9644
  verificationMethod: "dns_txt",
@@ -9523,6 +9704,7 @@ var MemoryAuthSSO = class {
9523
9704
  };
9524
9705
 
9525
9706
  // src/interfaces/ITenant.ts
9707
+ var import_crypto11 = require("crypto");
9526
9708
  var tenantContextStorage = /* @__PURE__ */ new Map();
9527
9709
  var contextIdCounter = 0;
9528
9710
  var currentContextId = null;
@@ -9590,7 +9772,7 @@ var MemoryTenant = class {
9590
9772
  // Tenant CRUD
9591
9773
  async createTenant(options) {
9592
9774
  const tenant = {
9593
- id: `tenant_${Math.random().toString(36).substring(2)}`,
9775
+ id: `tenant_${(0, import_crypto11.randomBytes)(8).toString("hex")}`,
9594
9776
  slug: options.slug,
9595
9777
  name: options.name,
9596
9778
  status: "active",
@@ -9711,7 +9893,7 @@ var MemoryTenant = class {
9711
9893
  }
9712
9894
  async addMember(tenantId, userId, role) {
9713
9895
  const member = {
9714
- id: `member_${Math.random().toString(36).substring(2)}`,
9896
+ id: `member_${(0, import_crypto11.randomBytes)(8).toString("hex")}`,
9715
9897
  tenantId,
9716
9898
  userId,
9717
9899
  role,
@@ -9752,12 +9934,12 @@ var MemoryTenant = class {
9752
9934
  }
9753
9935
  async inviteMember(tenantId, options) {
9754
9936
  const invitation = {
9755
- id: `inv_${Math.random().toString(36).substring(2)}`,
9937
+ id: `inv_${(0, import_crypto11.randomBytes)(8).toString("hex")}`,
9756
9938
  tenantId,
9757
9939
  email: options.email,
9758
9940
  role: options.role,
9759
9941
  invitedBy: "system",
9760
- token: Math.random().toString(36).substring(2),
9942
+ token: (0, import_crypto11.randomBytes)(16).toString("base64url"),
9761
9943
  status: "pending",
9762
9944
  createdAt: /* @__PURE__ */ new Date(),
9763
9945
  expiresAt: new Date(
@@ -9918,6 +10100,7 @@ var MemoryTenant = class {
9918
10100
  init_IAI();
9919
10101
 
9920
10102
  // src/interfaces/IPromptStore.ts
10103
+ var import_crypto12 = require("crypto");
9921
10104
  var MemoryPromptStore = class {
9922
10105
  // userId -> variantId
9923
10106
  constructor(config = {}) {
@@ -9933,7 +10116,7 @@ var MemoryPromptStore = class {
9933
10116
  // Prompt CRUD
9934
10117
  // ─────────────────────────────────────────────────────────────
9935
10118
  async create(prompt) {
9936
- const id = `prompt_${Date.now()}_${Math.random().toString(36).substring(7)}`;
10119
+ const id = `prompt_${Date.now()}_${(0, import_crypto12.randomBytes)(4).toString("hex")}`;
9937
10120
  const now = /* @__PURE__ */ new Date();
9938
10121
  const newPrompt = {
9939
10122
  ...prompt,
@@ -9948,7 +10131,7 @@ var MemoryPromptStore = class {
9948
10131
  this.prompts.set(id, newPrompt);
9949
10132
  this.prompts.set(prompt.slug, newPrompt);
9950
10133
  const version = {
9951
- id: `pv_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10134
+ id: `pv_${Date.now()}_${(0, import_crypto12.randomBytes)(4).toString("hex")}`,
9952
10135
  promptId: id,
9953
10136
  version: 1,
9954
10137
  content: prompt.content,
@@ -9983,7 +10166,7 @@ var MemoryPromptStore = class {
9983
10166
  latestVersion.isLatest = false;
9984
10167
  }
9985
10168
  const newVersion = {
9986
- id: `pv_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10169
+ id: `pv_${Date.now()}_${(0, import_crypto12.randomBytes)(4).toString("hex")}`,
9987
10170
  promptId: prompt.id,
9988
10171
  version: versions.length + 1,
9989
10172
  content: updates.content,
@@ -10228,7 +10411,7 @@ ${v2.content}`;
10228
10411
  // A/B Testing
10229
10412
  // ─────────────────────────────────────────────────────────────
10230
10413
  async createExperiment(experiment) {
10231
- const id = `exp_${Date.now()}_${Math.random().toString(36).substring(7)}`;
10414
+ const id = `exp_${Date.now()}_${(0, import_crypto12.randomBytes)(4).toString("hex")}`;
10232
10415
  const now = /* @__PURE__ */ new Date();
10233
10416
  const newExperiment = {
10234
10417
  ...experiment,
@@ -10305,7 +10488,7 @@ ${v2.content}`;
10305
10488
  // Prompt Chains
10306
10489
  // ─────────────────────────────────────────────────────────────
10307
10490
  async createChain(chain) {
10308
- const id = `chain_${Date.now()}_${Math.random().toString(36).substring(7)}`;
10491
+ const id = `chain_${Date.now()}_${(0, import_crypto12.randomBytes)(4).toString("hex")}`;
10309
10492
  const now = /* @__PURE__ */ new Date();
10310
10493
  const newChain = {
10311
10494
  ...chain,
@@ -10396,7 +10579,7 @@ ${v2.content}`;
10396
10579
  async recordUsage(record) {
10397
10580
  const usageRecord = {
10398
10581
  ...record,
10399
- id: `usage_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10582
+ id: `usage_${Date.now()}_${(0, import_crypto12.randomBytes)(4).toString("hex")}`,
10400
10583
  createdAt: /* @__PURE__ */ new Date()
10401
10584
  };
10402
10585
  if (this.config.trackUsage !== false) {
@@ -10500,6 +10683,7 @@ ${v2.content}`;
10500
10683
  init_IRAG();
10501
10684
 
10502
10685
  // src/interfaces/IAIUsage.ts
10686
+ var import_crypto14 = require("crypto");
10503
10687
  var MemoryAIUsage = class {
10504
10688
  constructor(config = {}) {
10505
10689
  this.config = config;
@@ -10533,7 +10717,7 @@ var MemoryAIUsage = class {
10533
10717
  async record(record) {
10534
10718
  const newRecord = {
10535
10719
  ...record,
10536
- id: `usage_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10720
+ id: `usage_${Date.now()}_${(0, import_crypto14.randomBytes)(4).toString("hex")}`,
10537
10721
  createdAt: /* @__PURE__ */ new Date()
10538
10722
  };
10539
10723
  this.records.push(newRecord);
@@ -10614,7 +10798,7 @@ var MemoryAIUsage = class {
10614
10798
  const period = this.getPeriodBounds(quota.period, /* @__PURE__ */ new Date());
10615
10799
  const newQuota = {
10616
10800
  ...quota,
10617
- id: existingQuota?.id || `quota_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10801
+ id: existingQuota?.id || `quota_${Date.now()}_${(0, import_crypto14.randomBytes)(4).toString("hex")}`,
10618
10802
  used: existingQuota?.used || 0,
10619
10803
  periodStart: period.start,
10620
10804
  periodEnd: period.end
@@ -10708,7 +10892,7 @@ var MemoryAIUsage = class {
10708
10892
  const period = this.getPeriodBounds(budget.period, /* @__PURE__ */ new Date());
10709
10893
  const newBudget = {
10710
10894
  ...budget,
10711
- id: existingBudget?.id || `budget_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10895
+ id: existingBudget?.id || `budget_${Date.now()}_${(0, import_crypto14.randomBytes)(4).toString("hex")}`,
10712
10896
  spent: existingBudget?.spent || 0,
10713
10897
  periodStart: period.start,
10714
10898
  periodEnd: period.end
@@ -10972,7 +11156,7 @@ var MemoryAIUsage = class {
10972
11156
  const items = Array.from(itemsMap.values());
10973
11157
  const subtotal = items.reduce((sum, item) => sum + item.costUsd, 0);
10974
11158
  const invoice = {
10975
- id: `inv_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11159
+ id: `inv_${Date.now()}_${(0, import_crypto14.randomBytes)(4).toString("hex")}`,
10976
11160
  tenantId,
10977
11161
  periodStart,
10978
11162
  periodEnd,
@@ -11185,7 +11369,7 @@ var MemoryAIUsage = class {
11185
11369
  );
11186
11370
  if (existingAlert) return;
11187
11371
  this.alerts.push({
11188
- id: `alert_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11372
+ id: `alert_${Date.now()}_${(0, import_crypto14.randomBytes)(4).toString("hex")}`,
11189
11373
  tenantId,
11190
11374
  type,
11191
11375
  severity,
@@ -11314,6 +11498,7 @@ var MemoryAIUsage = class {
11314
11498
  };
11315
11499
 
11316
11500
  // src/interfaces/IDevice.ts
11501
+ var import_crypto15 = require("crypto");
11317
11502
  var MemoryDevice = class {
11318
11503
  constructor(config = {}) {
11319
11504
  this.config = config;
@@ -11338,7 +11523,7 @@ var MemoryDevice = class {
11338
11523
  const now = /* @__PURE__ */ new Date();
11339
11524
  const newDevice = {
11340
11525
  ...device,
11341
- id: `dev_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11526
+ id: `dev_${Date.now()}_${(0, import_crypto15.randomBytes)(4).toString("hex")}`,
11342
11527
  status: "active",
11343
11528
  connectionState: "disconnected",
11344
11529
  tags: device.tags || [],
@@ -11461,7 +11646,7 @@ var MemoryDevice = class {
11461
11646
  // Provisioning
11462
11647
  // ─────────────────────────────────────────────────────────────
11463
11648
  async provision(request) {
11464
- const id = `prov_${Date.now()}_${Math.random().toString(36).substring(7)}`;
11649
+ const id = `prov_${Date.now()}_${(0, import_crypto15.randomBytes)(4).toString("hex")}`;
11465
11650
  const newRequest = {
11466
11651
  ...request,
11467
11652
  id,
@@ -11473,7 +11658,7 @@ var MemoryDevice = class {
11473
11658
  const result = {
11474
11659
  credentials: {
11475
11660
  type: request.config.authMethod || "token",
11476
- token: `tok_${Date.now()}_${Math.random().toString(36).substring(7)}`
11661
+ token: `tok_${Date.now()}_${(0, import_crypto15.randomBytes)(16).toString("hex")}`
11477
11662
  },
11478
11663
  endpoint: "mqtt://localhost:1883",
11479
11664
  mqttBroker: "mqtt://localhost:1883"
@@ -11516,7 +11701,7 @@ var MemoryDevice = class {
11516
11701
  }
11517
11702
  }
11518
11703
  async generateRegistrationCode(deviceType, tenantId, expiresInHours = 24) {
11519
- const code = `REG_${Math.random().toString(36).substring(2, 10).toUpperCase()}`;
11704
+ const code = `REG_${(0, import_crypto15.randomBytes)(4).toString("hex").toUpperCase()}`;
11520
11705
  this.registrationCodes.set(code, {
11521
11706
  deviceType,
11522
11707
  tenantId,
@@ -11616,7 +11801,7 @@ var MemoryDevice = class {
11616
11801
  async ingestTelemetry(message) {
11617
11802
  const newMessage = {
11618
11803
  ...message,
11619
- id: `tel_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11804
+ id: `tel_${Date.now()}_${(0, import_crypto15.randomBytes)(4).toString("hex")}`,
11620
11805
  receivedAt: /* @__PURE__ */ new Date()
11621
11806
  };
11622
11807
  if (this.config.storeTelemetry !== false) {
@@ -11696,7 +11881,7 @@ var MemoryDevice = class {
11696
11881
  // ─────────────────────────────────────────────────────────────
11697
11882
  async sendCommand(deviceId, name, payload, options) {
11698
11883
  const command = {
11699
- id: `cmd_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11884
+ id: `cmd_${Date.now()}_${(0, import_crypto15.randomBytes)(4).toString("hex")}`,
11700
11885
  deviceId,
11701
11886
  name,
11702
11887
  payload,
@@ -11759,7 +11944,7 @@ var MemoryDevice = class {
11759
11944
  async createFirmware(firmware) {
11760
11945
  const newFirmware = {
11761
11946
  ...firmware,
11762
- id: `fw_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11947
+ id: `fw_${Date.now()}_${(0, import_crypto15.randomBytes)(4).toString("hex")}`,
11763
11948
  status: "draft",
11764
11949
  createdAt: /* @__PURE__ */ new Date()
11765
11950
  };
@@ -11811,7 +11996,7 @@ var MemoryDevice = class {
11811
11996
  throw new Error(`Firmware not found: ${firmwareVersionId}`);
11812
11997
  }
11813
11998
  const update = {
11814
- id: `upd_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11999
+ id: `upd_${Date.now()}_${(0, import_crypto15.randomBytes)(4).toString("hex")}`,
11815
12000
  deviceId,
11816
12001
  firmwareVersionId,
11817
12002
  targetVersion: firmware.version,
@@ -11865,7 +12050,7 @@ var MemoryDevice = class {
11865
12050
  const now = /* @__PURE__ */ new Date();
11866
12051
  const newGroup = {
11867
12052
  ...group,
11868
- id: `grp_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12053
+ id: `grp_${Date.now()}_${(0, import_crypto15.randomBytes)(4).toString("hex")}`,
11869
12054
  deviceCount: 0,
11870
12055
  tags: group.tags || [],
11871
12056
  attributes: group.attributes || {},
@@ -11985,6 +12170,7 @@ var MemoryDevice = class {
11985
12170
  };
11986
12171
 
11987
12172
  // src/interfaces/IBilling.ts
12173
+ var import_crypto16 = require("crypto");
11988
12174
  var MemoryBilling = class {
11989
12175
  constructor(config = {}) {
11990
12176
  this.config = config;
@@ -12005,7 +12191,7 @@ var MemoryBilling = class {
12005
12191
  async createProduct(product) {
12006
12192
  const newProduct = {
12007
12193
  ...product,
12008
- id: `prod_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12194
+ id: `prod_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12009
12195
  features: product.features || [],
12010
12196
  metadata: product.metadata || {},
12011
12197
  createdAt: /* @__PURE__ */ new Date(),
@@ -12033,7 +12219,7 @@ var MemoryBilling = class {
12033
12219
  async createPrice(price) {
12034
12220
  const newPrice = {
12035
12221
  ...price,
12036
- id: `price_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12222
+ id: `price_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12037
12223
  metadata: price.metadata || {},
12038
12224
  createdAt: /* @__PURE__ */ new Date(),
12039
12225
  updatedAt: /* @__PURE__ */ new Date()
@@ -12064,7 +12250,7 @@ var MemoryBilling = class {
12064
12250
  async createMeter(meter) {
12065
12251
  const newMeter = {
12066
12252
  ...meter,
12067
- id: `meter_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12253
+ id: `meter_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12068
12254
  createdAt: /* @__PURE__ */ new Date(),
12069
12255
  updatedAt: /* @__PURE__ */ new Date()
12070
12256
  };
@@ -12098,13 +12284,13 @@ var MemoryBilling = class {
12098
12284
  const trialDays = options.trialDays ?? price.trialDays ?? 0;
12099
12285
  const periodEnd = this.addPeriod(now, price.billingPeriod);
12100
12286
  const subscription = {
12101
- id: `sub_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12287
+ id: `sub_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12102
12288
  customerId: options.customerId,
12103
12289
  tenantId: options.tenantId,
12104
12290
  status: trialDays > 0 ? "trialing" : "active",
12105
12291
  items: [
12106
12292
  {
12107
- id: `si_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12293
+ id: `si_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12108
12294
  priceId: options.priceId,
12109
12295
  quantity: options.quantity || 1
12110
12296
  }
@@ -12195,7 +12381,7 @@ var MemoryBilling = class {
12195
12381
  const sub = await this.getSubscription(subscriptionId);
12196
12382
  if (!sub) throw new Error(`Subscription not found: ${subscriptionId}`);
12197
12383
  sub.items.push({
12198
- id: `si_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12384
+ id: `si_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12199
12385
  priceId,
12200
12386
  quantity: quantity || 1
12201
12387
  });
@@ -12247,7 +12433,7 @@ var MemoryBilling = class {
12247
12433
  if (existing) return existing;
12248
12434
  }
12249
12435
  const event = {
12250
- id: `ue_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12436
+ id: `ue_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12251
12437
  subscriptionId,
12252
12438
  customerId: sub.customerId,
12253
12439
  meterId: meter.id,
@@ -12318,7 +12504,7 @@ var MemoryBilling = class {
12318
12504
  if (price) {
12319
12505
  const unitAmount = price.unitAmount || 0;
12320
12506
  lineItems.push({
12321
- id: `ii_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12507
+ id: `ii_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12322
12508
  priceId: item.priceId,
12323
12509
  description: price.name,
12324
12510
  quantity: item.quantity,
@@ -12333,7 +12519,7 @@ var MemoryBilling = class {
12333
12519
  const usageSummary = await this.getUsageSummary(subscriptionId);
12334
12520
  for (const usage of usageSummary) {
12335
12521
  lineItems.push({
12336
- id: `ii_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12522
+ id: `ii_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12337
12523
  description: `${usage.meterName}: ${usage.total} ${usage.unit}`,
12338
12524
  quantity: usage.total,
12339
12525
  unitAmount: usage.cost / usage.total,
@@ -12356,7 +12542,7 @@ var MemoryBilling = class {
12356
12542
  const tax = (subtotal - discount) * (taxRate / 100);
12357
12543
  const total = subtotal - discount + tax;
12358
12544
  const invoice = {
12359
- id: `inv_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12545
+ id: `inv_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12360
12546
  customerId: sub.customerId,
12361
12547
  subscriptionId,
12362
12548
  tenantId: sub.tenantId,
@@ -12387,14 +12573,14 @@ var MemoryBilling = class {
12387
12573
  async createInvoice(options) {
12388
12574
  const lineItems = options.lineItems.map((item) => ({
12389
12575
  ...item,
12390
- id: `ii_${Date.now()}_${Math.random().toString(36).substring(7)}`
12576
+ id: `ii_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`
12391
12577
  }));
12392
12578
  const subtotal = lineItems.reduce((sum, item) => sum + item.amount, 0);
12393
12579
  const taxRate = this.config.defaultTaxRate || 0;
12394
12580
  const tax = subtotal * (taxRate / 100);
12395
12581
  const total = subtotal + tax;
12396
12582
  const invoice = {
12397
- id: `inv_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12583
+ id: `inv_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12398
12584
  customerId: options.customerId,
12399
12585
  tenantId: options.tenantId,
12400
12586
  number: `${this.config.invoiceNumberPrefix || "INV-"}${++this.invoiceCounter}`,
@@ -12483,7 +12669,7 @@ var MemoryBilling = class {
12483
12669
  async createDunningConfig(config) {
12484
12670
  const newConfig = {
12485
12671
  ...config,
12486
- id: `dun_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12672
+ id: `dun_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12487
12673
  createdAt: /* @__PURE__ */ new Date(),
12488
12674
  updatedAt: /* @__PURE__ */ new Date()
12489
12675
  };
@@ -12509,7 +12695,7 @@ var MemoryBilling = class {
12509
12695
  const invoice = await this.getInvoice(invoiceId);
12510
12696
  if (!invoice) throw new Error(`Invoice not found: ${invoiceId}`);
12511
12697
  const attempt = {
12512
- id: `da_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12698
+ id: `da_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12513
12699
  invoiceId,
12514
12700
  attemptNumber: invoice.attemptCount + 1,
12515
12701
  action: "retry_payment",
@@ -12541,7 +12727,7 @@ var MemoryBilling = class {
12541
12727
  balance.updatedAt = /* @__PURE__ */ new Date();
12542
12728
  this.creditBalances.set(customerId, balance);
12543
12729
  const transaction = {
12544
- id: `ct_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12730
+ id: `ct_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12545
12731
  customerId,
12546
12732
  type: options?.type || "manual",
12547
12733
  amount,
@@ -12566,7 +12752,7 @@ var MemoryBilling = class {
12566
12752
  balance.updatedAt = /* @__PURE__ */ new Date();
12567
12753
  this.creditBalances.set(customerId, balance);
12568
12754
  const transaction = {
12569
- id: `ct_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12755
+ id: `ct_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12570
12756
  customerId,
12571
12757
  type: "manual",
12572
12758
  amount: -amount,
@@ -12590,7 +12776,7 @@ var MemoryBilling = class {
12590
12776
  async createCoupon(coupon) {
12591
12777
  const newCoupon = {
12592
12778
  ...coupon,
12593
- id: `coup_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12779
+ id: `coup_${Date.now()}_${(0, import_crypto16.randomBytes)(4).toString("hex")}`,
12594
12780
  timesRedeemed: 0,
12595
12781
  createdAt: /* @__PURE__ */ new Date(),
12596
12782
  updatedAt: /* @__PURE__ */ new Date()
@@ -12826,6 +13012,7 @@ var MemoryBilling = class {
12826
13012
  };
12827
13013
 
12828
13014
  // src/interfaces/IDevPortal.ts
13015
+ var import_crypto17 = require("crypto");
12829
13016
  var MemoryDevPortal = class {
12830
13017
  constructor(config = {}) {
12831
13018
  this.config = config;
@@ -12838,8 +13025,9 @@ var MemoryDevPortal = class {
12838
13025
  usageRecords = [];
12839
13026
  // API Key Management
12840
13027
  async createApiKey(options, userId) {
12841
- const id = `key_${Date.now()}_${Math.random().toString(36).substring(7)}`;
12842
- const secret = `sk_${options.type}_${Math.random().toString(36).substring(2)}${Math.random().toString(36).substring(2)}`;
13028
+ const { randomBytes: randomBytes37, createHash: createHash2 } = await import("crypto");
13029
+ const id = `key_${Date.now()}_${randomBytes37(8).toString("hex")}`;
13030
+ const secret = `sk_${options.type}_${randomBytes37(24).toString("base64url")}`;
12843
13031
  const prefix = secret.substring(0, 12);
12844
13032
  const key = {
12845
13033
  id,
@@ -12926,7 +13114,7 @@ var MemoryDevPortal = class {
12926
13114
  // API Documentation
12927
13115
  async generateDocumentation(endpoints, config) {
12928
13116
  const doc = {
12929
- id: `doc_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13117
+ id: `doc_${Date.now()}_${(0, import_crypto17.randomBytes)(4).toString("hex")}`,
12930
13118
  title: config.title,
12931
13119
  version: config.version,
12932
13120
  baseUrl: config.baseUrl,
@@ -12982,7 +13170,7 @@ var MemoryDevPortal = class {
12982
13170
  if (!doc) throw new Error(`Documentation not found: ${docId}`);
12983
13171
  const newEndpoint = {
12984
13172
  ...endpoint,
12985
- id: `ep_${Date.now()}_${Math.random().toString(36).substring(7)}`
13173
+ id: `ep_${Date.now()}_${(0, import_crypto17.randomBytes)(4).toString("hex")}`
12986
13174
  };
12987
13175
  doc.endpoints.push(newEndpoint);
12988
13176
  return newEndpoint;
@@ -13078,7 +13266,7 @@ SDK for ${documentation.title}`,
13078
13266
  });
13079
13267
  }
13080
13268
  const sdk = {
13081
- id: `sdk_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13269
+ id: `sdk_${Date.now()}_${(0, import_crypto17.randomBytes)(4).toString("hex")}`,
13082
13270
  language: config.language,
13083
13271
  packageName: config.packageName,
13084
13272
  version: config.version,
@@ -13105,7 +13293,7 @@ SDK for ${documentation.title}`,
13105
13293
  }
13106
13294
  // Sandbox / Playground
13107
13295
  async createSandbox(options, userId) {
13108
- const id = `sandbox_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13296
+ const id = `sandbox_${Date.now()}_${(0, import_crypto17.randomBytes)(4).toString("hex")}`;
13109
13297
  const lifetimeHours = options.lifetimeHours || this.config.sandboxDefaultLifetimeHours || 24;
13110
13298
  const sandbox = {
13111
13299
  id,
@@ -13114,7 +13302,7 @@ SDK for ${documentation.title}`,
13114
13302
  tenantId: options.tenantId,
13115
13303
  status: "active",
13116
13304
  baseUrl: `https://sandbox-${id}.example.com`,
13117
- apiKey: `sandbox_${Math.random().toString(36).substring(2)}`,
13305
+ apiKey: `sandbox_${(0, import_crypto17.randomBytes)(8).toString("hex")}`,
13118
13306
  seedDataLoaded: options.seedData || [],
13119
13307
  config: options.config || {},
13120
13308
  limits: {
@@ -13251,7 +13439,7 @@ SDK for ${documentation.title}`,
13251
13439
  }
13252
13440
  // Webhook Testing
13253
13441
  async createWebhookTestEndpoint(userId, maxEvents = 100) {
13254
- const id = `wh_test_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13442
+ const id = `wh_test_${Date.now()}_${(0, import_crypto17.randomBytes)(4).toString("hex")}`;
13255
13443
  const endpoint = {
13256
13444
  id,
13257
13445
  url: `https://webhook-test.example.com/${id}`,
@@ -13288,18 +13476,13 @@ SDK for ${documentation.title}`,
13288
13476
  statusCode: 200,
13289
13477
  headers: { "content-type": "application/json" },
13290
13478
  body: { received: true },
13291
- latencyMs: Math.random() * 100
13479
+ latencyMs: 0
13292
13480
  };
13293
13481
  }
13294
13482
  // Private helpers
13295
13483
  hashKey(key) {
13296
- let hash = 0;
13297
- for (let i = 0; i < key.length; i++) {
13298
- const char = key.charCodeAt(i);
13299
- hash = (hash << 5) - hash + char;
13300
- hash = hash & hash;
13301
- }
13302
- return `hashed_${Math.abs(hash).toString(36)}`;
13484
+ const { createHash: createHash2 } = require("crypto");
13485
+ return createHash2("sha256").update(key).digest("hex");
13303
13486
  }
13304
13487
  endpointsToOpenApiPaths(endpoints) {
13305
13488
  const paths = {};
@@ -13391,6 +13574,7 @@ class ApiClient:
13391
13574
  };
13392
13575
 
13393
13576
  // src/interfaces/ICompliance.ts
13577
+ var import_crypto18 = require("crypto");
13394
13578
  var MemoryCompliance = class {
13395
13579
  constructor(config = {}) {
13396
13580
  this.config = config;
@@ -13407,13 +13591,13 @@ var MemoryCompliance = class {
13407
13591
  breaches = /* @__PURE__ */ new Map();
13408
13592
  // DSAR Management
13409
13593
  async createDsar(options) {
13410
- const id = `dsar_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13594
+ const id = `dsar_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`;
13411
13595
  const dsar = {
13412
13596
  id,
13413
13597
  type: options.type,
13414
13598
  subjectId: options.subjectId || options.subjectEmail,
13415
13599
  subjectEmail: options.subjectEmail,
13416
- verificationToken: `verify_${Math.random().toString(36).substring(2)}`,
13600
+ verificationToken: `verify_${(0, import_crypto18.randomBytes)(8).toString("hex")}`,
13417
13601
  verified: false,
13418
13602
  status: "pending_verification",
13419
13603
  tenantId: options.tenantId,
@@ -13464,7 +13648,7 @@ var MemoryCompliance = class {
13464
13648
  dsar.updatedAt = /* @__PURE__ */ new Date();
13465
13649
  if (notes) {
13466
13650
  dsar.notes.push({
13467
- id: `note_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13651
+ id: `note_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`,
13468
13652
  content: notes,
13469
13653
  authorId: "system",
13470
13654
  createdAt: /* @__PURE__ */ new Date()
@@ -13476,7 +13660,7 @@ var MemoryCompliance = class {
13476
13660
  const dsar = await this.getDsar(dsarId);
13477
13661
  if (!dsar) throw new Error(`DSAR not found: ${dsarId}`);
13478
13662
  const note = {
13479
- id: `note_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13663
+ id: `note_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`,
13480
13664
  content,
13481
13665
  authorId,
13482
13666
  createdAt: /* @__PURE__ */ new Date()
@@ -13490,7 +13674,7 @@ var MemoryCompliance = class {
13490
13674
  if (!dsar) throw new Error(`DSAR not found: ${dsarId}`);
13491
13675
  const att = {
13492
13676
  ...attachment,
13493
- id: `att_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13677
+ id: `att_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`,
13494
13678
  createdAt: /* @__PURE__ */ new Date()
13495
13679
  };
13496
13680
  dsar.attachments.push(att);
@@ -13531,7 +13715,7 @@ var MemoryCompliance = class {
13531
13715
  }
13532
13716
  // Consent Management
13533
13717
  async recordConsent(options) {
13534
- const id = `consent_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13718
+ const id = `consent_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`;
13535
13719
  const consent = {
13536
13720
  id,
13537
13721
  subjectId: options.subjectId,
@@ -13606,7 +13790,7 @@ var MemoryCompliance = class {
13606
13790
  }
13607
13791
  // Retention Policies
13608
13792
  async createRetentionPolicy(policy) {
13609
- const id = `rp_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13793
+ const id = `rp_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`;
13610
13794
  const newPolicy = {
13611
13795
  ...policy,
13612
13796
  id,
@@ -13639,7 +13823,7 @@ var MemoryCompliance = class {
13639
13823
  if (!policy) throw new Error(`Policy not found: ${policyId}`);
13640
13824
  const startedAt = /* @__PURE__ */ new Date();
13641
13825
  const execution = {
13642
- id: `re_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13826
+ id: `re_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`,
13643
13827
  policyId,
13644
13828
  recordsProcessed: 100,
13645
13829
  recordsAffected: 15,
@@ -13658,7 +13842,7 @@ var MemoryCompliance = class {
13658
13842
  }
13659
13843
  // Data Inventory
13660
13844
  async addDataInventoryItem(item) {
13661
- const id = `di_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13845
+ const id = `di_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`;
13662
13846
  const newItem = {
13663
13847
  ...item,
13664
13848
  id,
@@ -13719,7 +13903,7 @@ var MemoryCompliance = class {
13719
13903
  }
13720
13904
  // Audit Evidence
13721
13905
  async addEvidence(evidence) {
13722
- const id = `ev_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13906
+ const id = `ev_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`;
13723
13907
  const newEvidence = {
13724
13908
  ...evidence,
13725
13909
  id,
@@ -13795,7 +13979,7 @@ var MemoryCompliance = class {
13795
13979
  }
13796
13980
  // PIAs
13797
13981
  async createPia(pia) {
13798
- const id = `pia_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13982
+ const id = `pia_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`;
13799
13983
  const newPia = {
13800
13984
  ...pia,
13801
13985
  id,
@@ -13827,7 +14011,7 @@ var MemoryCompliance = class {
13827
14011
  if (!pia) throw new Error(`PIA not found: ${piaId}`);
13828
14012
  const newRisk = {
13829
14013
  ...risk,
13830
- id: `risk_${Date.now()}_${Math.random().toString(36).substring(7)}`
14014
+ id: `risk_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`
13831
14015
  };
13832
14016
  pia.risks.push(newRisk);
13833
14017
  pia.updatedAt = /* @__PURE__ */ new Date();
@@ -13838,7 +14022,7 @@ var MemoryCompliance = class {
13838
14022
  if (!pia) throw new Error(`PIA not found: ${piaId}`);
13839
14023
  const newMitigation = {
13840
14024
  ...mitigation,
13841
- id: `mit_${Date.now()}_${Math.random().toString(36).substring(7)}`
14025
+ id: `mit_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`
13842
14026
  };
13843
14027
  pia.mitigations.push(newMitigation);
13844
14028
  pia.updatedAt = /* @__PURE__ */ new Date();
@@ -13875,7 +14059,7 @@ var MemoryCompliance = class {
13875
14059
  (c) => c.status === "non_compliant"
13876
14060
  ).length;
13877
14061
  const report = {
13878
- id: `report_${Date.now()}_${Math.random().toString(36).substring(7)}`,
14062
+ id: `report_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`,
13879
14063
  title: `${framework.toUpperCase()} Compliance Report`,
13880
14064
  framework,
13881
14065
  period,
@@ -13926,7 +14110,7 @@ var MemoryCompliance = class {
13926
14110
  }
13927
14111
  // Breach Management
13928
14112
  async recordBreach(breach) {
13929
- const id = `breach_${Date.now()}_${Math.random().toString(36).substring(7)}`;
14113
+ const id = `breach_${Date.now()}_${(0, import_crypto18.randomBytes)(4).toString("hex")}`;
13930
14114
  const newBreach = {
13931
14115
  ...breach,
13932
14116
  id,
@@ -14165,6 +14349,25 @@ var RAGConfigSchema = import_zod.z.object({
14165
14349
  message: "Pinecone requires apiKey and indexName; Weaviate requires host"
14166
14350
  }
14167
14351
  );
14352
+ var CryptoConfigSchema = import_zod.z.object({
14353
+ enabled: import_zod.z.boolean().default(false).describe("Enable field-level encryption"),
14354
+ masterKey: import_zod.z.string().optional().describe("256-bit master key as hex (64 chars). Required when enabled."),
14355
+ hmacKey: import_zod.z.string().optional().describe("HMAC key for deterministic hashing (derived from master key if not provided)")
14356
+ }).refine(
14357
+ (data) => {
14358
+ if (data.enabled) {
14359
+ return data.masterKey && data.masterKey.length >= 64;
14360
+ }
14361
+ return true;
14362
+ },
14363
+ {
14364
+ message: "Crypto requires a 256-bit master key (64 hex characters) when enabled"
14365
+ }
14366
+ );
14367
+ var SecurityConfigSchema = import_zod.z.object({
14368
+ enforceTls: import_zod.z.boolean().default(true).describe("Enforce TLS for production connections"),
14369
+ tlsWarnOnly: import_zod.z.boolean().default(false).describe("Warn instead of throwing when TLS is missing in production")
14370
+ });
14168
14371
  var RetryConfigSchema = import_zod.z.object({
14169
14372
  enabled: import_zod.z.boolean().default(true).describe("Enable retry for failed operations"),
14170
14373
  maxAttempts: import_zod.z.number().int().min(1).max(10).default(3).describe("Maximum retry attempts"),
@@ -14254,6 +14457,10 @@ var PlatformConfigSchema = import_zod.z.object({
14254
14457
  // AI configurations
14255
14458
  ai: AIConfigSchema.default({ enabled: false }),
14256
14459
  rag: RAGConfigSchema.default({ enabled: false }),
14460
+ // Crypto configuration
14461
+ crypto: CryptoConfigSchema.default({ enabled: false }),
14462
+ // Security configuration
14463
+ security: SecurityConfigSchema.default({}),
14257
14464
  // Resilience configuration
14258
14465
  resilience: ResilienceConfigSchema.default({}),
14259
14466
  // Observability configuration
@@ -14331,6 +14538,15 @@ function loadConfig() {
14331
14538
  embeddingApiKey: process.env.EMBEDDING_API_KEY || process.env.OPENAI_API_KEY,
14332
14539
  embeddingModel: process.env.EMBEDDING_MODEL
14333
14540
  },
14541
+ crypto: {
14542
+ enabled: process.env.CRYPTO_ENABLED === "true",
14543
+ masterKey: process.env.CRYPTO_MASTER_KEY,
14544
+ hmacKey: process.env.CRYPTO_HMAC_KEY
14545
+ },
14546
+ security: {
14547
+ enforceTls: process.env.SECURITY_ENFORCE_TLS !== "false",
14548
+ tlsWarnOnly: process.env.SECURITY_TLS_WARN_ONLY === "true"
14549
+ },
14334
14550
  resilience: {
14335
14551
  retry: {
14336
14552
  enabled: process.env.RESILIENCE_RETRY_ENABLED !== "false",
@@ -14737,13 +14953,14 @@ var MemoryEmail = class {
14737
14953
 
14738
14954
  // src/context/CorrelationContext.ts
14739
14955
  var import_async_hooks = require("async_hooks");
14956
+ var import_crypto19 = require("crypto");
14740
14957
  var CorrelationContextManager = class {
14741
14958
  storage = new import_async_hooks.AsyncLocalStorage();
14742
14959
  idGenerator;
14743
14960
  constructor() {
14744
14961
  this.idGenerator = () => {
14745
14962
  const timestamp = Date.now().toString(36);
14746
- const random = Math.random().toString(36).substring(2, 10);
14963
+ const random = (0, import_crypto19.randomBytes)(4).toString("hex");
14747
14964
  return `${timestamp}-${random}`;
14748
14965
  };
14749
14966
  }
@@ -15373,10 +15590,11 @@ var MemoryQueue = class {
15373
15590
  };
15374
15591
 
15375
15592
  // src/adapters/console/ConsoleEmail.ts
15593
+ var import_crypto20 = require("crypto");
15376
15594
  var ConsoleEmail = class {
15377
15595
  sentEmails = [];
15378
15596
  async send(message) {
15379
- const id = `console_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
15597
+ const id = `console_${Date.now()}_${(0, import_crypto20.randomBytes)(4).toString("hex")}`;
15380
15598
  console.log("\n" + "=".repeat(60));
15381
15599
  console.log("\u{1F4E7} EMAIL SENT (Console Adapter)");
15382
15600
  console.log("=".repeat(60));
@@ -15453,6 +15671,147 @@ var ConsoleEmail = class {
15453
15671
  // src/factory.ts
15454
15672
  init_IAI();
15455
15673
  init_IRAG();
15674
+
15675
+ // src/adapters/memory/MemoryCrypto.ts
15676
+ var import_crypto21 = require("crypto");
15677
+ var MemoryCrypto = class {
15678
+ keys = /* @__PURE__ */ new Map();
15679
+ activeKeyId;
15680
+ hmacKey;
15681
+ constructor(options) {
15682
+ const masterKeyBuf = options?.masterKey ? Buffer.from(options.masterKey, "hex") : (0, import_crypto21.randomBytes)(32);
15683
+ this.hmacKey = options?.hmacKey ? Buffer.from(options.hmacKey, "hex") : (0, import_crypto21.randomBytes)(32);
15684
+ const keyId = this.generateKeyId();
15685
+ this.keys.set(keyId, {
15686
+ id: keyId,
15687
+ key: masterKeyBuf,
15688
+ status: "active",
15689
+ createdAt: /* @__PURE__ */ new Date()
15690
+ });
15691
+ this.activeKeyId = keyId;
15692
+ }
15693
+ async encrypt(plaintext, options) {
15694
+ const keyId = options?.keyId || this.activeKeyId;
15695
+ const stored = this.keys.get(keyId);
15696
+ if (!stored) {
15697
+ throw new Error(`Key not found: ${keyId}`);
15698
+ }
15699
+ if (stored.status === "retired") {
15700
+ throw new Error(`Key is retired: ${keyId}`);
15701
+ }
15702
+ if (stored.status === "decrypt-only" && !options?.keyId) {
15703
+ throw new Error(`Key is decrypt-only: ${keyId}`);
15704
+ }
15705
+ const iv = (0, import_crypto21.randomBytes)(12);
15706
+ const cipher = (0, import_crypto21.createCipheriv)("aes-256-gcm", stored.key, iv);
15707
+ if (options?.aad) {
15708
+ cipher.setAAD(Buffer.from(options.aad, "utf8"));
15709
+ }
15710
+ const encrypted = Buffer.concat([
15711
+ cipher.update(plaintext, "utf8"),
15712
+ cipher.final()
15713
+ ]);
15714
+ const tag = cipher.getAuthTag();
15715
+ return {
15716
+ ciphertext: encrypted.toString("base64"),
15717
+ iv: iv.toString("base64"),
15718
+ tag: tag.toString("base64"),
15719
+ keyId,
15720
+ algorithm: "aes-256-gcm",
15721
+ version: 1
15722
+ };
15723
+ }
15724
+ async decrypt(field, options) {
15725
+ const stored = this.keys.get(field.keyId);
15726
+ if (!stored) {
15727
+ throw new Error(`Key not found: ${field.keyId}`);
15728
+ }
15729
+ if (stored.status === "retired") {
15730
+ throw new Error(`Key is retired and cannot decrypt: ${field.keyId}`);
15731
+ }
15732
+ const decipher = (0, import_crypto21.createDecipheriv)(
15733
+ "aes-256-gcm",
15734
+ stored.key,
15735
+ Buffer.from(field.iv, "base64")
15736
+ );
15737
+ decipher.setAuthTag(Buffer.from(field.tag, "base64"));
15738
+ if (options?.aad) {
15739
+ decipher.setAAD(Buffer.from(options.aad, "utf8"));
15740
+ }
15741
+ const decrypted = Buffer.concat([
15742
+ decipher.update(Buffer.from(field.ciphertext, "base64")),
15743
+ decipher.final()
15744
+ ]);
15745
+ return decrypted.toString("utf8");
15746
+ }
15747
+ async encryptDeterministic(plaintext, options) {
15748
+ const hash = await this.computeHash(plaintext);
15749
+ const encrypted = await this.encrypt(plaintext, options);
15750
+ return { hash, encrypted };
15751
+ }
15752
+ async computeHash(plaintext) {
15753
+ return (0, import_crypto21.createHmac)("sha256", this.hmacKey).update(plaintext, "utf8").digest("hex");
15754
+ }
15755
+ async encryptBatch(fields, options) {
15756
+ const result = {};
15757
+ for (const [key, value] of Object.entries(fields)) {
15758
+ result[key] = await this.encrypt(value, options);
15759
+ }
15760
+ return result;
15761
+ }
15762
+ async decryptBatch(fields, options) {
15763
+ const result = {};
15764
+ for (const [key, value] of Object.entries(fields)) {
15765
+ result[key] = await this.decrypt(value, options);
15766
+ }
15767
+ return result;
15768
+ }
15769
+ async rotateKey() {
15770
+ const previousKeyId = this.activeKeyId;
15771
+ const currentKey = this.keys.get(previousKeyId);
15772
+ if (currentKey) {
15773
+ currentKey.status = "decrypt-only";
15774
+ }
15775
+ const newKeyId = this.generateKeyId();
15776
+ this.keys.set(newKeyId, {
15777
+ id: newKeyId,
15778
+ key: (0, import_crypto21.randomBytes)(32),
15779
+ status: "active",
15780
+ createdAt: /* @__PURE__ */ new Date()
15781
+ });
15782
+ this.activeKeyId = newKeyId;
15783
+ return { newKeyId, previousKeyId };
15784
+ }
15785
+ async reEncrypt(field, options) {
15786
+ const plaintext = await this.decrypt(field);
15787
+ return this.encrypt(plaintext, options);
15788
+ }
15789
+ async listKeys() {
15790
+ return Array.from(this.keys.values()).map((k) => ({
15791
+ keyId: k.id,
15792
+ createdAt: k.createdAt,
15793
+ status: k.status
15794
+ }));
15795
+ }
15796
+ async getActiveKeyId() {
15797
+ return this.activeKeyId;
15798
+ }
15799
+ async healthCheck() {
15800
+ try {
15801
+ const testPlain = "health-check-test";
15802
+ const encrypted = await this.encrypt(testPlain);
15803
+ const decrypted = await this.decrypt(encrypted);
15804
+ return decrypted === testPlain;
15805
+ } catch {
15806
+ return false;
15807
+ }
15808
+ }
15809
+ generateKeyId() {
15810
+ return `key_${(0, import_crypto21.randomBytes)(8).toString("hex")}`;
15811
+ }
15812
+ };
15813
+
15814
+ // src/factory.ts
15456
15815
  async function createDatabaseAdapter(config) {
15457
15816
  switch (config.database.provider) {
15458
15817
  case "postgres": {
@@ -15753,15 +16112,70 @@ async function createRAGAdapter(config, ai) {
15753
16112
  return new MemoryRAG();
15754
16113
  }
15755
16114
  }
16115
+ async function createCryptoAdapter(config) {
16116
+ if (!config.crypto.enabled) {
16117
+ return null;
16118
+ }
16119
+ if (config.crypto.masterKey && config.crypto.masterKey.length >= 64) {
16120
+ const { NodeCrypto: NodeCrypto2 } = await Promise.resolve().then(() => (init_NodeCrypto(), NodeCrypto_exports));
16121
+ return new NodeCrypto2({
16122
+ masterKey: config.crypto.masterKey,
16123
+ hmacKey: config.crypto.hmacKey
16124
+ });
16125
+ }
16126
+ return new MemoryCrypto();
16127
+ }
16128
+ function validateTlsSecurity(config) {
16129
+ const isProduction = process.env.NODE_ENV === "production";
16130
+ if (!isProduction || !config.security.enforceTls) {
16131
+ return;
16132
+ }
16133
+ const warnings = [];
16134
+ if (config.database.provider === "postgres") {
16135
+ const connStr = config.database.connectionString || config.database.url || "";
16136
+ const hasSSL = config.database.ssl || connStr.includes("sslmode=require") || connStr.includes("sslmode=verify");
16137
+ if (!hasSSL) {
16138
+ warnings.push(
16139
+ "PostgreSQL: TLS/SSL not configured. Set database.ssl=true or add sslmode=require to connection string."
16140
+ );
16141
+ }
16142
+ }
16143
+ if (config.cache.provider === "redis") {
16144
+ const url = config.cache.url || "";
16145
+ if (url && !url.startsWith("rediss://")) {
16146
+ warnings.push(
16147
+ "Redis: Connection URL uses redis:// instead of rediss:// (TLS). Consider enabling TLS."
16148
+ );
16149
+ }
16150
+ }
16151
+ if (config.email.provider === "smtp") {
16152
+ if (!config.email.secure) {
16153
+ warnings.push(
16154
+ "SMTP: secure=false in production. Set email.secure=true for TLS."
16155
+ );
16156
+ }
16157
+ }
16158
+ if (warnings.length > 0) {
16159
+ const message = `[Security] TLS warnings in production:
16160
+ - ${warnings.join("\n - ")}`;
16161
+ if (config.security.tlsWarnOnly) {
16162
+ console.warn(message);
16163
+ } else {
16164
+ throw new Error(message);
16165
+ }
16166
+ }
16167
+ }
15756
16168
  async function createPlatformAsync(config) {
15757
16169
  const finalConfig = config ? deepMerge(loadConfig(), config) : loadConfig();
15758
- const [db, cache, storage, email, queue, tracing] = await Promise.all([
16170
+ validateTlsSecurity(finalConfig);
16171
+ const [db, cache, storage, email, queue, tracing, crypto2] = await Promise.all([
15759
16172
  createDatabaseAdapter(finalConfig),
15760
16173
  createCacheAdapter(finalConfig),
15761
16174
  createStorageAdapter(finalConfig),
15762
16175
  createEmailAdapter(finalConfig),
15763
16176
  createQueueAdapter(finalConfig),
15764
- createTracingAdapter(finalConfig)
16177
+ createTracingAdapter(finalConfig),
16178
+ createCryptoAdapter(finalConfig)
15765
16179
  ]);
15766
16180
  const logger = createLogger(finalConfig);
15767
16181
  const metrics = createMetrics(finalConfig);
@@ -15777,7 +16191,8 @@ async function createPlatformAsync(config) {
15777
16191
  metrics,
15778
16192
  tracing,
15779
16193
  ai,
15780
- rag
16194
+ rag,
16195
+ crypto2
15781
16196
  );
15782
16197
  }
15783
16198
  function createPlatform(config) {
@@ -15798,6 +16213,7 @@ function createPlatform(config) {
15798
16213
  const tracing = finalConfig.observability.tracing.provider === "memory" ? new MemoryTracing() : new NoopTracing();
15799
16214
  const ai = finalConfig.ai.enabled ? new MemoryAI() : null;
15800
16215
  const rag = finalConfig.rag.enabled ? new MemoryRAG() : null;
16216
+ const crypto2 = finalConfig.crypto.enabled ? new MemoryCrypto() : null;
15801
16217
  return createPlatformFromAdapters(
15802
16218
  db,
15803
16219
  cache,
@@ -15808,10 +16224,11 @@ function createPlatform(config) {
15808
16224
  metrics,
15809
16225
  tracing,
15810
16226
  ai,
15811
- rag
16227
+ rag,
16228
+ crypto2
15812
16229
  );
15813
16230
  }
15814
- function createPlatformFromAdapters(db, cache, storage, email, queue, logger, metrics, tracing, ai, rag) {
16231
+ function createPlatformFromAdapters(db, cache, storage, email, queue, logger, metrics, tracing, ai, rag, crypto2) {
15815
16232
  const platform = {
15816
16233
  db,
15817
16234
  cache,
@@ -15865,6 +16282,9 @@ function createPlatformFromAdapters(db, cache, storage, email, queue, logger, me
15865
16282
  if (rag) {
15866
16283
  platform.rag = rag;
15867
16284
  }
16285
+ if (crypto2) {
16286
+ platform.crypto = crypto2;
16287
+ }
15868
16288
  return platform;
15869
16289
  }
15870
16290
  function deepMerge(target, source) {
@@ -15887,11 +16307,11 @@ function deepMerge(target, source) {
15887
16307
  }
15888
16308
 
15889
16309
  // src/middleware/chain.ts
15890
- var import_crypto = require("crypto");
16310
+ var import_crypto26 = require("crypto");
15891
16311
  function createMiddlewareChain(options = {}) {
15892
16312
  const middlewares = [];
15893
16313
  const logger = options.logger ?? new NoopLogger();
15894
- const generateCorrelationId = options.generateCorrelationId ?? (() => (0, import_crypto.randomUUID)());
16314
+ const generateCorrelationId = options.generateCorrelationId ?? (() => (0, import_crypto26.randomUUID)());
15895
16315
  function sortMiddleware() {
15896
16316
  middlewares.sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100));
15897
16317
  }
@@ -16008,7 +16428,7 @@ function createMiddlewareContext(service, operation, args, logger, options = {})
16008
16428
  args,
16009
16429
  logger,
16010
16430
  startTime: Date.now(),
16011
- correlationId: options.correlationId ?? (0, import_crypto.randomUUID)(),
16431
+ correlationId: options.correlationId ?? (0, import_crypto26.randomUUID)(),
16012
16432
  tenantId: options.tenantId
16013
16433
  };
16014
16434
  }
@@ -17361,6 +17781,113 @@ function sanitizeForEmail(str) {
17361
17781
  return escapeHtml(str);
17362
17782
  }
17363
17783
 
17784
+ // src/security-headers.ts
17785
+ var SecurityHeaderPresets = {
17786
+ /** Minimal: basic headers only, no CSP */
17787
+ minimal: {
17788
+ csp: false,
17789
+ hsts: false
17790
+ },
17791
+ /** Standard: full CSP + HSTS for most apps */
17792
+ standard: {
17793
+ csp: true,
17794
+ hsts: true,
17795
+ frameOptions: "DENY"
17796
+ },
17797
+ /** Strict: deny all permissions, strict CSP, no frame embedding */
17798
+ strict: {
17799
+ csp: true,
17800
+ hsts: true,
17801
+ hstsMaxAge: 63072e3,
17802
+ // 2 years
17803
+ frameOptions: "DENY"
17804
+ }
17805
+ };
17806
+ function generateSecurityHeaders(config = {}) {
17807
+ const isProduction = config.isProduction ?? process.env.NODE_ENV === "production";
17808
+ const frameOptions = config.frameOptions ?? "DENY";
17809
+ const enableCsp = config.csp ?? true;
17810
+ const enableHsts = config.hsts ?? true;
17811
+ const hstsMaxAge = config.hstsMaxAge ?? 31536e3;
17812
+ const baseHeaders = [
17813
+ { key: "X-Frame-Options", value: frameOptions },
17814
+ { key: "X-Content-Type-Options", value: "nosniff" },
17815
+ // Modern browsers use CSP, not XSS-Protection. Value '0' disables the
17816
+ // legacy filter which can itself introduce vulnerabilities.
17817
+ { key: "X-XSS-Protection", value: "0" },
17818
+ {
17819
+ key: "Referrer-Policy",
17820
+ value: "strict-origin-when-cross-origin"
17821
+ },
17822
+ {
17823
+ key: "Permissions-Policy",
17824
+ value: "camera=(), microphone=(), geolocation=()"
17825
+ }
17826
+ ];
17827
+ const entries = [
17828
+ { source: "/:path*", headers: baseHeaders }
17829
+ ];
17830
+ if (isProduction) {
17831
+ const prodHeaders = [];
17832
+ if (enableHsts) {
17833
+ prodHeaders.push({
17834
+ key: "Strict-Transport-Security",
17835
+ value: `max-age=${hstsMaxAge}; includeSubDomains`
17836
+ });
17837
+ }
17838
+ if (enableCsp) {
17839
+ const csp = buildCsp(config);
17840
+ prodHeaders.push({ key: "Content-Security-Policy", value: csp });
17841
+ }
17842
+ if (prodHeaders.length > 0) {
17843
+ entries.push({ source: "/:path*", headers: prodHeaders });
17844
+ }
17845
+ }
17846
+ return entries;
17847
+ }
17848
+ function buildCsp(config) {
17849
+ const scriptSrc = [
17850
+ "'self'",
17851
+ "'unsafe-inline'",
17852
+ "'unsafe-eval'",
17853
+ ...config.cspScriptSrc ?? []
17854
+ ];
17855
+ const styleSrc = [
17856
+ "'self'",
17857
+ "'unsafe-inline'",
17858
+ "https://fonts.googleapis.com",
17859
+ ...config.cspStyleSrc ?? []
17860
+ ];
17861
+ const imgSrc = [
17862
+ "'self'",
17863
+ "data:",
17864
+ "https:",
17865
+ "blob:",
17866
+ ...config.cspImgSrc ?? []
17867
+ ];
17868
+ const fontSrc = ["'self'", "data:", "https://fonts.gstatic.com"];
17869
+ const connectSrc = ["'self'", ...config.cspConnectSrc ?? []];
17870
+ const frameSrc = [...config.cspFrameSrc ?? []];
17871
+ const directives = [
17872
+ `default-src 'self'`,
17873
+ `script-src ${scriptSrc.join(" ")}`,
17874
+ `style-src ${styleSrc.join(" ")}`,
17875
+ `img-src ${imgSrc.join(" ")}`,
17876
+ `font-src ${fontSrc.join(" ")}`,
17877
+ `connect-src ${connectSrc.join(" ")}`
17878
+ ];
17879
+ if (frameSrc.length > 0) {
17880
+ directives.push(`frame-src ${frameSrc.join(" ")}`);
17881
+ }
17882
+ directives.push(
17883
+ `object-src 'none'`,
17884
+ `base-uri 'self'`,
17885
+ `form-action 'self'`,
17886
+ `frame-ancestors 'none'`
17887
+ );
17888
+ return directives.join("; ");
17889
+ }
17890
+
17364
17891
  // src/api.ts
17365
17892
  var ApiErrorCode = {
17366
17893
  VALIDATION_ERROR: "VALIDATION_ERROR",
@@ -18564,7 +19091,7 @@ var MemoryAuditLog = class {
18564
19091
  };
18565
19092
 
18566
19093
  // src/adapters/memory/MemoryWebhook.ts
18567
- var import_crypto2 = require("crypto");
19094
+ var import_crypto27 = require("crypto");
18568
19095
  var MemoryWebhook = class {
18569
19096
  endpoints = /* @__PURE__ */ new Map();
18570
19097
  deliveries = /* @__PURE__ */ new Map();
@@ -18846,7 +19373,7 @@ var MemoryWebhook = class {
18846
19373
  config.secret,
18847
19374
  algorithm
18848
19375
  );
18849
- const providedSig = signature.replace(/^(sha256=|sha512=|sha1=)/, "");
19376
+ const providedSig = signature.replace(/^(sha256=|sha512=)/, "");
18850
19377
  if (providedSig !== expectedSignature) {
18851
19378
  return { valid: false, error: "Invalid signature" };
18852
19379
  }
@@ -18951,7 +19478,7 @@ var MemoryWebhook = class {
18951
19478
  this.deliveries.set(delivery.id, delivery);
18952
19479
  }
18953
19480
  async executeDelivery(endpoint, event, attemptNumber) {
18954
- const attemptId = `att_${Date.now().toString(36)}${Math.random().toString(36).substring(2, 8)}`;
19481
+ const attemptId = `att_${Date.now().toString(36)}${(0, import_crypto27.randomBytes)(4).toString("hex")}`;
18955
19482
  const startTime = Date.now();
18956
19483
  if (this.config.simulatedDelay > 0) {
18957
19484
  await new Promise(
@@ -19005,7 +19532,7 @@ var MemoryWebhook = class {
19005
19532
  this.endpoints.set(endpoint.id, endpoint);
19006
19533
  }
19007
19534
  computeSignature(payload, secret, algorithm) {
19008
- return (0, import_crypto2.createHmac)(algorithm, secret).update(payload).digest("hex");
19535
+ return (0, import_crypto27.createHmac)(algorithm, secret).update(payload).digest("hex");
19009
19536
  }
19010
19537
  };
19011
19538
 
@@ -19356,6 +19883,7 @@ var MemoryNotification = class {
19356
19883
  };
19357
19884
 
19358
19885
  // src/adapters/memory/MemoryScheduler.ts
19886
+ var import_crypto28 = require("crypto");
19359
19887
  var MemoryScheduler = class {
19360
19888
  config;
19361
19889
  schedules = /* @__PURE__ */ new Map();
@@ -19639,7 +20167,7 @@ var MemoryScheduler = class {
19639
20167
  }
19640
20168
  }
19641
20169
  async executeSchedule(schedule) {
19642
- const executionId = `exec_${Date.now().toString(36)}${Math.random().toString(36).substring(2, 8)}`;
20170
+ const executionId = `exec_${Date.now().toString(36)}${(0, import_crypto28.randomBytes)(4).toString("hex")}`;
19643
20171
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
19644
20172
  const execution = {
19645
20173
  id: executionId,
@@ -20119,6 +20647,7 @@ CREATE INDEX IF NOT EXISTS idx_${tableName}_trace_id ON ${tableName}((context->>
20119
20647
  };
20120
20648
 
20121
20649
  // src/adapters/database/DatabaseErrorReporter.ts
20650
+ var import_crypto29 = require("crypto");
20122
20651
  var DatabaseErrorReporter = class {
20123
20652
  db;
20124
20653
  errorsTable;
@@ -20413,7 +20942,7 @@ CREATE INDEX IF NOT EXISTS idx_${breadcrumbsTable}_error ON ${breadcrumbsTable}(
20413
20942
  if (report.breadcrumbs && report.breadcrumbs.length > 0) {
20414
20943
  for (const crumb of report.breadcrumbs) {
20415
20944
  await this.db.from(this.breadcrumbsTable).insert({
20416
- id: `bc_${Date.now().toString(36)}${Math.random().toString(36).substring(2, 8)}`,
20945
+ id: `bc_${Date.now().toString(36)}${(0, import_crypto29.randomBytes)(4).toString("hex")}`,
20417
20946
  error_id: report.id,
20418
20947
  category: crumb.category,
20419
20948
  message: crumb.message,
@@ -20453,6 +20982,7 @@ CREATE INDEX IF NOT EXISTS idx_${breadcrumbsTable}_error ON ${breadcrumbsTable}(
20453
20982
  };
20454
20983
 
20455
20984
  // src/adapters/database/DatabasePromptStore.ts
20985
+ var import_crypto30 = require("crypto");
20456
20986
  var DatabasePromptStore = class {
20457
20987
  db;
20458
20988
  cache;
@@ -20592,7 +21122,7 @@ CREATE INDEX IF NOT EXISTS idx_${tablePrefix}usage_experiment ON ${tablePrefix}p
20592
21122
  // Prompt CRUD
20593
21123
  // ═══════════════════════════════════════════════════════════════
20594
21124
  async create(prompt) {
20595
- const id = `prompt_${Date.now()}_${Math.random().toString(36).substring(7)}`;
21125
+ const id = `prompt_${Date.now()}_${(0, import_crypto30.randomBytes)(4).toString("hex")}`;
20596
21126
  const now = /* @__PURE__ */ new Date();
20597
21127
  const newPrompt = {
20598
21128
  ...prompt,
@@ -20620,7 +21150,7 @@ CREATE INDEX IF NOT EXISTS idx_${tablePrefix}usage_experiment ON ${tablePrefix}p
20620
21150
  created_by: newPrompt.createdBy,
20621
21151
  updated_by: newPrompt.updatedBy
20622
21152
  }).execute();
20623
- const versionId = `pv_${Date.now()}_${Math.random().toString(36).substring(7)}`;
21153
+ const versionId = `pv_${Date.now()}_${(0, import_crypto30.randomBytes)(4).toString("hex")}`;
20624
21154
  await this.db.from(this.versionsTable).insert({
20625
21155
  id: versionId,
20626
21156
  prompt_id: id,
@@ -20689,7 +21219,7 @@ CREATE INDEX IF NOT EXISTS idx_${tablePrefix}usage_experiment ON ${tablePrefix}p
20689
21219
  await this.db.from(this.versionsTable).update({ is_latest: false }).where("prompt_id", "=", prompt.id).execute();
20690
21220
  const versionsResult = await this.db.from(this.versionsTable).where("prompt_id", "=", prompt.id).execute();
20691
21221
  const newVersionNum = versionsResult.data.length + 1;
20692
- const versionId = `pv_${Date.now()}_${Math.random().toString(36).substring(7)}`;
21222
+ const versionId = `pv_${Date.now()}_${(0, import_crypto30.randomBytes)(4).toString("hex")}`;
20693
21223
  await this.db.from(this.versionsTable).insert({
20694
21224
  id: versionId,
20695
21225
  prompt_id: prompt.id,
@@ -20944,7 +21474,7 @@ ${v2.content}`;
20944
21474
  // A/B Testing
20945
21475
  // ═══════════════════════════════════════════════════════════════
20946
21476
  async createExperiment(experiment) {
20947
- const id = `exp_${Date.now()}_${Math.random().toString(36).substring(7)}`;
21477
+ const id = `exp_${Date.now()}_${(0, import_crypto30.randomBytes)(4).toString("hex")}`;
20948
21478
  const now = /* @__PURE__ */ new Date();
20949
21479
  const newExperiment = {
20950
21480
  ...experiment,
@@ -21058,7 +21588,7 @@ ${v2.content}`;
21058
21588
  // Prompt Chains
21059
21589
  // ═══════════════════════════════════════════════════════════════
21060
21590
  async createChain(chain) {
21061
- const id = `chain_${Date.now()}_${Math.random().toString(36).substring(7)}`;
21591
+ const id = `chain_${Date.now()}_${(0, import_crypto30.randomBytes)(4).toString("hex")}`;
21062
21592
  const now = /* @__PURE__ */ new Date();
21063
21593
  const newChain = {
21064
21594
  ...chain,
@@ -21156,7 +21686,7 @@ ${v2.content}`;
21156
21686
  // Usage & Analytics
21157
21687
  // ═══════════════════════════════════════════════════════════════
21158
21688
  async recordUsage(record) {
21159
- const id = `usage_${Date.now()}_${Math.random().toString(36).substring(7)}`;
21689
+ const id = `usage_${Date.now()}_${(0, import_crypto30.randomBytes)(4).toString("hex")}`;
21160
21690
  const now = /* @__PURE__ */ new Date();
21161
21691
  const usageRecord = {
21162
21692
  ...record,
@@ -21342,8 +21872,9 @@ ${v2.content}`;
21342
21872
  };
21343
21873
 
21344
21874
  // src/adapters/database/DatabaseCompliance.ts
21875
+ var import_crypto31 = require("crypto");
21345
21876
  function generateId(prefix) {
21346
- return `${prefix}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
21877
+ return `${prefix}_${Date.now()}_${(0, import_crypto31.randomBytes)(4).toString("hex")}`;
21347
21878
  }
21348
21879
  function toDate(value) {
21349
21880
  return value ? new Date(value) : void 0;
@@ -21534,7 +22065,7 @@ var DatabaseCompliance = class {
21534
22065
  async createDsar(options) {
21535
22066
  const id = generateId("dsar");
21536
22067
  const now = (/* @__PURE__ */ new Date()).toISOString();
21537
- const verificationToken = `verify_${Math.random().toString(36).substring(2)}`;
22068
+ const verificationToken = `verify_${(0, import_crypto31.randomBytes)(16).toString("hex")}`;
21538
22069
  const result = await this.db.from("compliance_dsars").insert({
21539
22070
  id,
21540
22071
  type: options.type,
@@ -22473,6 +23004,7 @@ var DatabaseCompliance = class {
22473
23004
  };
22474
23005
 
22475
23006
  // src/adapters/database/DatabaseAIUsage.ts
23007
+ var import_crypto32 = require("crypto");
22476
23008
  var DatabaseAIUsage = class {
22477
23009
  db;
22478
23010
  config;
@@ -22486,7 +23018,7 @@ var DatabaseAIUsage = class {
22486
23018
  // Usage Recording
22487
23019
  // ─────────────────────────────────────────────────────────────
22488
23020
  async record(record) {
22489
- const id = `usage_${Date.now()}_${Math.random().toString(36).substring(7)}`;
23021
+ const id = `usage_${Date.now()}_${(0, import_crypto32.randomBytes)(4).toString("hex")}`;
22490
23022
  const now = /* @__PURE__ */ new Date();
22491
23023
  await this.db.from(`${this.prefix}records`).insert({
22492
23024
  id,
@@ -22593,7 +23125,7 @@ var DatabaseAIUsage = class {
22593
23125
  quota.category
22594
23126
  );
22595
23127
  const period = this.getPeriodBounds(quota.period, /* @__PURE__ */ new Date());
22596
- const id = existing?.id || `quota_${Date.now()}_${Math.random().toString(36).substring(7)}`;
23128
+ const id = existing?.id || `quota_${Date.now()}_${(0, import_crypto32.randomBytes)(4).toString("hex")}`;
22597
23129
  const data = {
22598
23130
  id,
22599
23131
  tenant_id: quota.tenantId,
@@ -22730,7 +23262,7 @@ var DatabaseAIUsage = class {
22730
23262
  existingResult.data[0]
22731
23263
  ) : null;
22732
23264
  const period = this.getPeriodBounds(budget.period, /* @__PURE__ */ new Date());
22733
- const id = existing?.id || `budget_${Date.now()}_${Math.random().toString(36).substring(7)}`;
23265
+ const id = existing?.id || `budget_${Date.now()}_${(0, import_crypto32.randomBytes)(4).toString("hex")}`;
22734
23266
  const data = {
22735
23267
  id,
22736
23268
  tenant_id: budget.tenantId,
@@ -23029,7 +23561,7 @@ var DatabaseAIUsage = class {
23029
23561
  }
23030
23562
  const items = Array.from(itemsMap.values());
23031
23563
  const subtotal = items.reduce((sum, item) => sum + item.costUsd, 0);
23032
- const id = `inv_${Date.now()}_${Math.random().toString(36).substring(7)}`;
23564
+ const id = `inv_${Date.now()}_${(0, import_crypto32.randomBytes)(4).toString("hex")}`;
23033
23565
  const now = /* @__PURE__ */ new Date();
23034
23566
  await this.db.from(`${this.prefix}invoices`).insert({
23035
23567
  id,
@@ -23251,7 +23783,7 @@ var DatabaseAIUsage = class {
23251
23783
  }
23252
23784
  }
23253
23785
  async createAlert(tenantId, type, severity, message, metadata) {
23254
- const id = `alert_${Date.now()}_${Math.random().toString(36).substring(7)}`;
23786
+ const id = `alert_${Date.now()}_${(0, import_crypto32.randomBytes)(4).toString("hex")}`;
23255
23787
  await this.db.from(`${this.prefix}alerts`).insert({
23256
23788
  id,
23257
23789
  tenant_id: tenantId,
@@ -23457,6 +23989,7 @@ var DatabaseAIUsage = class {
23457
23989
  };
23458
23990
 
23459
23991
  // src/adapters/database/DatabaseNotification.ts
23992
+ var import_crypto33 = require("crypto");
23460
23993
  var DatabaseNotification = class {
23461
23994
  db;
23462
23995
  email;
@@ -23694,7 +24227,7 @@ var DatabaseNotification = class {
23694
24227
  // PUSH SUBSCRIPTIONS
23695
24228
  // ═══════════════════════════════════════════════════════════════
23696
24229
  async registerPushSubscription(userId, subscription) {
23697
- const id = `push_${Date.now()}_${Math.random().toString(36).substring(7)}`;
24230
+ const id = `push_${Date.now()}_${(0, import_crypto33.randomBytes)(4).toString("hex")}`;
23698
24231
  const existing = await this.db.from(`${this.prefix}push_subscriptions`).where("user_id", "=", userId).where("endpoint", "=", subscription.endpoint).execute();
23699
24232
  if (existing.data && existing.data.length > 0) {
23700
24233
  await this.db.from(`${this.prefix}push_subscriptions`).where("user_id", "=", userId).where("endpoint", "=", subscription.endpoint).update({
@@ -23792,7 +24325,7 @@ var DatabaseNotification = class {
23792
24325
  // TOPICS
23793
24326
  // ═══════════════════════════════════════════════════════════════
23794
24327
  async subscribeToTopic(userId, topic) {
23795
- const id = `topic_${Date.now()}_${Math.random().toString(36).substring(7)}`;
24328
+ const id = `topic_${Date.now()}_${(0, import_crypto33.randomBytes)(4).toString("hex")}`;
23796
24329
  const existing = await this.db.from(`${this.prefix}notification_topic_subs`).where("user_id", "=", userId).where("topic", "=", topic).execute();
23797
24330
  if (!existing.data || existing.data.length === 0) {
23798
24331
  await this.db.from(`${this.prefix}notification_topic_subs`).insert({
@@ -23873,7 +24406,7 @@ var DatabaseNotification = class {
23873
24406
  // PRIVATE HELPERS
23874
24407
  // ═══════════════════════════════════════════════════════════════
23875
24408
  async logDelivery(notificationId, channel, status, messageId, error) {
23876
- const id = `del_${Date.now()}_${Math.random().toString(36).substring(7)}`;
24409
+ const id = `del_${Date.now()}_${(0, import_crypto33.randomBytes)(4).toString("hex")}`;
23877
24410
  try {
23878
24411
  await this.db.from(`${this.prefix}notification_delivery_log`).insert({
23879
24412
  id,
@@ -23935,6 +24468,7 @@ var DatabaseNotification = class {
23935
24468
  };
23936
24469
 
23937
24470
  // src/adapters/database/DatabaseBilling.ts
24471
+ var import_crypto34 = require("crypto");
23938
24472
  var DatabaseBilling = class {
23939
24473
  db;
23940
24474
  prefix;
@@ -23957,7 +24491,7 @@ var DatabaseBilling = class {
23957
24491
  return `${this.prefix}${name}`;
23958
24492
  }
23959
24493
  generateId(prefix) {
23960
- return `${prefix}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
24494
+ return `${prefix}_${Date.now()}_${(0, import_crypto34.randomBytes)(4).toString("hex")}`;
23961
24495
  }
23962
24496
  // ─────────────────────────────────────────────────────────────
23963
24497
  // Product & Price Management
@@ -25455,6 +25989,7 @@ var DatabaseBilling = class {
25455
25989
  };
25456
25990
 
25457
25991
  // src/adapters/scheduler/QueueScheduler.ts
25992
+ var import_crypto35 = require("crypto");
25458
25993
  var QueueScheduler = class {
25459
25994
  queue;
25460
25995
  db;
@@ -25870,7 +26405,7 @@ CREATE INDEX IF NOT EXISTS idx_${executionsTable}_started ON ${executionsTable}(
25870
26405
  }
25871
26406
  }
25872
26407
  async executeSchedule(schedule) {
25873
- const executionId = `exec_${Date.now().toString(36)}${Math.random().toString(36).substring(2, 8)}`;
26408
+ const executionId = `exec_${Date.now().toString(36)}${(0, import_crypto35.randomBytes)(4).toString("hex")}`;
25874
26409
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
25875
26410
  const execution = {
25876
26411
  id: executionId,
@@ -26033,7 +26568,7 @@ CREATE INDEX IF NOT EXISTS idx_${executionsTable}_started ON ${executionsTable}(
26033
26568
  };
26034
26569
 
26035
26570
  // src/adapters/webhook/HttpWebhook.ts
26036
- var import_crypto3 = require("crypto");
26571
+ var import_crypto36 = require("crypto");
26037
26572
  var HttpWebhook = class {
26038
26573
  db;
26039
26574
  queue;
@@ -26375,14 +26910,14 @@ var HttpWebhook = class {
26375
26910
  config.secret,
26376
26911
  algorithm
26377
26912
  );
26378
- const providedSig = signature.replace(/^(sha256=|sha512=|sha1=)/, "");
26913
+ const providedSig = signature.replace(/^(sha256=|sha512=)/, "");
26379
26914
  try {
26380
26915
  const providedBuffer = Buffer.from(providedSig, "hex");
26381
26916
  const expectedBuffer = Buffer.from(expectedSignature, "hex");
26382
26917
  if (providedBuffer.length !== expectedBuffer.length) {
26383
26918
  return { valid: false, error: "Invalid signature" };
26384
26919
  }
26385
- if (!(0, import_crypto3.timingSafeEqual)(providedBuffer, expectedBuffer)) {
26920
+ if (!(0, import_crypto36.timingSafeEqual)(providedBuffer, expectedBuffer)) {
26386
26921
  return { valid: false, error: "Invalid signature" };
26387
26922
  }
26388
26923
  } catch {
@@ -26631,7 +27166,7 @@ CREATE INDEX IF NOT EXISTS idx_${attemptsTable}_delivery ON ${attemptsTable}(del
26631
27166
  await this.saveDelivery(delivery);
26632
27167
  }
26633
27168
  async executeDelivery(endpoint, event, attemptNumber) {
26634
- const attemptId = `att_${Date.now().toString(36)}${Math.random().toString(36).substring(2, 8)}`;
27169
+ const attemptId = `att_${Date.now().toString(36)}${(0, import_crypto36.randomBytes)(4).toString("hex")}`;
26635
27170
  const startTime = Date.now();
26636
27171
  const payloadStr = JSON.stringify(event);
26637
27172
  const signature = this.computeSignature(
@@ -26735,7 +27270,7 @@ CREATE INDEX IF NOT EXISTS idx_${attemptsTable}_delivery ON ${attemptsTable}(del
26735
27270
  await this.saveEndpoint(endpoint);
26736
27271
  }
26737
27272
  computeSignature(payload, secret, algorithm) {
26738
- return (0, import_crypto3.createHmac)(algorithm, secret).update(payload).digest("hex");
27273
+ return (0, import_crypto36.createHmac)(algorithm, secret).update(payload).digest("hex");
26739
27274
  }
26740
27275
  endpointToRow(endpoint) {
26741
27276
  return {
@@ -28057,6 +28592,9 @@ init_PineconeRAG();
28057
28592
  // src/adapters/weaviate/index.ts
28058
28593
  init_WeaviateRAG();
28059
28594
 
28595
+ // src/index.ts
28596
+ init_NodeCrypto();
28597
+
28060
28598
  // src/adapters/oidc/GenericOIDCAuthSSO.ts
28061
28599
  function generateRandomString(length) {
28062
28600
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
@@ -28650,6 +29188,7 @@ var GenericOIDCAuthSSO = class {
28650
29188
  };
28651
29189
 
28652
29190
  // src/adapters/postgres-tenant/PostgresTenant.ts
29191
+ var import_crypto37 = require("crypto");
28653
29192
  var tenantContextMap = /* @__PURE__ */ new Map();
28654
29193
  var contextIdCounter2 = 0;
28655
29194
  var currentContextId2 = null;
@@ -29431,7 +29970,7 @@ var PostgresTenant = class {
29431
29970
  }
29432
29971
  };
29433
29972
  function generateId2() {
29434
- return Math.random().toString(36).substring(2) + Date.now().toString(36);
29973
+ return (0, import_crypto37.randomBytes)(8).toString("hex") + Date.now().toString(36);
29435
29974
  }
29436
29975
 
29437
29976
  // src/migrations/Migrator.ts
@@ -30214,6 +30753,7 @@ function getEnterpriseMigrations(features) {
30214
30753
  ConsoleEmail,
30215
30754
  ConsoleLogger,
30216
30755
  CronPresets,
30756
+ CryptoConfigSchema,
30217
30757
  DEFAULT_BULKHEAD_OPTIONS,
30218
30758
  DEFAULT_CIRCUIT_BREAKER_OPTIONS,
30219
30759
  DEFAULT_RETRY_OPTIONS,
@@ -30245,6 +30785,7 @@ function getEnterpriseMigrations(features) {
30245
30785
  MemoryBilling,
30246
30786
  MemoryCache,
30247
30787
  MemoryCompliance,
30788
+ MemoryCrypto,
30248
30789
  MemoryDatabase,
30249
30790
  MemoryDevPortal,
30250
30791
  MemoryDevice,
@@ -30266,6 +30807,7 @@ function getEnterpriseMigrations(features) {
30266
30807
  MetricsConfigSchema,
30267
30808
  MiddlewareConfigSchema,
30268
30809
  Migrator,
30810
+ NodeCrypto,
30269
30811
  NoopLogger,
30270
30812
  NoopMetrics,
30271
30813
  NoopTracing,
@@ -30293,6 +30835,8 @@ function getEnterpriseMigrations(features) {
30293
30835
  RetryPredicates,
30294
30836
  S3Storage,
30295
30837
  SQL,
30838
+ SecurityConfigSchema,
30839
+ SecurityHeaderPresets,
30296
30840
  SmtpEmail,
30297
30841
  StorageConfigSchema,
30298
30842
  StorageProviderSchema,
@@ -30382,6 +30926,7 @@ function getEnterpriseMigrations(features) {
30382
30926
  generatePaymentId,
30383
30927
  generateScheduleId,
30384
30928
  generateSecureToken,
30929
+ generateSecurityHeaders,
30385
30930
  generateVersion,
30386
30931
  generateWebhookId,
30387
30932
  generateWebhookSecret,