@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.mjs CHANGED
@@ -1,5 +1,11 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
3
9
  var __esm = (fn, res) => function __init() {
4
10
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
11
  };
@@ -387,6 +393,7 @@ var init_IAI = __esm({
387
393
  });
388
394
 
389
395
  // src/interfaces/IRAG.ts
396
+ import { randomBytes as randomBytes13 } from "crypto";
390
397
  var ChunkingPresets, MemoryRAG;
391
398
  var init_IRAG = __esm({
392
399
  "src/interfaces/IRAG.ts"() {
@@ -516,7 +523,7 @@ var init_IRAG = __esm({
516
523
  }
517
524
  async ingestOne(collection, document, options) {
518
525
  const startTime = Date.now();
519
- const docId = `doc_${Date.now()}_${Math.random().toString(36).substring(7)}`;
526
+ const docId = `doc_${Date.now()}_${randomBytes13(4).toString("hex")}`;
520
527
  const now = /* @__PURE__ */ new Date();
521
528
  try {
522
529
  const col = await this.getCollection(collection);
@@ -1059,6 +1066,7 @@ var PostgresDatabase_exports = {};
1059
1066
  __export(PostgresDatabase_exports, {
1060
1067
  PostgresDatabase: () => PostgresDatabase
1061
1068
  });
1069
+ import { randomBytes as randomBytes22 } from "crypto";
1062
1070
  function toPoolConfig(config) {
1063
1071
  const poolConfig = {};
1064
1072
  if (config.connectionString) {
@@ -1209,7 +1217,7 @@ var init_PostgresDatabase = __esm({
1209
1217
  }
1210
1218
  }
1211
1219
  async transaction(fn) {
1212
- const savepointName = `sp_${Date.now()}_${Math.random().toString(36).slice(2)}`;
1220
+ const savepointName = `sp_${Date.now()}_${randomBytes22(4).toString("hex")}`;
1213
1221
  try {
1214
1222
  await this.client.query(`SAVEPOINT ${savepointName}`);
1215
1223
  const result = await fn(this);
@@ -5445,6 +5453,7 @@ __export(PineconeRAG_exports, {
5445
5453
  PineconeRAG: () => PineconeRAG,
5446
5454
  createPineconeRAG: () => createPineconeRAG
5447
5455
  });
5456
+ import { randomBytes as randomBytes23 } from "crypto";
5448
5457
  function createPineconeRAG(config) {
5449
5458
  return new PineconeRAG(config);
5450
5459
  }
@@ -5602,7 +5611,7 @@ var init_PineconeRAG = __esm({
5602
5611
  throw new Error(`Collection ${collection} not found`);
5603
5612
  }
5604
5613
  const now = /* @__PURE__ */ new Date();
5605
- const documentId = `doc_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
5614
+ const documentId = `doc_${Date.now()}_${randomBytes23(4).toString("hex")}`;
5606
5615
  const doc = {
5607
5616
  id: documentId,
5608
5617
  source: document.source,
@@ -6166,6 +6175,7 @@ __export(WeaviateRAG_exports, {
6166
6175
  WeaviateRAG: () => WeaviateRAG,
6167
6176
  createWeaviateRAG: () => createWeaviateRAG
6168
6177
  });
6178
+ import { randomBytes as randomBytes24 } from "crypto";
6169
6179
  function createWeaviateRAG(config) {
6170
6180
  return new WeaviateRAG(config);
6171
6181
  }
@@ -6360,7 +6370,7 @@ var init_WeaviateRAG = __esm({
6360
6370
  const client = await this.getClient();
6361
6371
  const className = this.getClassName(collection);
6362
6372
  const now = /* @__PURE__ */ new Date();
6363
- const documentId = `doc_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
6373
+ const documentId = `doc_${Date.now()}_${randomBytes24(4).toString("hex")}`;
6364
6374
  const doc = {
6365
6375
  id: documentId,
6366
6376
  source: document.source,
@@ -6935,7 +6945,185 @@ var init_WeaviateRAG = __esm({
6935
6945
  }
6936
6946
  });
6937
6947
 
6948
+ // src/adapters/node-crypto/NodeCrypto.ts
6949
+ var NodeCrypto_exports = {};
6950
+ __export(NodeCrypto_exports, {
6951
+ NodeCrypto: () => NodeCrypto
6952
+ });
6953
+ import {
6954
+ randomBytes as randomBytes25,
6955
+ createCipheriv as createCipheriv2,
6956
+ createDecipheriv as createDecipheriv2,
6957
+ createHmac as createHmac2,
6958
+ hkdfSync
6959
+ } from "crypto";
6960
+ var NodeCrypto;
6961
+ var init_NodeCrypto = __esm({
6962
+ "src/adapters/node-crypto/NodeCrypto.ts"() {
6963
+ "use strict";
6964
+ NodeCrypto = class {
6965
+ masterKey;
6966
+ hmacKey;
6967
+ keys = /* @__PURE__ */ new Map();
6968
+ activeKeyId;
6969
+ keyCounter = 0;
6970
+ constructor(config) {
6971
+ if (!config.masterKey || config.masterKey.length < 64) {
6972
+ throw new Error(
6973
+ "NodeCrypto requires a 256-bit master key (64 hex characters)"
6974
+ );
6975
+ }
6976
+ this.masterKey = Buffer.from(config.masterKey, "hex");
6977
+ this.hmacKey = config.hmacKey ? Buffer.from(config.hmacKey, "hex") : Buffer.from(
6978
+ hkdfSync("sha256", this.masterKey, "", "hmac-key", 32)
6979
+ );
6980
+ const keyId = this.generateKeyId();
6981
+ const dek = this.deriveDEK(keyId);
6982
+ this.keys.set(keyId, {
6983
+ id: keyId,
6984
+ dek,
6985
+ status: "active",
6986
+ createdAt: /* @__PURE__ */ new Date()
6987
+ });
6988
+ this.activeKeyId = keyId;
6989
+ }
6990
+ async encrypt(plaintext, options) {
6991
+ const keyId = options?.keyId || this.activeKeyId;
6992
+ const stored = this.keys.get(keyId);
6993
+ if (!stored) {
6994
+ throw new Error(`Key not found: ${keyId}`);
6995
+ }
6996
+ if (stored.status === "retired") {
6997
+ throw new Error(`Key is retired and cannot encrypt: ${keyId}`);
6998
+ }
6999
+ if (stored.status === "decrypt-only" && !options?.keyId) {
7000
+ throw new Error(`Key is decrypt-only: ${keyId}`);
7001
+ }
7002
+ const iv = randomBytes25(12);
7003
+ const cipher = createCipheriv2("aes-256-gcm", stored.dek, iv);
7004
+ if (options?.aad) {
7005
+ cipher.setAAD(Buffer.from(options.aad, "utf8"));
7006
+ }
7007
+ const encrypted = Buffer.concat([
7008
+ cipher.update(plaintext, "utf8"),
7009
+ cipher.final()
7010
+ ]);
7011
+ const tag = cipher.getAuthTag();
7012
+ return {
7013
+ ciphertext: encrypted.toString("base64"),
7014
+ iv: iv.toString("base64"),
7015
+ tag: tag.toString("base64"),
7016
+ keyId,
7017
+ algorithm: "aes-256-gcm",
7018
+ version: 1
7019
+ };
7020
+ }
7021
+ async decrypt(field, options) {
7022
+ const stored = this.keys.get(field.keyId);
7023
+ if (!stored) {
7024
+ throw new Error(`Key not found: ${field.keyId}`);
7025
+ }
7026
+ if (stored.status === "retired") {
7027
+ throw new Error(`Key is retired and cannot decrypt: ${field.keyId}`);
7028
+ }
7029
+ const decipher = createDecipheriv2(
7030
+ "aes-256-gcm",
7031
+ stored.dek,
7032
+ Buffer.from(field.iv, "base64")
7033
+ );
7034
+ decipher.setAuthTag(Buffer.from(field.tag, "base64"));
7035
+ if (options?.aad) {
7036
+ decipher.setAAD(Buffer.from(options.aad, "utf8"));
7037
+ }
7038
+ const decrypted = Buffer.concat([
7039
+ decipher.update(Buffer.from(field.ciphertext, "base64")),
7040
+ decipher.final()
7041
+ ]);
7042
+ return decrypted.toString("utf8");
7043
+ }
7044
+ async encryptDeterministic(plaintext, options) {
7045
+ const hash = await this.computeHash(plaintext);
7046
+ const encrypted = await this.encrypt(plaintext, options);
7047
+ return { hash, encrypted };
7048
+ }
7049
+ async computeHash(plaintext) {
7050
+ return createHmac2("sha256", this.hmacKey).update(plaintext, "utf8").digest("hex");
7051
+ }
7052
+ async encryptBatch(fields, options) {
7053
+ const result = {};
7054
+ for (const [key, value] of Object.entries(fields)) {
7055
+ result[key] = await this.encrypt(value, options);
7056
+ }
7057
+ return result;
7058
+ }
7059
+ async decryptBatch(fields, options) {
7060
+ const result = {};
7061
+ for (const [key, value] of Object.entries(fields)) {
7062
+ result[key] = await this.decrypt(value, options);
7063
+ }
7064
+ return result;
7065
+ }
7066
+ async rotateKey() {
7067
+ const previousKeyId = this.activeKeyId;
7068
+ const currentKey = this.keys.get(previousKeyId);
7069
+ if (currentKey) {
7070
+ currentKey.status = "decrypt-only";
7071
+ }
7072
+ const newKeyId = this.generateKeyId();
7073
+ const dek = this.deriveDEK(newKeyId);
7074
+ this.keys.set(newKeyId, {
7075
+ id: newKeyId,
7076
+ dek,
7077
+ status: "active",
7078
+ createdAt: /* @__PURE__ */ new Date()
7079
+ });
7080
+ this.activeKeyId = newKeyId;
7081
+ return { newKeyId, previousKeyId };
7082
+ }
7083
+ async reEncrypt(field, options) {
7084
+ const plaintext = await this.decrypt(field);
7085
+ return this.encrypt(plaintext, options);
7086
+ }
7087
+ async listKeys() {
7088
+ return Array.from(this.keys.values()).map((k) => ({
7089
+ keyId: k.id,
7090
+ createdAt: k.createdAt,
7091
+ status: k.status
7092
+ }));
7093
+ }
7094
+ async getActiveKeyId() {
7095
+ return this.activeKeyId;
7096
+ }
7097
+ async healthCheck() {
7098
+ try {
7099
+ const testPlain = "health-check-" + randomBytes25(4).toString("hex");
7100
+ const encrypted = await this.encrypt(testPlain);
7101
+ const decrypted = await this.decrypt(encrypted);
7102
+ return decrypted === testPlain;
7103
+ } catch {
7104
+ return false;
7105
+ }
7106
+ }
7107
+ /**
7108
+ * Derive a Data Encryption Key from the master key using HKDF.
7109
+ */
7110
+ deriveDEK(keyId) {
7111
+ return Buffer.from(
7112
+ hkdfSync("sha256", this.masterKey, keyId, "dek-derivation", 32)
7113
+ );
7114
+ }
7115
+ generateKeyId() {
7116
+ this.keyCounter++;
7117
+ const timestamp = Date.now().toString(36);
7118
+ const random = randomBytes25(4).toString("hex");
7119
+ return `dek_${timestamp}_${random}_${this.keyCounter}`;
7120
+ }
7121
+ };
7122
+ }
7123
+ });
7124
+
6938
7125
  // src/interfaces/IQueue.ts
7126
+ import { randomBytes } from "crypto";
6939
7127
  function calculateBackoff(attempt, options) {
6940
7128
  if (options.type === "fixed") {
6941
7129
  return options.delay;
@@ -6946,7 +7134,7 @@ function calculateBackoff(attempt, options) {
6946
7134
  }
6947
7135
  function generateJobId() {
6948
7136
  const timestamp = Date.now().toString(36);
6949
- const random = Math.random().toString(36).substring(2, 10);
7137
+ const random = randomBytes(4).toString("hex");
6950
7138
  return `job_${timestamp}_${random}`;
6951
7139
  }
6952
7140
 
@@ -7297,6 +7485,7 @@ function createScopedMetrics(metrics, prefix, defaultTags = {}) {
7297
7485
  }
7298
7486
 
7299
7487
  // src/interfaces/ISecrets.ts
7488
+ import { randomBytes as randomBytes2 } from "crypto";
7300
7489
  var EnvSecrets = class {
7301
7490
  prefix;
7302
7491
  cache = /* @__PURE__ */ new Map();
@@ -7497,12 +7686,7 @@ var MemorySecrets = class {
7497
7686
  return true;
7498
7687
  }
7499
7688
  generateSecureValue(length = 32) {
7500
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
7501
- let result = "";
7502
- for (let i = 0; i < length; i++) {
7503
- result += chars[Math.floor(Math.random() * chars.length)];
7504
- }
7505
- return result;
7689
+ return randomBytes2(length).toString("base64url").slice(0, length);
7506
7690
  }
7507
7691
  /**
7508
7692
  * Clear all secrets (for testing)
@@ -7520,6 +7704,7 @@ var MemorySecrets = class {
7520
7704
  };
7521
7705
 
7522
7706
  // src/interfaces/ITracing.ts
7707
+ import { randomBytes as randomBytes3 } from "crypto";
7523
7708
  var MemorySpan = class {
7524
7709
  name;
7525
7710
  context;
@@ -7539,7 +7724,7 @@ var MemorySpan = class {
7539
7724
  };
7540
7725
  }
7541
7726
  generateSpanId() {
7542
- return Math.random().toString(16).substring(2, 18).padStart(16, "0");
7727
+ return randomBytes3(8).toString("hex");
7543
7728
  }
7544
7729
  setAttribute(key, value) {
7545
7730
  this._attributes[key] = value;
@@ -7599,7 +7784,7 @@ var MemoryTracing = class {
7599
7784
  this.traceId = this.generateTraceId();
7600
7785
  }
7601
7786
  generateTraceId() {
7602
- return Math.random().toString(16).substring(2, 34).padStart(32, "0");
7787
+ return randomBytes3(16).toString("hex");
7603
7788
  }
7604
7789
  startSpan(name, options) {
7605
7790
  const span = new MemorySpan(
@@ -7752,9 +7937,10 @@ var NoopTracing = class {
7752
7937
  };
7753
7938
 
7754
7939
  // src/interfaces/IErrorReporter.ts
7940
+ import { randomBytes as randomBytes4 } from "crypto";
7755
7941
  function generateErrorId() {
7756
7942
  const timestamp = Date.now().toString(36);
7757
- const random = Math.random().toString(36).substring(2, 10);
7943
+ const random = randomBytes4(4).toString("hex");
7758
7944
  return `err_${timestamp}_${random}`;
7759
7945
  }
7760
7946
  function generateFingerprint(error) {
@@ -7798,9 +7984,10 @@ function createErrorReport(error, context, options) {
7798
7984
  }
7799
7985
 
7800
7986
  // src/interfaces/IAuditLog.ts
7987
+ import { randomBytes as randomBytes5 } from "crypto";
7801
7988
  function generateAuditId() {
7802
7989
  const timestamp = Date.now().toString(36);
7803
- const random = Math.random().toString(36).substring(2, 10);
7990
+ const random = randomBytes5(4).toString("hex");
7804
7991
  return `aud_${timestamp}${random}`;
7805
7992
  }
7806
7993
  function generateChecksum(event) {
@@ -7966,9 +8153,10 @@ var AuditEvents = {
7966
8153
  };
7967
8154
 
7968
8155
  // src/interfaces/IScheduler.ts
8156
+ import { randomBytes as randomBytes6 } from "crypto";
7969
8157
  function generateScheduleId() {
7970
8158
  const timestamp = Date.now().toString(36);
7971
- const random = Math.random().toString(36).substring(2, 8);
8159
+ const random = randomBytes6(4).toString("hex");
7972
8160
  return `sch_${timestamp}${random}`;
7973
8161
  }
7974
8162
  function getNextCronRun(cron, after = /* @__PURE__ */ new Date(), timezone) {
@@ -8027,28 +8215,24 @@ function describeCron(cron) {
8027
8215
  }
8028
8216
 
8029
8217
  // src/interfaces/IWebhook.ts
8218
+ import { randomBytes as randomBytes7 } from "crypto";
8030
8219
  function generateWebhookId() {
8031
8220
  const timestamp = Date.now().toString(36);
8032
- const random = Math.random().toString(36).substring(2, 10);
8221
+ const random = randomBytes7(6).toString("hex");
8033
8222
  return `wh_${timestamp}${random}`;
8034
8223
  }
8035
8224
  function generateDeliveryId() {
8036
8225
  const timestamp = Date.now().toString(36);
8037
- const random = Math.random().toString(36).substring(2, 10);
8226
+ const random = randomBytes7(6).toString("hex");
8038
8227
  return `del_${timestamp}${random}`;
8039
8228
  }
8040
8229
  function generateEventId() {
8041
8230
  const timestamp = Date.now().toString(36);
8042
- const random = Math.random().toString(36).substring(2, 10);
8231
+ const random = randomBytes7(6).toString("hex");
8043
8232
  return `evt_${timestamp}${random}`;
8044
8233
  }
8045
8234
  function generateWebhookSecret(length = 32) {
8046
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
8047
- let secret = "whsec_";
8048
- for (let i = 0; i < length; i++) {
8049
- secret += chars.charAt(Math.floor(Math.random() * chars.length));
8050
- }
8051
- return secret;
8235
+ return `whsec_${randomBytes7(length).toString("base64url").slice(0, length)}`;
8052
8236
  }
8053
8237
  function matchEventType(eventType, pattern) {
8054
8238
  if (eventType === pattern || pattern === "*" || pattern === "**") {
@@ -8125,9 +8309,10 @@ var WebhookEventTypes = {
8125
8309
  };
8126
8310
 
8127
8311
  // src/interfaces/INotification.ts
8312
+ import { randomBytes as randomBytes8 } from "crypto";
8128
8313
  function generateNotificationId() {
8129
8314
  const timestamp = Date.now().toString(36);
8130
- const random = Math.random().toString(36).substring(2, 10);
8315
+ const random = randomBytes8(4).toString("hex");
8131
8316
  return `notif_${timestamp}${random}`;
8132
8317
  }
8133
8318
  function isInQuietHours(preferences) {
@@ -8617,6 +8802,7 @@ var MemoryAuth = class {
8617
8802
  };
8618
8803
 
8619
8804
  // src/interfaces/IPayment.ts
8805
+ import { randomBytes as randomBytes9 } from "crypto";
8620
8806
  function createPaymentError(code, message, originalError) {
8621
8807
  return { code, message, originalError };
8622
8808
  }
@@ -8648,7 +8834,7 @@ function formatAmount(amount, currency, locale = "en-US") {
8648
8834
  }
8649
8835
  function generatePaymentId(prefix = "pi") {
8650
8836
  const timestamp = Date.now().toString(36);
8651
- const random = Math.random().toString(36).substring(2, 10);
8837
+ const random = randomBytes9(8).toString("hex");
8652
8838
  return `${prefix}_${timestamp}${random}`;
8653
8839
  }
8654
8840
  var MemoryPayment = class {
@@ -8706,7 +8892,7 @@ var MemoryPayment = class {
8706
8892
  amount: options.amount,
8707
8893
  currency: options.currency,
8708
8894
  status: options.paymentMethodId ? "requires_confirmation" : "requires_payment_method",
8709
- clientSecret: `${id}_secret_${Math.random().toString(36).substring(2, 15)}`,
8895
+ clientSecret: `${id}_secret_${randomBytes9(16).toString("base64url")}`,
8710
8896
  metadata: options.metadata,
8711
8897
  description: options.description,
8712
8898
  receiptEmail: options.receiptEmail,
@@ -9021,6 +9207,7 @@ var MemoryPayment = class {
9021
9207
  };
9022
9208
 
9023
9209
  // src/interfaces/IAuthSSO.ts
9210
+ import { randomBytes as randomBytes10 } from "crypto";
9024
9211
  var MemoryAuthSSO = class {
9025
9212
  samlConfigs = /* @__PURE__ */ new Map();
9026
9213
  oidcConfigs = /* @__PURE__ */ new Map();
@@ -9052,7 +9239,7 @@ var MemoryAuthSSO = class {
9052
9239
  if (!config) {
9053
9240
  throw new Error("SAML not configured for tenant");
9054
9241
  }
9055
- const id = `_${Math.random().toString(36).substring(2)}`;
9242
+ const id = `_${randomBytes10(8).toString("hex")}`;
9056
9243
  return {
9057
9244
  id,
9058
9245
  redirectUrl: `${config.ssoUrl}?SAMLRequest=mock_request&RelayState=${options.relayState ?? ""}`,
@@ -9064,7 +9251,7 @@ var MemoryAuthSSO = class {
9064
9251
  }
9065
9252
  async processSamlResponse(_samlResponse, _relayState) {
9066
9253
  const user = {
9067
- id: `saml_${Math.random().toString(36).substring(2)}`,
9254
+ id: `saml_${randomBytes10(8).toString("hex")}`,
9068
9255
  email: "saml.user@example.com",
9069
9256
  emailVerified: true,
9070
9257
  metadata: { ssoProvider: "saml" },
@@ -9074,7 +9261,7 @@ var MemoryAuthSSO = class {
9074
9261
  success: true,
9075
9262
  user,
9076
9263
  session: {
9077
- accessToken: `saml_token_${Math.random().toString(36)}`,
9264
+ accessToken: `saml_token_${randomBytes10(8).toString("hex")}`,
9078
9265
  expiresAt: new Date(Date.now() + 36e5),
9079
9266
  user
9080
9267
  },
@@ -9111,8 +9298,8 @@ var MemoryAuthSSO = class {
9111
9298
  }
9112
9299
  // OIDC Authentication
9113
9300
  async initiateOidcLogin(options) {
9114
- const state = options.state ?? Math.random().toString(36).substring(2);
9115
- const nonce = Math.random().toString(36).substring(2);
9301
+ const state = options.state ?? randomBytes10(8).toString("hex");
9302
+ const nonce = randomBytes10(8).toString("hex");
9116
9303
  return {
9117
9304
  state,
9118
9305
  redirectUrl: `https://idp.example.com/authorize?client_id=mock&redirect_uri=${encodeURIComponent(options.redirectUri)}&state=${state}`,
@@ -9123,7 +9310,7 @@ var MemoryAuthSSO = class {
9123
9310
  }
9124
9311
  async processOidcCallback(_code, _state, _codeVerifier) {
9125
9312
  const user = {
9126
- id: `oidc_${Math.random().toString(36).substring(2)}`,
9313
+ id: `oidc_${randomBytes10(8).toString("hex")}`,
9127
9314
  email: "oidc.user@example.com",
9128
9315
  emailVerified: true,
9129
9316
  metadata: { ssoProvider: "oidc" },
@@ -9133,7 +9320,7 @@ var MemoryAuthSSO = class {
9133
9320
  success: true,
9134
9321
  user,
9135
9322
  session: {
9136
- accessToken: `oidc_token_${Math.random().toString(36)}`,
9323
+ accessToken: `oidc_token_${randomBytes10(8).toString("hex")}`,
9137
9324
  expiresAt: new Date(Date.now() + 36e5),
9138
9325
  user
9139
9326
  },
@@ -9142,7 +9329,7 @@ var MemoryAuthSSO = class {
9142
9329
  }
9143
9330
  async refreshOidcTokens(_refreshToken, _tenantId) {
9144
9331
  return {
9145
- accessToken: `refreshed_token_${Math.random().toString(36)}`,
9332
+ accessToken: `refreshed_token_${randomBytes10(8).toString("hex")}`,
9146
9333
  expiresIn: 3600
9147
9334
  };
9148
9335
  }
@@ -9172,7 +9359,7 @@ var MemoryAuthSSO = class {
9172
9359
  }
9173
9360
  // SCIM
9174
9361
  async configureScim(config) {
9175
- const token = `scim_token_${Math.random().toString(36)}`;
9362
+ const token = `scim_token_${randomBytes10(8).toString("hex")}`;
9176
9363
  this.scimConfigs.set(config.tenantId, { ...config, bearerToken: token });
9177
9364
  return { bearerToken: token };
9178
9365
  }
@@ -9185,7 +9372,7 @@ var MemoryAuthSSO = class {
9185
9372
  async regenerateScimToken(tenantId) {
9186
9373
  const config = this.scimConfigs.get(tenantId);
9187
9374
  if (!config) throw new Error("SCIM not configured");
9188
- const token = `scim_token_${Math.random().toString(36)}`;
9375
+ const token = `scim_token_${randomBytes10(8).toString("hex")}`;
9189
9376
  config.bearerToken = token;
9190
9377
  return { bearerToken: token };
9191
9378
  }
@@ -9194,7 +9381,7 @@ var MemoryAuthSSO = class {
9194
9381
  }
9195
9382
  // Domain Verification
9196
9383
  async initiateDomainVerification(tenantId, domain) {
9197
- const token = `dll-verify-${Math.random().toString(36).substring(2)}`;
9384
+ const token = `dll-verify-${randomBytes10(8).toString("hex")}`;
9198
9385
  this.pendingVerifications.set(`${tenantId}:${domain}`, { domain, token });
9199
9386
  return {
9200
9387
  verificationMethod: "dns_txt",
@@ -9260,6 +9447,7 @@ var MemoryAuthSSO = class {
9260
9447
  };
9261
9448
 
9262
9449
  // src/interfaces/ITenant.ts
9450
+ import { randomBytes as randomBytes11 } from "crypto";
9263
9451
  var tenantContextStorage = /* @__PURE__ */ new Map();
9264
9452
  var contextIdCounter = 0;
9265
9453
  var currentContextId = null;
@@ -9327,7 +9515,7 @@ var MemoryTenant = class {
9327
9515
  // Tenant CRUD
9328
9516
  async createTenant(options) {
9329
9517
  const tenant = {
9330
- id: `tenant_${Math.random().toString(36).substring(2)}`,
9518
+ id: `tenant_${randomBytes11(8).toString("hex")}`,
9331
9519
  slug: options.slug,
9332
9520
  name: options.name,
9333
9521
  status: "active",
@@ -9448,7 +9636,7 @@ var MemoryTenant = class {
9448
9636
  }
9449
9637
  async addMember(tenantId, userId, role) {
9450
9638
  const member = {
9451
- id: `member_${Math.random().toString(36).substring(2)}`,
9639
+ id: `member_${randomBytes11(8).toString("hex")}`,
9452
9640
  tenantId,
9453
9641
  userId,
9454
9642
  role,
@@ -9489,12 +9677,12 @@ var MemoryTenant = class {
9489
9677
  }
9490
9678
  async inviteMember(tenantId, options) {
9491
9679
  const invitation = {
9492
- id: `inv_${Math.random().toString(36).substring(2)}`,
9680
+ id: `inv_${randomBytes11(8).toString("hex")}`,
9493
9681
  tenantId,
9494
9682
  email: options.email,
9495
9683
  role: options.role,
9496
9684
  invitedBy: "system",
9497
- token: Math.random().toString(36).substring(2),
9685
+ token: randomBytes11(16).toString("base64url"),
9498
9686
  status: "pending",
9499
9687
  createdAt: /* @__PURE__ */ new Date(),
9500
9688
  expiresAt: new Date(
@@ -9655,6 +9843,7 @@ var MemoryTenant = class {
9655
9843
  init_IAI();
9656
9844
 
9657
9845
  // src/interfaces/IPromptStore.ts
9846
+ import { randomBytes as randomBytes12 } from "crypto";
9658
9847
  var MemoryPromptStore = class {
9659
9848
  // userId -> variantId
9660
9849
  constructor(config = {}) {
@@ -9670,7 +9859,7 @@ var MemoryPromptStore = class {
9670
9859
  // Prompt CRUD
9671
9860
  // ─────────────────────────────────────────────────────────────
9672
9861
  async create(prompt) {
9673
- const id = `prompt_${Date.now()}_${Math.random().toString(36).substring(7)}`;
9862
+ const id = `prompt_${Date.now()}_${randomBytes12(4).toString("hex")}`;
9674
9863
  const now = /* @__PURE__ */ new Date();
9675
9864
  const newPrompt = {
9676
9865
  ...prompt,
@@ -9685,7 +9874,7 @@ var MemoryPromptStore = class {
9685
9874
  this.prompts.set(id, newPrompt);
9686
9875
  this.prompts.set(prompt.slug, newPrompt);
9687
9876
  const version = {
9688
- id: `pv_${Date.now()}_${Math.random().toString(36).substring(7)}`,
9877
+ id: `pv_${Date.now()}_${randomBytes12(4).toString("hex")}`,
9689
9878
  promptId: id,
9690
9879
  version: 1,
9691
9880
  content: prompt.content,
@@ -9720,7 +9909,7 @@ var MemoryPromptStore = class {
9720
9909
  latestVersion.isLatest = false;
9721
9910
  }
9722
9911
  const newVersion = {
9723
- id: `pv_${Date.now()}_${Math.random().toString(36).substring(7)}`,
9912
+ id: `pv_${Date.now()}_${randomBytes12(4).toString("hex")}`,
9724
9913
  promptId: prompt.id,
9725
9914
  version: versions.length + 1,
9726
9915
  content: updates.content,
@@ -9965,7 +10154,7 @@ ${v2.content}`;
9965
10154
  // A/B Testing
9966
10155
  // ─────────────────────────────────────────────────────────────
9967
10156
  async createExperiment(experiment) {
9968
- const id = `exp_${Date.now()}_${Math.random().toString(36).substring(7)}`;
10157
+ const id = `exp_${Date.now()}_${randomBytes12(4).toString("hex")}`;
9969
10158
  const now = /* @__PURE__ */ new Date();
9970
10159
  const newExperiment = {
9971
10160
  ...experiment,
@@ -10042,7 +10231,7 @@ ${v2.content}`;
10042
10231
  // Prompt Chains
10043
10232
  // ─────────────────────────────────────────────────────────────
10044
10233
  async createChain(chain) {
10045
- const id = `chain_${Date.now()}_${Math.random().toString(36).substring(7)}`;
10234
+ const id = `chain_${Date.now()}_${randomBytes12(4).toString("hex")}`;
10046
10235
  const now = /* @__PURE__ */ new Date();
10047
10236
  const newChain = {
10048
10237
  ...chain,
@@ -10133,7 +10322,7 @@ ${v2.content}`;
10133
10322
  async recordUsage(record) {
10134
10323
  const usageRecord = {
10135
10324
  ...record,
10136
- id: `usage_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10325
+ id: `usage_${Date.now()}_${randomBytes12(4).toString("hex")}`,
10137
10326
  createdAt: /* @__PURE__ */ new Date()
10138
10327
  };
10139
10328
  if (this.config.trackUsage !== false) {
@@ -10237,6 +10426,7 @@ ${v2.content}`;
10237
10426
  init_IRAG();
10238
10427
 
10239
10428
  // src/interfaces/IAIUsage.ts
10429
+ import { randomBytes as randomBytes14 } from "crypto";
10240
10430
  var MemoryAIUsage = class {
10241
10431
  constructor(config = {}) {
10242
10432
  this.config = config;
@@ -10270,7 +10460,7 @@ var MemoryAIUsage = class {
10270
10460
  async record(record) {
10271
10461
  const newRecord = {
10272
10462
  ...record,
10273
- id: `usage_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10463
+ id: `usage_${Date.now()}_${randomBytes14(4).toString("hex")}`,
10274
10464
  createdAt: /* @__PURE__ */ new Date()
10275
10465
  };
10276
10466
  this.records.push(newRecord);
@@ -10351,7 +10541,7 @@ var MemoryAIUsage = class {
10351
10541
  const period = this.getPeriodBounds(quota.period, /* @__PURE__ */ new Date());
10352
10542
  const newQuota = {
10353
10543
  ...quota,
10354
- id: existingQuota?.id || `quota_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10544
+ id: existingQuota?.id || `quota_${Date.now()}_${randomBytes14(4).toString("hex")}`,
10355
10545
  used: existingQuota?.used || 0,
10356
10546
  periodStart: period.start,
10357
10547
  periodEnd: period.end
@@ -10445,7 +10635,7 @@ var MemoryAIUsage = class {
10445
10635
  const period = this.getPeriodBounds(budget.period, /* @__PURE__ */ new Date());
10446
10636
  const newBudget = {
10447
10637
  ...budget,
10448
- id: existingBudget?.id || `budget_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10638
+ id: existingBudget?.id || `budget_${Date.now()}_${randomBytes14(4).toString("hex")}`,
10449
10639
  spent: existingBudget?.spent || 0,
10450
10640
  periodStart: period.start,
10451
10641
  periodEnd: period.end
@@ -10709,7 +10899,7 @@ var MemoryAIUsage = class {
10709
10899
  const items = Array.from(itemsMap.values());
10710
10900
  const subtotal = items.reduce((sum, item) => sum + item.costUsd, 0);
10711
10901
  const invoice = {
10712
- id: `inv_${Date.now()}_${Math.random().toString(36).substring(7)}`,
10902
+ id: `inv_${Date.now()}_${randomBytes14(4).toString("hex")}`,
10713
10903
  tenantId,
10714
10904
  periodStart,
10715
10905
  periodEnd,
@@ -10922,7 +11112,7 @@ var MemoryAIUsage = class {
10922
11112
  );
10923
11113
  if (existingAlert) return;
10924
11114
  this.alerts.push({
10925
- id: `alert_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11115
+ id: `alert_${Date.now()}_${randomBytes14(4).toString("hex")}`,
10926
11116
  tenantId,
10927
11117
  type,
10928
11118
  severity,
@@ -11051,6 +11241,7 @@ var MemoryAIUsage = class {
11051
11241
  };
11052
11242
 
11053
11243
  // src/interfaces/IDevice.ts
11244
+ import { randomBytes as randomBytes15 } from "crypto";
11054
11245
  var MemoryDevice = class {
11055
11246
  constructor(config = {}) {
11056
11247
  this.config = config;
@@ -11075,7 +11266,7 @@ var MemoryDevice = class {
11075
11266
  const now = /* @__PURE__ */ new Date();
11076
11267
  const newDevice = {
11077
11268
  ...device,
11078
- id: `dev_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11269
+ id: `dev_${Date.now()}_${randomBytes15(4).toString("hex")}`,
11079
11270
  status: "active",
11080
11271
  connectionState: "disconnected",
11081
11272
  tags: device.tags || [],
@@ -11198,7 +11389,7 @@ var MemoryDevice = class {
11198
11389
  // Provisioning
11199
11390
  // ─────────────────────────────────────────────────────────────
11200
11391
  async provision(request) {
11201
- const id = `prov_${Date.now()}_${Math.random().toString(36).substring(7)}`;
11392
+ const id = `prov_${Date.now()}_${randomBytes15(4).toString("hex")}`;
11202
11393
  const newRequest = {
11203
11394
  ...request,
11204
11395
  id,
@@ -11210,7 +11401,7 @@ var MemoryDevice = class {
11210
11401
  const result = {
11211
11402
  credentials: {
11212
11403
  type: request.config.authMethod || "token",
11213
- token: `tok_${Date.now()}_${Math.random().toString(36).substring(7)}`
11404
+ token: `tok_${Date.now()}_${randomBytes15(16).toString("hex")}`
11214
11405
  },
11215
11406
  endpoint: "mqtt://localhost:1883",
11216
11407
  mqttBroker: "mqtt://localhost:1883"
@@ -11253,7 +11444,7 @@ var MemoryDevice = class {
11253
11444
  }
11254
11445
  }
11255
11446
  async generateRegistrationCode(deviceType, tenantId, expiresInHours = 24) {
11256
- const code = `REG_${Math.random().toString(36).substring(2, 10).toUpperCase()}`;
11447
+ const code = `REG_${randomBytes15(4).toString("hex").toUpperCase()}`;
11257
11448
  this.registrationCodes.set(code, {
11258
11449
  deviceType,
11259
11450
  tenantId,
@@ -11353,7 +11544,7 @@ var MemoryDevice = class {
11353
11544
  async ingestTelemetry(message) {
11354
11545
  const newMessage = {
11355
11546
  ...message,
11356
- id: `tel_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11547
+ id: `tel_${Date.now()}_${randomBytes15(4).toString("hex")}`,
11357
11548
  receivedAt: /* @__PURE__ */ new Date()
11358
11549
  };
11359
11550
  if (this.config.storeTelemetry !== false) {
@@ -11433,7 +11624,7 @@ var MemoryDevice = class {
11433
11624
  // ─────────────────────────────────────────────────────────────
11434
11625
  async sendCommand(deviceId, name, payload, options) {
11435
11626
  const command = {
11436
- id: `cmd_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11627
+ id: `cmd_${Date.now()}_${randomBytes15(4).toString("hex")}`,
11437
11628
  deviceId,
11438
11629
  name,
11439
11630
  payload,
@@ -11496,7 +11687,7 @@ var MemoryDevice = class {
11496
11687
  async createFirmware(firmware) {
11497
11688
  const newFirmware = {
11498
11689
  ...firmware,
11499
- id: `fw_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11690
+ id: `fw_${Date.now()}_${randomBytes15(4).toString("hex")}`,
11500
11691
  status: "draft",
11501
11692
  createdAt: /* @__PURE__ */ new Date()
11502
11693
  };
@@ -11548,7 +11739,7 @@ var MemoryDevice = class {
11548
11739
  throw new Error(`Firmware not found: ${firmwareVersionId}`);
11549
11740
  }
11550
11741
  const update = {
11551
- id: `upd_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11742
+ id: `upd_${Date.now()}_${randomBytes15(4).toString("hex")}`,
11552
11743
  deviceId,
11553
11744
  firmwareVersionId,
11554
11745
  targetVersion: firmware.version,
@@ -11602,7 +11793,7 @@ var MemoryDevice = class {
11602
11793
  const now = /* @__PURE__ */ new Date();
11603
11794
  const newGroup = {
11604
11795
  ...group,
11605
- id: `grp_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11796
+ id: `grp_${Date.now()}_${randomBytes15(4).toString("hex")}`,
11606
11797
  deviceCount: 0,
11607
11798
  tags: group.tags || [],
11608
11799
  attributes: group.attributes || {},
@@ -11722,6 +11913,7 @@ var MemoryDevice = class {
11722
11913
  };
11723
11914
 
11724
11915
  // src/interfaces/IBilling.ts
11916
+ import { randomBytes as randomBytes16 } from "crypto";
11725
11917
  var MemoryBilling = class {
11726
11918
  constructor(config = {}) {
11727
11919
  this.config = config;
@@ -11742,7 +11934,7 @@ var MemoryBilling = class {
11742
11934
  async createProduct(product) {
11743
11935
  const newProduct = {
11744
11936
  ...product,
11745
- id: `prod_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11937
+ id: `prod_${Date.now()}_${randomBytes16(4).toString("hex")}`,
11746
11938
  features: product.features || [],
11747
11939
  metadata: product.metadata || {},
11748
11940
  createdAt: /* @__PURE__ */ new Date(),
@@ -11770,7 +11962,7 @@ var MemoryBilling = class {
11770
11962
  async createPrice(price) {
11771
11963
  const newPrice = {
11772
11964
  ...price,
11773
- id: `price_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11965
+ id: `price_${Date.now()}_${randomBytes16(4).toString("hex")}`,
11774
11966
  metadata: price.metadata || {},
11775
11967
  createdAt: /* @__PURE__ */ new Date(),
11776
11968
  updatedAt: /* @__PURE__ */ new Date()
@@ -11801,7 +11993,7 @@ var MemoryBilling = class {
11801
11993
  async createMeter(meter) {
11802
11994
  const newMeter = {
11803
11995
  ...meter,
11804
- id: `meter_${Date.now()}_${Math.random().toString(36).substring(7)}`,
11996
+ id: `meter_${Date.now()}_${randomBytes16(4).toString("hex")}`,
11805
11997
  createdAt: /* @__PURE__ */ new Date(),
11806
11998
  updatedAt: /* @__PURE__ */ new Date()
11807
11999
  };
@@ -11835,13 +12027,13 @@ var MemoryBilling = class {
11835
12027
  const trialDays = options.trialDays ?? price.trialDays ?? 0;
11836
12028
  const periodEnd = this.addPeriod(now, price.billingPeriod);
11837
12029
  const subscription = {
11838
- id: `sub_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12030
+ id: `sub_${Date.now()}_${randomBytes16(4).toString("hex")}`,
11839
12031
  customerId: options.customerId,
11840
12032
  tenantId: options.tenantId,
11841
12033
  status: trialDays > 0 ? "trialing" : "active",
11842
12034
  items: [
11843
12035
  {
11844
- id: `si_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12036
+ id: `si_${Date.now()}_${randomBytes16(4).toString("hex")}`,
11845
12037
  priceId: options.priceId,
11846
12038
  quantity: options.quantity || 1
11847
12039
  }
@@ -11932,7 +12124,7 @@ var MemoryBilling = class {
11932
12124
  const sub = await this.getSubscription(subscriptionId);
11933
12125
  if (!sub) throw new Error(`Subscription not found: ${subscriptionId}`);
11934
12126
  sub.items.push({
11935
- id: `si_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12127
+ id: `si_${Date.now()}_${randomBytes16(4).toString("hex")}`,
11936
12128
  priceId,
11937
12129
  quantity: quantity || 1
11938
12130
  });
@@ -11984,7 +12176,7 @@ var MemoryBilling = class {
11984
12176
  if (existing) return existing;
11985
12177
  }
11986
12178
  const event = {
11987
- id: `ue_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12179
+ id: `ue_${Date.now()}_${randomBytes16(4).toString("hex")}`,
11988
12180
  subscriptionId,
11989
12181
  customerId: sub.customerId,
11990
12182
  meterId: meter.id,
@@ -12055,7 +12247,7 @@ var MemoryBilling = class {
12055
12247
  if (price) {
12056
12248
  const unitAmount = price.unitAmount || 0;
12057
12249
  lineItems.push({
12058
- id: `ii_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12250
+ id: `ii_${Date.now()}_${randomBytes16(4).toString("hex")}`,
12059
12251
  priceId: item.priceId,
12060
12252
  description: price.name,
12061
12253
  quantity: item.quantity,
@@ -12070,7 +12262,7 @@ var MemoryBilling = class {
12070
12262
  const usageSummary = await this.getUsageSummary(subscriptionId);
12071
12263
  for (const usage of usageSummary) {
12072
12264
  lineItems.push({
12073
- id: `ii_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12265
+ id: `ii_${Date.now()}_${randomBytes16(4).toString("hex")}`,
12074
12266
  description: `${usage.meterName}: ${usage.total} ${usage.unit}`,
12075
12267
  quantity: usage.total,
12076
12268
  unitAmount: usage.cost / usage.total,
@@ -12093,7 +12285,7 @@ var MemoryBilling = class {
12093
12285
  const tax = (subtotal - discount) * (taxRate / 100);
12094
12286
  const total = subtotal - discount + tax;
12095
12287
  const invoice = {
12096
- id: `inv_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12288
+ id: `inv_${Date.now()}_${randomBytes16(4).toString("hex")}`,
12097
12289
  customerId: sub.customerId,
12098
12290
  subscriptionId,
12099
12291
  tenantId: sub.tenantId,
@@ -12124,14 +12316,14 @@ var MemoryBilling = class {
12124
12316
  async createInvoice(options) {
12125
12317
  const lineItems = options.lineItems.map((item) => ({
12126
12318
  ...item,
12127
- id: `ii_${Date.now()}_${Math.random().toString(36).substring(7)}`
12319
+ id: `ii_${Date.now()}_${randomBytes16(4).toString("hex")}`
12128
12320
  }));
12129
12321
  const subtotal = lineItems.reduce((sum, item) => sum + item.amount, 0);
12130
12322
  const taxRate = this.config.defaultTaxRate || 0;
12131
12323
  const tax = subtotal * (taxRate / 100);
12132
12324
  const total = subtotal + tax;
12133
12325
  const invoice = {
12134
- id: `inv_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12326
+ id: `inv_${Date.now()}_${randomBytes16(4).toString("hex")}`,
12135
12327
  customerId: options.customerId,
12136
12328
  tenantId: options.tenantId,
12137
12329
  number: `${this.config.invoiceNumberPrefix || "INV-"}${++this.invoiceCounter}`,
@@ -12220,7 +12412,7 @@ var MemoryBilling = class {
12220
12412
  async createDunningConfig(config) {
12221
12413
  const newConfig = {
12222
12414
  ...config,
12223
- id: `dun_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12415
+ id: `dun_${Date.now()}_${randomBytes16(4).toString("hex")}`,
12224
12416
  createdAt: /* @__PURE__ */ new Date(),
12225
12417
  updatedAt: /* @__PURE__ */ new Date()
12226
12418
  };
@@ -12246,7 +12438,7 @@ var MemoryBilling = class {
12246
12438
  const invoice = await this.getInvoice(invoiceId);
12247
12439
  if (!invoice) throw new Error(`Invoice not found: ${invoiceId}`);
12248
12440
  const attempt = {
12249
- id: `da_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12441
+ id: `da_${Date.now()}_${randomBytes16(4).toString("hex")}`,
12250
12442
  invoiceId,
12251
12443
  attemptNumber: invoice.attemptCount + 1,
12252
12444
  action: "retry_payment",
@@ -12278,7 +12470,7 @@ var MemoryBilling = class {
12278
12470
  balance.updatedAt = /* @__PURE__ */ new Date();
12279
12471
  this.creditBalances.set(customerId, balance);
12280
12472
  const transaction = {
12281
- id: `ct_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12473
+ id: `ct_${Date.now()}_${randomBytes16(4).toString("hex")}`,
12282
12474
  customerId,
12283
12475
  type: options?.type || "manual",
12284
12476
  amount,
@@ -12303,7 +12495,7 @@ var MemoryBilling = class {
12303
12495
  balance.updatedAt = /* @__PURE__ */ new Date();
12304
12496
  this.creditBalances.set(customerId, balance);
12305
12497
  const transaction = {
12306
- id: `ct_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12498
+ id: `ct_${Date.now()}_${randomBytes16(4).toString("hex")}`,
12307
12499
  customerId,
12308
12500
  type: "manual",
12309
12501
  amount: -amount,
@@ -12327,7 +12519,7 @@ var MemoryBilling = class {
12327
12519
  async createCoupon(coupon) {
12328
12520
  const newCoupon = {
12329
12521
  ...coupon,
12330
- id: `coup_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12522
+ id: `coup_${Date.now()}_${randomBytes16(4).toString("hex")}`,
12331
12523
  timesRedeemed: 0,
12332
12524
  createdAt: /* @__PURE__ */ new Date(),
12333
12525
  updatedAt: /* @__PURE__ */ new Date()
@@ -12563,6 +12755,7 @@ var MemoryBilling = class {
12563
12755
  };
12564
12756
 
12565
12757
  // src/interfaces/IDevPortal.ts
12758
+ import { randomBytes as randomBytes17 } from "crypto";
12566
12759
  var MemoryDevPortal = class {
12567
12760
  constructor(config = {}) {
12568
12761
  this.config = config;
@@ -12575,8 +12768,9 @@ var MemoryDevPortal = class {
12575
12768
  usageRecords = [];
12576
12769
  // API Key Management
12577
12770
  async createApiKey(options, userId) {
12578
- const id = `key_${Date.now()}_${Math.random().toString(36).substring(7)}`;
12579
- const secret = `sk_${options.type}_${Math.random().toString(36).substring(2)}${Math.random().toString(36).substring(2)}`;
12771
+ const { randomBytes: randomBytes37, createHash: createHash2 } = await import("crypto");
12772
+ const id = `key_${Date.now()}_${randomBytes37(8).toString("hex")}`;
12773
+ const secret = `sk_${options.type}_${randomBytes37(24).toString("base64url")}`;
12580
12774
  const prefix = secret.substring(0, 12);
12581
12775
  const key = {
12582
12776
  id,
@@ -12663,7 +12857,7 @@ var MemoryDevPortal = class {
12663
12857
  // API Documentation
12664
12858
  async generateDocumentation(endpoints, config) {
12665
12859
  const doc = {
12666
- id: `doc_${Date.now()}_${Math.random().toString(36).substring(7)}`,
12860
+ id: `doc_${Date.now()}_${randomBytes17(4).toString("hex")}`,
12667
12861
  title: config.title,
12668
12862
  version: config.version,
12669
12863
  baseUrl: config.baseUrl,
@@ -12719,7 +12913,7 @@ var MemoryDevPortal = class {
12719
12913
  if (!doc) throw new Error(`Documentation not found: ${docId}`);
12720
12914
  const newEndpoint = {
12721
12915
  ...endpoint,
12722
- id: `ep_${Date.now()}_${Math.random().toString(36).substring(7)}`
12916
+ id: `ep_${Date.now()}_${randomBytes17(4).toString("hex")}`
12723
12917
  };
12724
12918
  doc.endpoints.push(newEndpoint);
12725
12919
  return newEndpoint;
@@ -12815,7 +13009,7 @@ SDK for ${documentation.title}`,
12815
13009
  });
12816
13010
  }
12817
13011
  const sdk = {
12818
- id: `sdk_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13012
+ id: `sdk_${Date.now()}_${randomBytes17(4).toString("hex")}`,
12819
13013
  language: config.language,
12820
13014
  packageName: config.packageName,
12821
13015
  version: config.version,
@@ -12842,7 +13036,7 @@ SDK for ${documentation.title}`,
12842
13036
  }
12843
13037
  // Sandbox / Playground
12844
13038
  async createSandbox(options, userId) {
12845
- const id = `sandbox_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13039
+ const id = `sandbox_${Date.now()}_${randomBytes17(4).toString("hex")}`;
12846
13040
  const lifetimeHours = options.lifetimeHours || this.config.sandboxDefaultLifetimeHours || 24;
12847
13041
  const sandbox = {
12848
13042
  id,
@@ -12851,7 +13045,7 @@ SDK for ${documentation.title}`,
12851
13045
  tenantId: options.tenantId,
12852
13046
  status: "active",
12853
13047
  baseUrl: `https://sandbox-${id}.example.com`,
12854
- apiKey: `sandbox_${Math.random().toString(36).substring(2)}`,
13048
+ apiKey: `sandbox_${randomBytes17(8).toString("hex")}`,
12855
13049
  seedDataLoaded: options.seedData || [],
12856
13050
  config: options.config || {},
12857
13051
  limits: {
@@ -12988,7 +13182,7 @@ SDK for ${documentation.title}`,
12988
13182
  }
12989
13183
  // Webhook Testing
12990
13184
  async createWebhookTestEndpoint(userId, maxEvents = 100) {
12991
- const id = `wh_test_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13185
+ const id = `wh_test_${Date.now()}_${randomBytes17(4).toString("hex")}`;
12992
13186
  const endpoint = {
12993
13187
  id,
12994
13188
  url: `https://webhook-test.example.com/${id}`,
@@ -13025,18 +13219,13 @@ SDK for ${documentation.title}`,
13025
13219
  statusCode: 200,
13026
13220
  headers: { "content-type": "application/json" },
13027
13221
  body: { received: true },
13028
- latencyMs: Math.random() * 100
13222
+ latencyMs: 0
13029
13223
  };
13030
13224
  }
13031
13225
  // Private helpers
13032
13226
  hashKey(key) {
13033
- let hash = 0;
13034
- for (let i = 0; i < key.length; i++) {
13035
- const char = key.charCodeAt(i);
13036
- hash = (hash << 5) - hash + char;
13037
- hash = hash & hash;
13038
- }
13039
- return `hashed_${Math.abs(hash).toString(36)}`;
13227
+ const { createHash: createHash2 } = __require("crypto");
13228
+ return createHash2("sha256").update(key).digest("hex");
13040
13229
  }
13041
13230
  endpointsToOpenApiPaths(endpoints) {
13042
13231
  const paths = {};
@@ -13128,6 +13317,7 @@ class ApiClient:
13128
13317
  };
13129
13318
 
13130
13319
  // src/interfaces/ICompliance.ts
13320
+ import { randomBytes as randomBytes18 } from "crypto";
13131
13321
  var MemoryCompliance = class {
13132
13322
  constructor(config = {}) {
13133
13323
  this.config = config;
@@ -13144,13 +13334,13 @@ var MemoryCompliance = class {
13144
13334
  breaches = /* @__PURE__ */ new Map();
13145
13335
  // DSAR Management
13146
13336
  async createDsar(options) {
13147
- const id = `dsar_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13337
+ const id = `dsar_${Date.now()}_${randomBytes18(4).toString("hex")}`;
13148
13338
  const dsar = {
13149
13339
  id,
13150
13340
  type: options.type,
13151
13341
  subjectId: options.subjectId || options.subjectEmail,
13152
13342
  subjectEmail: options.subjectEmail,
13153
- verificationToken: `verify_${Math.random().toString(36).substring(2)}`,
13343
+ verificationToken: `verify_${randomBytes18(8).toString("hex")}`,
13154
13344
  verified: false,
13155
13345
  status: "pending_verification",
13156
13346
  tenantId: options.tenantId,
@@ -13201,7 +13391,7 @@ var MemoryCompliance = class {
13201
13391
  dsar.updatedAt = /* @__PURE__ */ new Date();
13202
13392
  if (notes) {
13203
13393
  dsar.notes.push({
13204
- id: `note_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13394
+ id: `note_${Date.now()}_${randomBytes18(4).toString("hex")}`,
13205
13395
  content: notes,
13206
13396
  authorId: "system",
13207
13397
  createdAt: /* @__PURE__ */ new Date()
@@ -13213,7 +13403,7 @@ var MemoryCompliance = class {
13213
13403
  const dsar = await this.getDsar(dsarId);
13214
13404
  if (!dsar) throw new Error(`DSAR not found: ${dsarId}`);
13215
13405
  const note = {
13216
- id: `note_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13406
+ id: `note_${Date.now()}_${randomBytes18(4).toString("hex")}`,
13217
13407
  content,
13218
13408
  authorId,
13219
13409
  createdAt: /* @__PURE__ */ new Date()
@@ -13227,7 +13417,7 @@ var MemoryCompliance = class {
13227
13417
  if (!dsar) throw new Error(`DSAR not found: ${dsarId}`);
13228
13418
  const att = {
13229
13419
  ...attachment,
13230
- id: `att_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13420
+ id: `att_${Date.now()}_${randomBytes18(4).toString("hex")}`,
13231
13421
  createdAt: /* @__PURE__ */ new Date()
13232
13422
  };
13233
13423
  dsar.attachments.push(att);
@@ -13268,7 +13458,7 @@ var MemoryCompliance = class {
13268
13458
  }
13269
13459
  // Consent Management
13270
13460
  async recordConsent(options) {
13271
- const id = `consent_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13461
+ const id = `consent_${Date.now()}_${randomBytes18(4).toString("hex")}`;
13272
13462
  const consent = {
13273
13463
  id,
13274
13464
  subjectId: options.subjectId,
@@ -13343,7 +13533,7 @@ var MemoryCompliance = class {
13343
13533
  }
13344
13534
  // Retention Policies
13345
13535
  async createRetentionPolicy(policy) {
13346
- const id = `rp_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13536
+ const id = `rp_${Date.now()}_${randomBytes18(4).toString("hex")}`;
13347
13537
  const newPolicy = {
13348
13538
  ...policy,
13349
13539
  id,
@@ -13376,7 +13566,7 @@ var MemoryCompliance = class {
13376
13566
  if (!policy) throw new Error(`Policy not found: ${policyId}`);
13377
13567
  const startedAt = /* @__PURE__ */ new Date();
13378
13568
  const execution = {
13379
- id: `re_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13569
+ id: `re_${Date.now()}_${randomBytes18(4).toString("hex")}`,
13380
13570
  policyId,
13381
13571
  recordsProcessed: 100,
13382
13572
  recordsAffected: 15,
@@ -13395,7 +13585,7 @@ var MemoryCompliance = class {
13395
13585
  }
13396
13586
  // Data Inventory
13397
13587
  async addDataInventoryItem(item) {
13398
- const id = `di_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13588
+ const id = `di_${Date.now()}_${randomBytes18(4).toString("hex")}`;
13399
13589
  const newItem = {
13400
13590
  ...item,
13401
13591
  id,
@@ -13456,7 +13646,7 @@ var MemoryCompliance = class {
13456
13646
  }
13457
13647
  // Audit Evidence
13458
13648
  async addEvidence(evidence) {
13459
- const id = `ev_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13649
+ const id = `ev_${Date.now()}_${randomBytes18(4).toString("hex")}`;
13460
13650
  const newEvidence = {
13461
13651
  ...evidence,
13462
13652
  id,
@@ -13532,7 +13722,7 @@ var MemoryCompliance = class {
13532
13722
  }
13533
13723
  // PIAs
13534
13724
  async createPia(pia) {
13535
- const id = `pia_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13725
+ const id = `pia_${Date.now()}_${randomBytes18(4).toString("hex")}`;
13536
13726
  const newPia = {
13537
13727
  ...pia,
13538
13728
  id,
@@ -13564,7 +13754,7 @@ var MemoryCompliance = class {
13564
13754
  if (!pia) throw new Error(`PIA not found: ${piaId}`);
13565
13755
  const newRisk = {
13566
13756
  ...risk,
13567
- id: `risk_${Date.now()}_${Math.random().toString(36).substring(7)}`
13757
+ id: `risk_${Date.now()}_${randomBytes18(4).toString("hex")}`
13568
13758
  };
13569
13759
  pia.risks.push(newRisk);
13570
13760
  pia.updatedAt = /* @__PURE__ */ new Date();
@@ -13575,7 +13765,7 @@ var MemoryCompliance = class {
13575
13765
  if (!pia) throw new Error(`PIA not found: ${piaId}`);
13576
13766
  const newMitigation = {
13577
13767
  ...mitigation,
13578
- id: `mit_${Date.now()}_${Math.random().toString(36).substring(7)}`
13768
+ id: `mit_${Date.now()}_${randomBytes18(4).toString("hex")}`
13579
13769
  };
13580
13770
  pia.mitigations.push(newMitigation);
13581
13771
  pia.updatedAt = /* @__PURE__ */ new Date();
@@ -13612,7 +13802,7 @@ var MemoryCompliance = class {
13612
13802
  (c) => c.status === "non_compliant"
13613
13803
  ).length;
13614
13804
  const report = {
13615
- id: `report_${Date.now()}_${Math.random().toString(36).substring(7)}`,
13805
+ id: `report_${Date.now()}_${randomBytes18(4).toString("hex")}`,
13616
13806
  title: `${framework.toUpperCase()} Compliance Report`,
13617
13807
  framework,
13618
13808
  period,
@@ -13663,7 +13853,7 @@ var MemoryCompliance = class {
13663
13853
  }
13664
13854
  // Breach Management
13665
13855
  async recordBreach(breach) {
13666
- const id = `breach_${Date.now()}_${Math.random().toString(36).substring(7)}`;
13856
+ const id = `breach_${Date.now()}_${randomBytes18(4).toString("hex")}`;
13667
13857
  const newBreach = {
13668
13858
  ...breach,
13669
13859
  id,
@@ -13902,6 +14092,25 @@ var RAGConfigSchema = z.object({
13902
14092
  message: "Pinecone requires apiKey and indexName; Weaviate requires host"
13903
14093
  }
13904
14094
  );
14095
+ var CryptoConfigSchema = z.object({
14096
+ enabled: z.boolean().default(false).describe("Enable field-level encryption"),
14097
+ masterKey: z.string().optional().describe("256-bit master key as hex (64 chars). Required when enabled."),
14098
+ hmacKey: z.string().optional().describe("HMAC key for deterministic hashing (derived from master key if not provided)")
14099
+ }).refine(
14100
+ (data) => {
14101
+ if (data.enabled) {
14102
+ return data.masterKey && data.masterKey.length >= 64;
14103
+ }
14104
+ return true;
14105
+ },
14106
+ {
14107
+ message: "Crypto requires a 256-bit master key (64 hex characters) when enabled"
14108
+ }
14109
+ );
14110
+ var SecurityConfigSchema = z.object({
14111
+ enforceTls: z.boolean().default(true).describe("Enforce TLS for production connections"),
14112
+ tlsWarnOnly: z.boolean().default(false).describe("Warn instead of throwing when TLS is missing in production")
14113
+ });
13905
14114
  var RetryConfigSchema = z.object({
13906
14115
  enabled: z.boolean().default(true).describe("Enable retry for failed operations"),
13907
14116
  maxAttempts: z.number().int().min(1).max(10).default(3).describe("Maximum retry attempts"),
@@ -13991,6 +14200,10 @@ var PlatformConfigSchema = z.object({
13991
14200
  // AI configurations
13992
14201
  ai: AIConfigSchema.default({ enabled: false }),
13993
14202
  rag: RAGConfigSchema.default({ enabled: false }),
14203
+ // Crypto configuration
14204
+ crypto: CryptoConfigSchema.default({ enabled: false }),
14205
+ // Security configuration
14206
+ security: SecurityConfigSchema.default({}),
13994
14207
  // Resilience configuration
13995
14208
  resilience: ResilienceConfigSchema.default({}),
13996
14209
  // Observability configuration
@@ -14068,6 +14281,15 @@ function loadConfig() {
14068
14281
  embeddingApiKey: process.env.EMBEDDING_API_KEY || process.env.OPENAI_API_KEY,
14069
14282
  embeddingModel: process.env.EMBEDDING_MODEL
14070
14283
  },
14284
+ crypto: {
14285
+ enabled: process.env.CRYPTO_ENABLED === "true",
14286
+ masterKey: process.env.CRYPTO_MASTER_KEY,
14287
+ hmacKey: process.env.CRYPTO_HMAC_KEY
14288
+ },
14289
+ security: {
14290
+ enforceTls: process.env.SECURITY_ENFORCE_TLS !== "false",
14291
+ tlsWarnOnly: process.env.SECURITY_TLS_WARN_ONLY === "true"
14292
+ },
14071
14293
  resilience: {
14072
14294
  retry: {
14073
14295
  enabled: process.env.RESILIENCE_RETRY_ENABLED !== "false",
@@ -14474,13 +14696,14 @@ var MemoryEmail = class {
14474
14696
 
14475
14697
  // src/context/CorrelationContext.ts
14476
14698
  import { AsyncLocalStorage } from "async_hooks";
14699
+ import { randomBytes as randomBytes19 } from "crypto";
14477
14700
  var CorrelationContextManager = class {
14478
14701
  storage = new AsyncLocalStorage();
14479
14702
  idGenerator;
14480
14703
  constructor() {
14481
14704
  this.idGenerator = () => {
14482
14705
  const timestamp = Date.now().toString(36);
14483
- const random = Math.random().toString(36).substring(2, 10);
14706
+ const random = randomBytes19(4).toString("hex");
14484
14707
  return `${timestamp}-${random}`;
14485
14708
  };
14486
14709
  }
@@ -15110,10 +15333,11 @@ var MemoryQueue = class {
15110
15333
  };
15111
15334
 
15112
15335
  // src/adapters/console/ConsoleEmail.ts
15336
+ import { randomBytes as randomBytes20 } from "crypto";
15113
15337
  var ConsoleEmail = class {
15114
15338
  sentEmails = [];
15115
15339
  async send(message) {
15116
- const id = `console_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
15340
+ const id = `console_${Date.now()}_${randomBytes20(4).toString("hex")}`;
15117
15341
  console.log("\n" + "=".repeat(60));
15118
15342
  console.log("\u{1F4E7} EMAIL SENT (Console Adapter)");
15119
15343
  console.log("=".repeat(60));
@@ -15190,6 +15414,147 @@ var ConsoleEmail = class {
15190
15414
  // src/factory.ts
15191
15415
  init_IAI();
15192
15416
  init_IRAG();
15417
+
15418
+ // src/adapters/memory/MemoryCrypto.ts
15419
+ import { randomBytes as randomBytes21, createCipheriv, createDecipheriv, createHmac } from "crypto";
15420
+ var MemoryCrypto = class {
15421
+ keys = /* @__PURE__ */ new Map();
15422
+ activeKeyId;
15423
+ hmacKey;
15424
+ constructor(options) {
15425
+ const masterKeyBuf = options?.masterKey ? Buffer.from(options.masterKey, "hex") : randomBytes21(32);
15426
+ this.hmacKey = options?.hmacKey ? Buffer.from(options.hmacKey, "hex") : randomBytes21(32);
15427
+ const keyId = this.generateKeyId();
15428
+ this.keys.set(keyId, {
15429
+ id: keyId,
15430
+ key: masterKeyBuf,
15431
+ status: "active",
15432
+ createdAt: /* @__PURE__ */ new Date()
15433
+ });
15434
+ this.activeKeyId = keyId;
15435
+ }
15436
+ async encrypt(plaintext, options) {
15437
+ const keyId = options?.keyId || this.activeKeyId;
15438
+ const stored = this.keys.get(keyId);
15439
+ if (!stored) {
15440
+ throw new Error(`Key not found: ${keyId}`);
15441
+ }
15442
+ if (stored.status === "retired") {
15443
+ throw new Error(`Key is retired: ${keyId}`);
15444
+ }
15445
+ if (stored.status === "decrypt-only" && !options?.keyId) {
15446
+ throw new Error(`Key is decrypt-only: ${keyId}`);
15447
+ }
15448
+ const iv = randomBytes21(12);
15449
+ const cipher = createCipheriv("aes-256-gcm", stored.key, iv);
15450
+ if (options?.aad) {
15451
+ cipher.setAAD(Buffer.from(options.aad, "utf8"));
15452
+ }
15453
+ const encrypted = Buffer.concat([
15454
+ cipher.update(plaintext, "utf8"),
15455
+ cipher.final()
15456
+ ]);
15457
+ const tag = cipher.getAuthTag();
15458
+ return {
15459
+ ciphertext: encrypted.toString("base64"),
15460
+ iv: iv.toString("base64"),
15461
+ tag: tag.toString("base64"),
15462
+ keyId,
15463
+ algorithm: "aes-256-gcm",
15464
+ version: 1
15465
+ };
15466
+ }
15467
+ async decrypt(field, options) {
15468
+ const stored = this.keys.get(field.keyId);
15469
+ if (!stored) {
15470
+ throw new Error(`Key not found: ${field.keyId}`);
15471
+ }
15472
+ if (stored.status === "retired") {
15473
+ throw new Error(`Key is retired and cannot decrypt: ${field.keyId}`);
15474
+ }
15475
+ const decipher = createDecipheriv(
15476
+ "aes-256-gcm",
15477
+ stored.key,
15478
+ Buffer.from(field.iv, "base64")
15479
+ );
15480
+ decipher.setAuthTag(Buffer.from(field.tag, "base64"));
15481
+ if (options?.aad) {
15482
+ decipher.setAAD(Buffer.from(options.aad, "utf8"));
15483
+ }
15484
+ const decrypted = Buffer.concat([
15485
+ decipher.update(Buffer.from(field.ciphertext, "base64")),
15486
+ decipher.final()
15487
+ ]);
15488
+ return decrypted.toString("utf8");
15489
+ }
15490
+ async encryptDeterministic(plaintext, options) {
15491
+ const hash = await this.computeHash(plaintext);
15492
+ const encrypted = await this.encrypt(plaintext, options);
15493
+ return { hash, encrypted };
15494
+ }
15495
+ async computeHash(plaintext) {
15496
+ return createHmac("sha256", this.hmacKey).update(plaintext, "utf8").digest("hex");
15497
+ }
15498
+ async encryptBatch(fields, options) {
15499
+ const result = {};
15500
+ for (const [key, value] of Object.entries(fields)) {
15501
+ result[key] = await this.encrypt(value, options);
15502
+ }
15503
+ return result;
15504
+ }
15505
+ async decryptBatch(fields, options) {
15506
+ const result = {};
15507
+ for (const [key, value] of Object.entries(fields)) {
15508
+ result[key] = await this.decrypt(value, options);
15509
+ }
15510
+ return result;
15511
+ }
15512
+ async rotateKey() {
15513
+ const previousKeyId = this.activeKeyId;
15514
+ const currentKey = this.keys.get(previousKeyId);
15515
+ if (currentKey) {
15516
+ currentKey.status = "decrypt-only";
15517
+ }
15518
+ const newKeyId = this.generateKeyId();
15519
+ this.keys.set(newKeyId, {
15520
+ id: newKeyId,
15521
+ key: randomBytes21(32),
15522
+ status: "active",
15523
+ createdAt: /* @__PURE__ */ new Date()
15524
+ });
15525
+ this.activeKeyId = newKeyId;
15526
+ return { newKeyId, previousKeyId };
15527
+ }
15528
+ async reEncrypt(field, options) {
15529
+ const plaintext = await this.decrypt(field);
15530
+ return this.encrypt(plaintext, options);
15531
+ }
15532
+ async listKeys() {
15533
+ return Array.from(this.keys.values()).map((k) => ({
15534
+ keyId: k.id,
15535
+ createdAt: k.createdAt,
15536
+ status: k.status
15537
+ }));
15538
+ }
15539
+ async getActiveKeyId() {
15540
+ return this.activeKeyId;
15541
+ }
15542
+ async healthCheck() {
15543
+ try {
15544
+ const testPlain = "health-check-test";
15545
+ const encrypted = await this.encrypt(testPlain);
15546
+ const decrypted = await this.decrypt(encrypted);
15547
+ return decrypted === testPlain;
15548
+ } catch {
15549
+ return false;
15550
+ }
15551
+ }
15552
+ generateKeyId() {
15553
+ return `key_${randomBytes21(8).toString("hex")}`;
15554
+ }
15555
+ };
15556
+
15557
+ // src/factory.ts
15193
15558
  async function createDatabaseAdapter(config) {
15194
15559
  switch (config.database.provider) {
15195
15560
  case "postgres": {
@@ -15490,15 +15855,70 @@ async function createRAGAdapter(config, ai) {
15490
15855
  return new MemoryRAG();
15491
15856
  }
15492
15857
  }
15858
+ async function createCryptoAdapter(config) {
15859
+ if (!config.crypto.enabled) {
15860
+ return null;
15861
+ }
15862
+ if (config.crypto.masterKey && config.crypto.masterKey.length >= 64) {
15863
+ const { NodeCrypto: NodeCrypto2 } = await Promise.resolve().then(() => (init_NodeCrypto(), NodeCrypto_exports));
15864
+ return new NodeCrypto2({
15865
+ masterKey: config.crypto.masterKey,
15866
+ hmacKey: config.crypto.hmacKey
15867
+ });
15868
+ }
15869
+ return new MemoryCrypto();
15870
+ }
15871
+ function validateTlsSecurity(config) {
15872
+ const isProduction = process.env.NODE_ENV === "production";
15873
+ if (!isProduction || !config.security.enforceTls) {
15874
+ return;
15875
+ }
15876
+ const warnings = [];
15877
+ if (config.database.provider === "postgres") {
15878
+ const connStr = config.database.connectionString || config.database.url || "";
15879
+ const hasSSL = config.database.ssl || connStr.includes("sslmode=require") || connStr.includes("sslmode=verify");
15880
+ if (!hasSSL) {
15881
+ warnings.push(
15882
+ "PostgreSQL: TLS/SSL not configured. Set database.ssl=true or add sslmode=require to connection string."
15883
+ );
15884
+ }
15885
+ }
15886
+ if (config.cache.provider === "redis") {
15887
+ const url = config.cache.url || "";
15888
+ if (url && !url.startsWith("rediss://")) {
15889
+ warnings.push(
15890
+ "Redis: Connection URL uses redis:// instead of rediss:// (TLS). Consider enabling TLS."
15891
+ );
15892
+ }
15893
+ }
15894
+ if (config.email.provider === "smtp") {
15895
+ if (!config.email.secure) {
15896
+ warnings.push(
15897
+ "SMTP: secure=false in production. Set email.secure=true for TLS."
15898
+ );
15899
+ }
15900
+ }
15901
+ if (warnings.length > 0) {
15902
+ const message = `[Security] TLS warnings in production:
15903
+ - ${warnings.join("\n - ")}`;
15904
+ if (config.security.tlsWarnOnly) {
15905
+ console.warn(message);
15906
+ } else {
15907
+ throw new Error(message);
15908
+ }
15909
+ }
15910
+ }
15493
15911
  async function createPlatformAsync(config) {
15494
15912
  const finalConfig = config ? deepMerge(loadConfig(), config) : loadConfig();
15495
- const [db, cache, storage, email, queue, tracing] = await Promise.all([
15913
+ validateTlsSecurity(finalConfig);
15914
+ const [db, cache, storage, email, queue, tracing, crypto2] = await Promise.all([
15496
15915
  createDatabaseAdapter(finalConfig),
15497
15916
  createCacheAdapter(finalConfig),
15498
15917
  createStorageAdapter(finalConfig),
15499
15918
  createEmailAdapter(finalConfig),
15500
15919
  createQueueAdapter(finalConfig),
15501
- createTracingAdapter(finalConfig)
15920
+ createTracingAdapter(finalConfig),
15921
+ createCryptoAdapter(finalConfig)
15502
15922
  ]);
15503
15923
  const logger = createLogger(finalConfig);
15504
15924
  const metrics = createMetrics(finalConfig);
@@ -15514,7 +15934,8 @@ async function createPlatformAsync(config) {
15514
15934
  metrics,
15515
15935
  tracing,
15516
15936
  ai,
15517
- rag
15937
+ rag,
15938
+ crypto2
15518
15939
  );
15519
15940
  }
15520
15941
  function createPlatform(config) {
@@ -15535,6 +15956,7 @@ function createPlatform(config) {
15535
15956
  const tracing = finalConfig.observability.tracing.provider === "memory" ? new MemoryTracing() : new NoopTracing();
15536
15957
  const ai = finalConfig.ai.enabled ? new MemoryAI() : null;
15537
15958
  const rag = finalConfig.rag.enabled ? new MemoryRAG() : null;
15959
+ const crypto2 = finalConfig.crypto.enabled ? new MemoryCrypto() : null;
15538
15960
  return createPlatformFromAdapters(
15539
15961
  db,
15540
15962
  cache,
@@ -15545,10 +15967,11 @@ function createPlatform(config) {
15545
15967
  metrics,
15546
15968
  tracing,
15547
15969
  ai,
15548
- rag
15970
+ rag,
15971
+ crypto2
15549
15972
  );
15550
15973
  }
15551
- function createPlatformFromAdapters(db, cache, storage, email, queue, logger, metrics, tracing, ai, rag) {
15974
+ function createPlatformFromAdapters(db, cache, storage, email, queue, logger, metrics, tracing, ai, rag, crypto2) {
15552
15975
  const platform = {
15553
15976
  db,
15554
15977
  cache,
@@ -15602,6 +16025,9 @@ function createPlatformFromAdapters(db, cache, storage, email, queue, logger, me
15602
16025
  if (rag) {
15603
16026
  platform.rag = rag;
15604
16027
  }
16028
+ if (crypto2) {
16029
+ platform.crypto = crypto2;
16030
+ }
15605
16031
  return platform;
15606
16032
  }
15607
16033
  function deepMerge(target, source) {
@@ -17098,6 +17524,113 @@ function sanitizeForEmail(str) {
17098
17524
  return escapeHtml(str);
17099
17525
  }
17100
17526
 
17527
+ // src/security-headers.ts
17528
+ var SecurityHeaderPresets = {
17529
+ /** Minimal: basic headers only, no CSP */
17530
+ minimal: {
17531
+ csp: false,
17532
+ hsts: false
17533
+ },
17534
+ /** Standard: full CSP + HSTS for most apps */
17535
+ standard: {
17536
+ csp: true,
17537
+ hsts: true,
17538
+ frameOptions: "DENY"
17539
+ },
17540
+ /** Strict: deny all permissions, strict CSP, no frame embedding */
17541
+ strict: {
17542
+ csp: true,
17543
+ hsts: true,
17544
+ hstsMaxAge: 63072e3,
17545
+ // 2 years
17546
+ frameOptions: "DENY"
17547
+ }
17548
+ };
17549
+ function generateSecurityHeaders(config = {}) {
17550
+ const isProduction = config.isProduction ?? process.env.NODE_ENV === "production";
17551
+ const frameOptions = config.frameOptions ?? "DENY";
17552
+ const enableCsp = config.csp ?? true;
17553
+ const enableHsts = config.hsts ?? true;
17554
+ const hstsMaxAge = config.hstsMaxAge ?? 31536e3;
17555
+ const baseHeaders = [
17556
+ { key: "X-Frame-Options", value: frameOptions },
17557
+ { key: "X-Content-Type-Options", value: "nosniff" },
17558
+ // Modern browsers use CSP, not XSS-Protection. Value '0' disables the
17559
+ // legacy filter which can itself introduce vulnerabilities.
17560
+ { key: "X-XSS-Protection", value: "0" },
17561
+ {
17562
+ key: "Referrer-Policy",
17563
+ value: "strict-origin-when-cross-origin"
17564
+ },
17565
+ {
17566
+ key: "Permissions-Policy",
17567
+ value: "camera=(), microphone=(), geolocation=()"
17568
+ }
17569
+ ];
17570
+ const entries = [
17571
+ { source: "/:path*", headers: baseHeaders }
17572
+ ];
17573
+ if (isProduction) {
17574
+ const prodHeaders = [];
17575
+ if (enableHsts) {
17576
+ prodHeaders.push({
17577
+ key: "Strict-Transport-Security",
17578
+ value: `max-age=${hstsMaxAge}; includeSubDomains`
17579
+ });
17580
+ }
17581
+ if (enableCsp) {
17582
+ const csp = buildCsp(config);
17583
+ prodHeaders.push({ key: "Content-Security-Policy", value: csp });
17584
+ }
17585
+ if (prodHeaders.length > 0) {
17586
+ entries.push({ source: "/:path*", headers: prodHeaders });
17587
+ }
17588
+ }
17589
+ return entries;
17590
+ }
17591
+ function buildCsp(config) {
17592
+ const scriptSrc = [
17593
+ "'self'",
17594
+ "'unsafe-inline'",
17595
+ "'unsafe-eval'",
17596
+ ...config.cspScriptSrc ?? []
17597
+ ];
17598
+ const styleSrc = [
17599
+ "'self'",
17600
+ "'unsafe-inline'",
17601
+ "https://fonts.googleapis.com",
17602
+ ...config.cspStyleSrc ?? []
17603
+ ];
17604
+ const imgSrc = [
17605
+ "'self'",
17606
+ "data:",
17607
+ "https:",
17608
+ "blob:",
17609
+ ...config.cspImgSrc ?? []
17610
+ ];
17611
+ const fontSrc = ["'self'", "data:", "https://fonts.gstatic.com"];
17612
+ const connectSrc = ["'self'", ...config.cspConnectSrc ?? []];
17613
+ const frameSrc = [...config.cspFrameSrc ?? []];
17614
+ const directives = [
17615
+ `default-src 'self'`,
17616
+ `script-src ${scriptSrc.join(" ")}`,
17617
+ `style-src ${styleSrc.join(" ")}`,
17618
+ `img-src ${imgSrc.join(" ")}`,
17619
+ `font-src ${fontSrc.join(" ")}`,
17620
+ `connect-src ${connectSrc.join(" ")}`
17621
+ ];
17622
+ if (frameSrc.length > 0) {
17623
+ directives.push(`frame-src ${frameSrc.join(" ")}`);
17624
+ }
17625
+ directives.push(
17626
+ `object-src 'none'`,
17627
+ `base-uri 'self'`,
17628
+ `form-action 'self'`,
17629
+ `frame-ancestors 'none'`
17630
+ );
17631
+ return directives.join("; ");
17632
+ }
17633
+
17101
17634
  // src/api.ts
17102
17635
  var ApiErrorCode = {
17103
17636
  VALIDATION_ERROR: "VALIDATION_ERROR",
@@ -18301,7 +18834,7 @@ var MemoryAuditLog = class {
18301
18834
  };
18302
18835
 
18303
18836
  // src/adapters/memory/MemoryWebhook.ts
18304
- import { createHmac } from "crypto";
18837
+ import { createHmac as createHmac3, randomBytes as randomBytes26 } from "crypto";
18305
18838
  var MemoryWebhook = class {
18306
18839
  endpoints = /* @__PURE__ */ new Map();
18307
18840
  deliveries = /* @__PURE__ */ new Map();
@@ -18583,7 +19116,7 @@ var MemoryWebhook = class {
18583
19116
  config.secret,
18584
19117
  algorithm
18585
19118
  );
18586
- const providedSig = signature.replace(/^(sha256=|sha512=|sha1=)/, "");
19119
+ const providedSig = signature.replace(/^(sha256=|sha512=)/, "");
18587
19120
  if (providedSig !== expectedSignature) {
18588
19121
  return { valid: false, error: "Invalid signature" };
18589
19122
  }
@@ -18688,7 +19221,7 @@ var MemoryWebhook = class {
18688
19221
  this.deliveries.set(delivery.id, delivery);
18689
19222
  }
18690
19223
  async executeDelivery(endpoint, event, attemptNumber) {
18691
- const attemptId = `att_${Date.now().toString(36)}${Math.random().toString(36).substring(2, 8)}`;
19224
+ const attemptId = `att_${Date.now().toString(36)}${randomBytes26(4).toString("hex")}`;
18692
19225
  const startTime = Date.now();
18693
19226
  if (this.config.simulatedDelay > 0) {
18694
19227
  await new Promise(
@@ -18742,7 +19275,7 @@ var MemoryWebhook = class {
18742
19275
  this.endpoints.set(endpoint.id, endpoint);
18743
19276
  }
18744
19277
  computeSignature(payload, secret, algorithm) {
18745
- return createHmac(algorithm, secret).update(payload).digest("hex");
19278
+ return createHmac3(algorithm, secret).update(payload).digest("hex");
18746
19279
  }
18747
19280
  };
18748
19281
 
@@ -19093,6 +19626,7 @@ var MemoryNotification = class {
19093
19626
  };
19094
19627
 
19095
19628
  // src/adapters/memory/MemoryScheduler.ts
19629
+ import { randomBytes as randomBytes27 } from "crypto";
19096
19630
  var MemoryScheduler = class {
19097
19631
  config;
19098
19632
  schedules = /* @__PURE__ */ new Map();
@@ -19376,7 +19910,7 @@ var MemoryScheduler = class {
19376
19910
  }
19377
19911
  }
19378
19912
  async executeSchedule(schedule) {
19379
- const executionId = `exec_${Date.now().toString(36)}${Math.random().toString(36).substring(2, 8)}`;
19913
+ const executionId = `exec_${Date.now().toString(36)}${randomBytes27(4).toString("hex")}`;
19380
19914
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
19381
19915
  const execution = {
19382
19916
  id: executionId,
@@ -19856,6 +20390,7 @@ CREATE INDEX IF NOT EXISTS idx_${tableName}_trace_id ON ${tableName}((context->>
19856
20390
  };
19857
20391
 
19858
20392
  // src/adapters/database/DatabaseErrorReporter.ts
20393
+ import { randomBytes as randomBytes28 } from "crypto";
19859
20394
  var DatabaseErrorReporter = class {
19860
20395
  db;
19861
20396
  errorsTable;
@@ -20150,7 +20685,7 @@ CREATE INDEX IF NOT EXISTS idx_${breadcrumbsTable}_error ON ${breadcrumbsTable}(
20150
20685
  if (report.breadcrumbs && report.breadcrumbs.length > 0) {
20151
20686
  for (const crumb of report.breadcrumbs) {
20152
20687
  await this.db.from(this.breadcrumbsTable).insert({
20153
- id: `bc_${Date.now().toString(36)}${Math.random().toString(36).substring(2, 8)}`,
20688
+ id: `bc_${Date.now().toString(36)}${randomBytes28(4).toString("hex")}`,
20154
20689
  error_id: report.id,
20155
20690
  category: crumb.category,
20156
20691
  message: crumb.message,
@@ -20190,6 +20725,7 @@ CREATE INDEX IF NOT EXISTS idx_${breadcrumbsTable}_error ON ${breadcrumbsTable}(
20190
20725
  };
20191
20726
 
20192
20727
  // src/adapters/database/DatabasePromptStore.ts
20728
+ import { randomBytes as randomBytes29 } from "crypto";
20193
20729
  var DatabasePromptStore = class {
20194
20730
  db;
20195
20731
  cache;
@@ -20329,7 +20865,7 @@ CREATE INDEX IF NOT EXISTS idx_${tablePrefix}usage_experiment ON ${tablePrefix}p
20329
20865
  // Prompt CRUD
20330
20866
  // ═══════════════════════════════════════════════════════════════
20331
20867
  async create(prompt) {
20332
- const id = `prompt_${Date.now()}_${Math.random().toString(36).substring(7)}`;
20868
+ const id = `prompt_${Date.now()}_${randomBytes29(4).toString("hex")}`;
20333
20869
  const now = /* @__PURE__ */ new Date();
20334
20870
  const newPrompt = {
20335
20871
  ...prompt,
@@ -20357,7 +20893,7 @@ CREATE INDEX IF NOT EXISTS idx_${tablePrefix}usage_experiment ON ${tablePrefix}p
20357
20893
  created_by: newPrompt.createdBy,
20358
20894
  updated_by: newPrompt.updatedBy
20359
20895
  }).execute();
20360
- const versionId = `pv_${Date.now()}_${Math.random().toString(36).substring(7)}`;
20896
+ const versionId = `pv_${Date.now()}_${randomBytes29(4).toString("hex")}`;
20361
20897
  await this.db.from(this.versionsTable).insert({
20362
20898
  id: versionId,
20363
20899
  prompt_id: id,
@@ -20426,7 +20962,7 @@ CREATE INDEX IF NOT EXISTS idx_${tablePrefix}usage_experiment ON ${tablePrefix}p
20426
20962
  await this.db.from(this.versionsTable).update({ is_latest: false }).where("prompt_id", "=", prompt.id).execute();
20427
20963
  const versionsResult = await this.db.from(this.versionsTable).where("prompt_id", "=", prompt.id).execute();
20428
20964
  const newVersionNum = versionsResult.data.length + 1;
20429
- const versionId = `pv_${Date.now()}_${Math.random().toString(36).substring(7)}`;
20965
+ const versionId = `pv_${Date.now()}_${randomBytes29(4).toString("hex")}`;
20430
20966
  await this.db.from(this.versionsTable).insert({
20431
20967
  id: versionId,
20432
20968
  prompt_id: prompt.id,
@@ -20681,7 +21217,7 @@ ${v2.content}`;
20681
21217
  // A/B Testing
20682
21218
  // ═══════════════════════════════════════════════════════════════
20683
21219
  async createExperiment(experiment) {
20684
- const id = `exp_${Date.now()}_${Math.random().toString(36).substring(7)}`;
21220
+ const id = `exp_${Date.now()}_${randomBytes29(4).toString("hex")}`;
20685
21221
  const now = /* @__PURE__ */ new Date();
20686
21222
  const newExperiment = {
20687
21223
  ...experiment,
@@ -20795,7 +21331,7 @@ ${v2.content}`;
20795
21331
  // Prompt Chains
20796
21332
  // ═══════════════════════════════════════════════════════════════
20797
21333
  async createChain(chain) {
20798
- const id = `chain_${Date.now()}_${Math.random().toString(36).substring(7)}`;
21334
+ const id = `chain_${Date.now()}_${randomBytes29(4).toString("hex")}`;
20799
21335
  const now = /* @__PURE__ */ new Date();
20800
21336
  const newChain = {
20801
21337
  ...chain,
@@ -20893,7 +21429,7 @@ ${v2.content}`;
20893
21429
  // Usage & Analytics
20894
21430
  // ═══════════════════════════════════════════════════════════════
20895
21431
  async recordUsage(record) {
20896
- const id = `usage_${Date.now()}_${Math.random().toString(36).substring(7)}`;
21432
+ const id = `usage_${Date.now()}_${randomBytes29(4).toString("hex")}`;
20897
21433
  const now = /* @__PURE__ */ new Date();
20898
21434
  const usageRecord = {
20899
21435
  ...record,
@@ -21079,8 +21615,9 @@ ${v2.content}`;
21079
21615
  };
21080
21616
 
21081
21617
  // src/adapters/database/DatabaseCompliance.ts
21618
+ import { randomBytes as randomBytes30 } from "crypto";
21082
21619
  function generateId(prefix) {
21083
- return `${prefix}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
21620
+ return `${prefix}_${Date.now()}_${randomBytes30(4).toString("hex")}`;
21084
21621
  }
21085
21622
  function toDate(value) {
21086
21623
  return value ? new Date(value) : void 0;
@@ -21271,7 +21808,7 @@ var DatabaseCompliance = class {
21271
21808
  async createDsar(options) {
21272
21809
  const id = generateId("dsar");
21273
21810
  const now = (/* @__PURE__ */ new Date()).toISOString();
21274
- const verificationToken = `verify_${Math.random().toString(36).substring(2)}`;
21811
+ const verificationToken = `verify_${randomBytes30(16).toString("hex")}`;
21275
21812
  const result = await this.db.from("compliance_dsars").insert({
21276
21813
  id,
21277
21814
  type: options.type,
@@ -22210,6 +22747,7 @@ var DatabaseCompliance = class {
22210
22747
  };
22211
22748
 
22212
22749
  // src/adapters/database/DatabaseAIUsage.ts
22750
+ import { randomBytes as randomBytes31 } from "crypto";
22213
22751
  var DatabaseAIUsage = class {
22214
22752
  db;
22215
22753
  config;
@@ -22223,7 +22761,7 @@ var DatabaseAIUsage = class {
22223
22761
  // Usage Recording
22224
22762
  // ─────────────────────────────────────────────────────────────
22225
22763
  async record(record) {
22226
- const id = `usage_${Date.now()}_${Math.random().toString(36).substring(7)}`;
22764
+ const id = `usage_${Date.now()}_${randomBytes31(4).toString("hex")}`;
22227
22765
  const now = /* @__PURE__ */ new Date();
22228
22766
  await this.db.from(`${this.prefix}records`).insert({
22229
22767
  id,
@@ -22330,7 +22868,7 @@ var DatabaseAIUsage = class {
22330
22868
  quota.category
22331
22869
  );
22332
22870
  const period = this.getPeriodBounds(quota.period, /* @__PURE__ */ new Date());
22333
- const id = existing?.id || `quota_${Date.now()}_${Math.random().toString(36).substring(7)}`;
22871
+ const id = existing?.id || `quota_${Date.now()}_${randomBytes31(4).toString("hex")}`;
22334
22872
  const data = {
22335
22873
  id,
22336
22874
  tenant_id: quota.tenantId,
@@ -22467,7 +23005,7 @@ var DatabaseAIUsage = class {
22467
23005
  existingResult.data[0]
22468
23006
  ) : null;
22469
23007
  const period = this.getPeriodBounds(budget.period, /* @__PURE__ */ new Date());
22470
- const id = existing?.id || `budget_${Date.now()}_${Math.random().toString(36).substring(7)}`;
23008
+ const id = existing?.id || `budget_${Date.now()}_${randomBytes31(4).toString("hex")}`;
22471
23009
  const data = {
22472
23010
  id,
22473
23011
  tenant_id: budget.tenantId,
@@ -22766,7 +23304,7 @@ var DatabaseAIUsage = class {
22766
23304
  }
22767
23305
  const items = Array.from(itemsMap.values());
22768
23306
  const subtotal = items.reduce((sum, item) => sum + item.costUsd, 0);
22769
- const id = `inv_${Date.now()}_${Math.random().toString(36).substring(7)}`;
23307
+ const id = `inv_${Date.now()}_${randomBytes31(4).toString("hex")}`;
22770
23308
  const now = /* @__PURE__ */ new Date();
22771
23309
  await this.db.from(`${this.prefix}invoices`).insert({
22772
23310
  id,
@@ -22988,7 +23526,7 @@ var DatabaseAIUsage = class {
22988
23526
  }
22989
23527
  }
22990
23528
  async createAlert(tenantId, type, severity, message, metadata) {
22991
- const id = `alert_${Date.now()}_${Math.random().toString(36).substring(7)}`;
23529
+ const id = `alert_${Date.now()}_${randomBytes31(4).toString("hex")}`;
22992
23530
  await this.db.from(`${this.prefix}alerts`).insert({
22993
23531
  id,
22994
23532
  tenant_id: tenantId,
@@ -23194,6 +23732,7 @@ var DatabaseAIUsage = class {
23194
23732
  };
23195
23733
 
23196
23734
  // src/adapters/database/DatabaseNotification.ts
23735
+ import { randomBytes as randomBytes32 } from "crypto";
23197
23736
  var DatabaseNotification = class {
23198
23737
  db;
23199
23738
  email;
@@ -23431,7 +23970,7 @@ var DatabaseNotification = class {
23431
23970
  // PUSH SUBSCRIPTIONS
23432
23971
  // ═══════════════════════════════════════════════════════════════
23433
23972
  async registerPushSubscription(userId, subscription) {
23434
- const id = `push_${Date.now()}_${Math.random().toString(36).substring(7)}`;
23973
+ const id = `push_${Date.now()}_${randomBytes32(4).toString("hex")}`;
23435
23974
  const existing = await this.db.from(`${this.prefix}push_subscriptions`).where("user_id", "=", userId).where("endpoint", "=", subscription.endpoint).execute();
23436
23975
  if (existing.data && existing.data.length > 0) {
23437
23976
  await this.db.from(`${this.prefix}push_subscriptions`).where("user_id", "=", userId).where("endpoint", "=", subscription.endpoint).update({
@@ -23529,7 +24068,7 @@ var DatabaseNotification = class {
23529
24068
  // TOPICS
23530
24069
  // ═══════════════════════════════════════════════════════════════
23531
24070
  async subscribeToTopic(userId, topic) {
23532
- const id = `topic_${Date.now()}_${Math.random().toString(36).substring(7)}`;
24071
+ const id = `topic_${Date.now()}_${randomBytes32(4).toString("hex")}`;
23533
24072
  const existing = await this.db.from(`${this.prefix}notification_topic_subs`).where("user_id", "=", userId).where("topic", "=", topic).execute();
23534
24073
  if (!existing.data || existing.data.length === 0) {
23535
24074
  await this.db.from(`${this.prefix}notification_topic_subs`).insert({
@@ -23610,7 +24149,7 @@ var DatabaseNotification = class {
23610
24149
  // PRIVATE HELPERS
23611
24150
  // ═══════════════════════════════════════════════════════════════
23612
24151
  async logDelivery(notificationId, channel, status, messageId, error) {
23613
- const id = `del_${Date.now()}_${Math.random().toString(36).substring(7)}`;
24152
+ const id = `del_${Date.now()}_${randomBytes32(4).toString("hex")}`;
23614
24153
  try {
23615
24154
  await this.db.from(`${this.prefix}notification_delivery_log`).insert({
23616
24155
  id,
@@ -23672,6 +24211,7 @@ var DatabaseNotification = class {
23672
24211
  };
23673
24212
 
23674
24213
  // src/adapters/database/DatabaseBilling.ts
24214
+ import { randomBytes as randomBytes33 } from "crypto";
23675
24215
  var DatabaseBilling = class {
23676
24216
  db;
23677
24217
  prefix;
@@ -23694,7 +24234,7 @@ var DatabaseBilling = class {
23694
24234
  return `${this.prefix}${name}`;
23695
24235
  }
23696
24236
  generateId(prefix) {
23697
- return `${prefix}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
24237
+ return `${prefix}_${Date.now()}_${randomBytes33(4).toString("hex")}`;
23698
24238
  }
23699
24239
  // ─────────────────────────────────────────────────────────────
23700
24240
  // Product & Price Management
@@ -25192,6 +25732,7 @@ var DatabaseBilling = class {
25192
25732
  };
25193
25733
 
25194
25734
  // src/adapters/scheduler/QueueScheduler.ts
25735
+ import { randomBytes as randomBytes34 } from "crypto";
25195
25736
  var QueueScheduler = class {
25196
25737
  queue;
25197
25738
  db;
@@ -25607,7 +26148,7 @@ CREATE INDEX IF NOT EXISTS idx_${executionsTable}_started ON ${executionsTable}(
25607
26148
  }
25608
26149
  }
25609
26150
  async executeSchedule(schedule) {
25610
- const executionId = `exec_${Date.now().toString(36)}${Math.random().toString(36).substring(2, 8)}`;
26151
+ const executionId = `exec_${Date.now().toString(36)}${randomBytes34(4).toString("hex")}`;
25611
26152
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
25612
26153
  const execution = {
25613
26154
  id: executionId,
@@ -25770,7 +26311,7 @@ CREATE INDEX IF NOT EXISTS idx_${executionsTable}_started ON ${executionsTable}(
25770
26311
  };
25771
26312
 
25772
26313
  // src/adapters/webhook/HttpWebhook.ts
25773
- import { createHmac as createHmac2, timingSafeEqual } from "crypto";
26314
+ import { createHmac as createHmac4, timingSafeEqual, randomBytes as randomBytes35 } from "crypto";
25774
26315
  var HttpWebhook = class {
25775
26316
  db;
25776
26317
  queue;
@@ -26112,7 +26653,7 @@ var HttpWebhook = class {
26112
26653
  config.secret,
26113
26654
  algorithm
26114
26655
  );
26115
- const providedSig = signature.replace(/^(sha256=|sha512=|sha1=)/, "");
26656
+ const providedSig = signature.replace(/^(sha256=|sha512=)/, "");
26116
26657
  try {
26117
26658
  const providedBuffer = Buffer.from(providedSig, "hex");
26118
26659
  const expectedBuffer = Buffer.from(expectedSignature, "hex");
@@ -26368,7 +26909,7 @@ CREATE INDEX IF NOT EXISTS idx_${attemptsTable}_delivery ON ${attemptsTable}(del
26368
26909
  await this.saveDelivery(delivery);
26369
26910
  }
26370
26911
  async executeDelivery(endpoint, event, attemptNumber) {
26371
- const attemptId = `att_${Date.now().toString(36)}${Math.random().toString(36).substring(2, 8)}`;
26912
+ const attemptId = `att_${Date.now().toString(36)}${randomBytes35(4).toString("hex")}`;
26372
26913
  const startTime = Date.now();
26373
26914
  const payloadStr = JSON.stringify(event);
26374
26915
  const signature = this.computeSignature(
@@ -26472,7 +27013,7 @@ CREATE INDEX IF NOT EXISTS idx_${attemptsTable}_delivery ON ${attemptsTable}(del
26472
27013
  await this.saveEndpoint(endpoint);
26473
27014
  }
26474
27015
  computeSignature(payload, secret, algorithm) {
26475
- return createHmac2(algorithm, secret).update(payload).digest("hex");
27016
+ return createHmac4(algorithm, secret).update(payload).digest("hex");
26476
27017
  }
26477
27018
  endpointToRow(endpoint) {
26478
27019
  return {
@@ -27794,6 +28335,9 @@ init_PineconeRAG();
27794
28335
  // src/adapters/weaviate/index.ts
27795
28336
  init_WeaviateRAG();
27796
28337
 
28338
+ // src/index.ts
28339
+ init_NodeCrypto();
28340
+
27797
28341
  // src/adapters/oidc/GenericOIDCAuthSSO.ts
27798
28342
  function generateRandomString(length) {
27799
28343
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
@@ -28387,6 +28931,7 @@ var GenericOIDCAuthSSO = class {
28387
28931
  };
28388
28932
 
28389
28933
  // src/adapters/postgres-tenant/PostgresTenant.ts
28934
+ import { randomBytes as randomBytes36 } from "crypto";
28390
28935
  var tenantContextMap = /* @__PURE__ */ new Map();
28391
28936
  var contextIdCounter2 = 0;
28392
28937
  var currentContextId2 = null;
@@ -29168,7 +29713,7 @@ var PostgresTenant = class {
29168
29713
  }
29169
29714
  };
29170
29715
  function generateId2() {
29171
- return Math.random().toString(36).substring(2) + Date.now().toString(36);
29716
+ return randomBytes36(8).toString("hex") + Date.now().toString(36);
29172
29717
  }
29173
29718
 
29174
29719
  // src/migrations/Migrator.ts
@@ -29950,6 +30495,7 @@ export {
29950
30495
  ConsoleEmail,
29951
30496
  ConsoleLogger,
29952
30497
  CronPresets,
30498
+ CryptoConfigSchema,
29953
30499
  DEFAULT_BULKHEAD_OPTIONS,
29954
30500
  DEFAULT_CIRCUIT_BREAKER_OPTIONS,
29955
30501
  DEFAULT_RETRY_OPTIONS,
@@ -29981,6 +30527,7 @@ export {
29981
30527
  MemoryBilling,
29982
30528
  MemoryCache,
29983
30529
  MemoryCompliance,
30530
+ MemoryCrypto,
29984
30531
  MemoryDatabase,
29985
30532
  MemoryDevPortal,
29986
30533
  MemoryDevice,
@@ -30002,6 +30549,7 @@ export {
30002
30549
  MetricsConfigSchema,
30003
30550
  MiddlewareConfigSchema,
30004
30551
  Migrator,
30552
+ NodeCrypto,
30005
30553
  NoopLogger,
30006
30554
  NoopMetrics,
30007
30555
  NoopTracing,
@@ -30029,6 +30577,8 @@ export {
30029
30577
  RetryPredicates,
30030
30578
  S3Storage,
30031
30579
  SQL,
30580
+ SecurityConfigSchema,
30581
+ SecurityHeaderPresets,
30032
30582
  SmtpEmail,
30033
30583
  StorageConfigSchema,
30034
30584
  StorageProviderSchema,
@@ -30118,6 +30668,7 @@ export {
30118
30668
  generatePaymentId,
30119
30669
  generateScheduleId,
30120
30670
  generateSecureToken,
30671
+ generateSecurityHeaders,
30121
30672
  generateVersion,
30122
30673
  generateWebhookId,
30123
30674
  generateWebhookSecret,