@culturefy/shared 1.0.62 → 1.0.64
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/build/cjs/enums/secretKeys.enum.js +0 -1
- package/build/cjs/enums/secretKeys.enum.js.map +1 -1
- package/build/cjs/interfaces/user.js.map +1 -1
- package/build/cjs/middlewares/verify-middleware.js +83 -18
- package/build/cjs/middlewares/verify-middleware.js.map +1 -1
- package/build/cjs/repositories/multi-tenant.repository.js +24 -11
- package/build/cjs/repositories/multi-tenant.repository.js.map +1 -1
- package/build/cjs/repositories/tenant-base.repository.js +7 -1
- package/build/cjs/repositories/tenant-base.repository.js.map +1 -1
- package/build/cjs/utils/initializers.js +11 -5
- package/build/cjs/utils/initializers.js.map +1 -1
- package/build/esm/enums/secretKeys.enum.js +0 -1
- package/build/esm/enums/secretKeys.enum.js.map +1 -1
- package/build/esm/interfaces/user.js.map +1 -1
- package/build/esm/middlewares/verify-middleware.js +85 -20
- package/build/esm/middlewares/verify-middleware.js.map +1 -1
- package/build/esm/repositories/multi-tenant.repository.js +24 -11
- package/build/esm/repositories/multi-tenant.repository.js.map +1 -1
- package/build/esm/repositories/tenant-base.repository.js +7 -1
- package/build/esm/repositories/tenant-base.repository.js.map +1 -1
- package/build/esm/utils/initializers.js +11 -5
- package/build/esm/utils/initializers.js.map +1 -1
- package/build/src/enums/secretKeys.enum.d.ts +0 -1
- package/build/src/enums/secretKeys.enum.js +0 -1
- package/build/src/enums/secretKeys.enum.js.map +1 -1
- package/build/src/middlewares/verify-middleware.js +90 -36
- package/build/src/middlewares/verify-middleware.js.map +1 -1
- package/build/src/repositories/multi-tenant.repository.d.ts +1 -0
- package/build/src/repositories/multi-tenant.repository.js +24 -11
- package/build/src/repositories/multi-tenant.repository.js.map +1 -1
- package/build/src/repositories/tenant-base.repository.d.ts +1 -0
- package/build/src/repositories/tenant-base.repository.js +18 -0
- package/build/src/repositories/tenant-base.repository.js.map +1 -1
- package/build/src/utils/initializers.d.ts +1 -0
- package/build/src/utils/initializers.js +11 -5
- package/build/src/utils/initializers.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multi-tenant.repository.js","names":["_mongoose","_interopRequireWildcard","require","crypto","_identity","_keyvaultSecrets","_enums","_cache","_secrets","_configMapping","_dec","_dec2","_dec3","_class","_MultiTenantRepository","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","_applyDecoratedDescriptor","l","a","keys","forEach","enumerable","configurable","initializer","writable","slice","reverse","reduce","value","tenantDbCache","createCache","tenantBridgeCache","encryptionKeyCache","WithTenantDb","_target","_propertyKey","descriptor","originalMethod","args","ensureClientConnection","apply","MultiTenantRepository","exports","Cacheable","cache","key","getContext","instance","context","businessId","appId","serviceDbType","constructor","config","serviceDBType","tenantBridgeConfig","dbConnectionEncryptionKey","clientConnectionString","connectionPromise","tenantBridgeEnvKey","tenantBridgeSecretKey","AzureSecretKeysEnum","DB_CONNECTING_STRING_TENANT_BRIDGE","getEncryptionIv","iv","process","env","DB_CONNECTION_STRING_ENCRYPTION_IV","Buffer","alloc","normalizeFixedSize","label","utf8Value","from","length","base64Value","hexValue","Error","getOrCreateCachedConnection","connectionString","existing","connections","connection","readyState","info","mongoose","Mongoose","connect","serverSelectionTimeoutMS","connectTimeoutMS","socketTimeoutMS","err","error","message","name","code","stack","toObjectId","id","fieldName","Types","ObjectId","isValid","getTenantBridgeSrvDbConnectionString","envKey","localUri","undefined","vault","AZURE_KEY_VAULT_NAME","secretKey","dbUrl","getAzureVaultSecretByKey","getDbConnectionEncryptionKey","_secret$value","DB_CONNECTION_STRING_ENCRYPTION_KEY","vaultUrl","credential","DefaultAzureCredential","client","SecretClient","secret","getSecret","decryptConnectionString","encryptedValue","keyBuffer","normalizeEncryptionKey","ivBuffer","decipher","createDecipheriv","decrypted","update","final","utf8Key","base64Key","hexKey","getClientDbConnectionString","resolvedServiceDbType","tenantBridgeUrl","ConfigMapping","getModel","CONFIG_MAPPING_DOCUMENT_NAME","ConfigMappingModel","schema","CONFIG_MAPPING_COLLECTION_NAME","filter","configMapping","findOne","lean","exec","decryptedConnectionString","getConnection","clientDbUrl","disconnectByConnectionString","disconnect","delete","disconnectClient","getTenantModel","modelName","collectionName","model","models","Map","prototype","TenantModelRepository","modelDef","dbModel"],"sources":["../../../src/repositories/multi-tenant.repository.ts"],"sourcesContent":["import mongoose, { Model, Schema, Types } from \"mongoose\";\nimport * as crypto from \"crypto\";\nimport { InvocationContext } from \"@azure/functions\";\nimport { DefaultAzureCredential } from \"@azure/identity\";\nimport { SecretClient } from \"@azure/keyvault-secrets\";\nimport { AzureSecretKeysEnum } from \"../enums\";\nimport { Cacheable, createCache } from \"../utils/cache\";\nimport { getAzureVaultSecretByKey } from \"../utils/secrets\";\nimport {\n CONFIG_MAPPING_COLLECTION_NAME,\n CONFIG_MAPPING_DOCUMENT_NAME,\n ConfigMappingModel,\n IConfigMapping,\n} from \"../models/config-mapping.model\";\n\ntype ConnectionMap = Map<string, mongoose.Mongoose>;\n\ntype TenantBridgeConfig = {\n tenantBridgeEnvKey?: string;\n tenantBridgeSecretKey?: AzureSecretKeysEnum;\n};\n\nconst tenantDbCache = createCache(\"tenant-db\", 600);\nconst tenantBridgeCache = createCache(\"tenant-bridge-db-connection-string\", 1800);\nconst encryptionKeyCache = createCache(\"db-enc-key\", 1800);\n\n/**\n * Decorator that ensures tenant DB is connected before the method runs.\n */\nexport function WithTenantDb(\n _target: any,\n _propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>,\n): void {\n if (!descriptor.value) return;\n const originalMethod = descriptor.value;\n descriptor.value = async function (\n this: MultiTenantRepository,\n ...args: any[]\n ) {\n await this.ensureClientConnection();\n return originalMethod.apply(this, args);\n };\n}\n\nexport class MultiTenantRepository {\n private static connections: ConnectionMap = new Map();\n private readonly context: InvocationContext;\n private readonly tenantBridgeConfig: TenantBridgeConfig;\n private readonly businessId: string;\n private readonly appId?: string;\n private readonly serviceDBType?: string;\n private dbConnectionEncryptionKey?: string;\n private clientConnectionString?: string;\n private connectionPromise?: Promise<mongoose.Mongoose>;\n\n constructor(\n context: InvocationContext,\n businessId: string,\n appId?: string,\n config?: TenantBridgeConfig,\n serviceDBType?: string,\n ) {\n this.context = context;\n this.businessId = businessId;\n this.appId = appId;\n this.serviceDBType = serviceDBType ?? \"main\";\n this.tenantBridgeConfig = {\n tenantBridgeEnvKey: \"TENANT_BRIDGE_DB_URI\",\n tenantBridgeSecretKey: AzureSecretKeysEnum.DB_CONNECTING_STRING_TENANT_BRIDGE,\n ...config,\n };\n\n this.connectionPromise = this.ensureClientConnection();\n }\n\n private getEncryptionIv(): Buffer {\n const iv = process.env.DB_CONNECTION_STRING_ENCRYPTION_IV;\n if (!iv) {\n return Buffer.alloc(16, 0);\n }\n return this.normalizeFixedSize(iv, \"IV\");\n }\n\n private normalizeFixedSize(value: string, label: string): Buffer {\n const utf8Value = Buffer.from(value, \"utf8\");\n if (utf8Value.length === 16) {\n return utf8Value;\n }\n\n const base64Value = Buffer.from(value, \"base64\");\n if (base64Value.length === 16) {\n return base64Value;\n }\n\n const hexValue = Buffer.from(value, \"hex\");\n if (hexValue.length === 16) {\n return hexValue;\n }\n\n throw new Error(\n `${label} must be 16 bytes for aes-128-cbc (got ${utf8Value.length})`,\n );\n }\n\n private async getOrCreateCachedConnection(\n connectionString: string,\n ): Promise<mongoose.Mongoose> {\n const existing = MultiTenantRepository.connections.get(connectionString);\n if (existing && existing.connection.readyState === 1) {\n return existing;\n }\n\n this.context.info(`Initializing database connection... ${connectionString}`);\n const instance = new mongoose.Mongoose();\n\n try {\n await instance.connect(connectionString, {\n serverSelectionTimeoutMS: 10000,\n connectTimeoutMS: 10000,\n socketTimeoutMS: 45000,\n });\n this.context.info(`✅ MongoDB connected successfully ${connectionString}`);\n MultiTenantRepository.connections.set(connectionString, instance);\n return instance;\n } catch (err: any) {\n this.context.error(\n `❌ MongoDB connection error for ${connectionString}`,\n {\n message: err.message,\n name: err.name,\n code: err.code,\n stack: err.stack,\n },\n );\n throw new Error(`Failed to connect to MongoDB: ${err.message}`);\n }\n }\n\n private toObjectId(id: string, fieldName: string): Types.ObjectId {\n if (!Types.ObjectId.isValid(id)) {\n throw new Error(`Invalid ${fieldName}`);\n }\n return new Types.ObjectId(id);\n }\n\n @Cacheable({\n cache: tenantBridgeCache,\n key: () => [\"tenant-bridge\"],\n getContext: (instance: unknown) =>\n (instance as MultiTenantRepository).context,\n })\n async getTenantBridgeSrvDbConnectionString(): Promise<string> {\n const envKey = this.tenantBridgeConfig.tenantBridgeEnvKey;\n const localUri =\n (envKey ? process.env[envKey] : undefined);\n\n if (localUri) {\n return localUri;\n }\n\n const vault = process.env.AZURE_KEY_VAULT_NAME || \"\";\n const secretKey =\n this.tenantBridgeConfig.tenantBridgeSecretKey ||\n AzureSecretKeysEnum.DB_CONNECTING_STRING_TENANT_BRIDGE;\n\n const dbUrl = await getAzureVaultSecretByKey(\n this.context,\n vault,\n secretKey,\n );\n if (!dbUrl) {\n throw new Error(\"TenantBridge database connection string not found\");\n }\n return dbUrl;\n }\n\n @Cacheable({\n cache: encryptionKeyCache,\n key: () => [\"key\"],\n getContext: (instance: unknown) =>\n (instance as MultiTenantRepository).context,\n })\n private async getDbConnectionEncryptionKey(): Promise<string> {\n if (this.dbConnectionEncryptionKey) {\n return this.dbConnectionEncryptionKey;\n }\n\n const envKey = process.env.DB_CONNECTION_STRING_ENCRYPTION_KEY;\n if (envKey) {\n this.dbConnectionEncryptionKey = envKey;\n return envKey;\n }\n\n const vault = process.env.AZURE_KEY_VAULT_NAME || \"\";\n if (!vault) {\n throw new Error(\"AZURE_KEY_VAULT_NAME is required to fetch encryption key\");\n }\n const vaultUrl = `https://${vault}.vault.azure.net`;\n const credential = new DefaultAzureCredential();\n const client = new SecretClient(vaultUrl, credential);\n const secret = await client.getSecret(\"DB-CONNECTION-STRING-ENCRYPTION-KEY\");\n const key = secret.value ?? \"\";\n if (!key) {\n throw new Error(\"DB connection string encryption key not found\");\n }\n this.dbConnectionEncryptionKey = key;\n return key;\n }\n\n private async decryptConnectionString(encryptedValue: string): Promise<string> {\n const key = await this.getDbConnectionEncryptionKey();\n const keyBuffer = this.normalizeEncryptionKey(key);\n\n const ivBuffer = this.getEncryptionIv();\n const decipher = crypto.createDecipheriv(\"aes-128-cbc\", keyBuffer, ivBuffer);\n let decrypted = decipher.update(encryptedValue, \"base64\", \"utf8\");\n decrypted += decipher.final(\"utf8\");\n return decrypted;\n }\n\n private normalizeEncryptionKey(key: string): Buffer {\n const utf8Key = Buffer.from(key, \"utf8\");\n if (utf8Key.length === 16) {\n return utf8Key;\n }\n\n const base64Key = Buffer.from(key, \"base64\");\n if (base64Key.length === 16) {\n return base64Key;\n }\n\n const hexKey = Buffer.from(key, \"hex\");\n if (hexKey.length === 16) {\n return hexKey;\n }\n\n throw new Error(\n `DB connection string encryption key must be 16 bytes for aes-128-cbc (got ${utf8Key.length})`,\n );\n }\n\n @Cacheable({\n cache: tenantDbCache,\n key: (businessId: string, appId?: string, serviceDbType?: string) => [\n businessId,\n appId,\n serviceDbType,\n ],\n getContext: (instance: unknown) =>\n (instance as MultiTenantRepository).context,\n })\n async getClientDbConnectionString(\n businessId: string,\n appId?: string,\n serviceDBType?: string,\n ): Promise<string> {\n const resolvedServiceDbType = serviceDBType ?? \"main\";\n const tenantBridgeUrl = await this.getTenantBridgeSrvDbConnectionString();\n const connection = await this.getOrCreateCachedConnection(tenantBridgeUrl);\n\n const ConfigMapping = this.getModel(\n connection,\n CONFIG_MAPPING_DOCUMENT_NAME,\n ConfigMappingModel.schema,\n CONFIG_MAPPING_COLLECTION_NAME,\n ) as Model<IConfigMapping>;\n\n const filter: Record<string, unknown> = {\n businessId: this.toObjectId(businessId, \"businessId\"),\n };\n if (appId) {\n filter.appId = appId;\n }\n filter.serviceDBType = resolvedServiceDbType;\n\n const configMapping =\n (await ConfigMapping.findOne(filter).lean().exec()) as\n | IConfigMapping\n | null;\n if (!configMapping?.connectionString) {\n throw new Error(\"Config mapping not found for this business\");\n }\n const decryptedConnectionString = await this.decryptConnectionString(\n configMapping.connectionString,\n );\n this.context.info(\n `Resolved tenant DB connection string from bridge: ${decryptedConnectionString}`,\n );\n return decryptedConnectionString;\n }\n\n protected getConnection(): mongoose.Mongoose | undefined {\n if (!this.clientConnectionString) return undefined;\n return MultiTenantRepository.connections.get(this.clientConnectionString);\n }\n\n protected async ensureClientConnection(): Promise<mongoose.Mongoose> {\n if (this.connectionPromise) {\n return this.connectionPromise;\n }\n\n if (this.clientConnectionString) {\n const existing = this.getConnection();\n if (existing && existing.connection.readyState === 1) {\n return existing;\n }\n }\n\n const clientDbUrl = await this.getClientDbConnectionString(\n this.businessId,\n this.appId,\n this.serviceDBType,\n );\n this.clientConnectionString = clientDbUrl;\n this.connectionPromise = this.getOrCreateCachedConnection(clientDbUrl);\n return this.connectionPromise;\n }\n\n async disconnectByConnectionString(connectionString: string): Promise<void> {\n const existing = MultiTenantRepository.connections.get(connectionString);\n if (!existing) return;\n try {\n await existing.disconnect();\n this.context.info(`✅ Disconnected from database: ${connectionString}`);\n } catch (error) {\n this.context.error(`❌ Error disconnecting from database: ${connectionString}`, error);\n } finally {\n MultiTenantRepository.connections.delete(connectionString);\n }\n }\n\n async disconnectClient(): Promise<void> {\n const clientDbUrl = await this.getClientDbConnectionString(\n this.businessId,\n this.appId,\n );\n await this.disconnectByConnectionString(clientDbUrl);\n this.clientConnectionString = undefined;\n this.connectionPromise = undefined;\n }\n\n protected getTenantModel(\n modelName: string,\n schema: Schema<any>,\n collectionName?: string,\n ): Model<any> {\n const connection = this.getConnection();\n if (!connection) {\n throw new Error(\"database connection not established\");\n }\n return this.getModel(connection, modelName, schema, collectionName);\n }\n\n protected model<T>(model: Model<T>, collectionName?: string): Model<T> {\n return this.getTenantModel(\n model.modelName,\n model.schema,\n collectionName,\n ) as Model<T>;\n }\n\n protected getModel(\n connection: mongoose.Mongoose,\n modelName: string,\n schema: Schema<any>,\n collectionName?: string,\n ): Model<any> {\n if (connection.models[modelName]) {\n return connection.models[modelName] as Model<any>;\n }\n return connection.model(modelName, schema, collectionName);\n }\n}\n\nexport abstract class TenantModelRepository<T> extends MultiTenantRepository {\n protected abstract readonly modelDef: Model<T>;\n\n protected get dbModel(): Model<T> {\n return this.model(this.modelDef);\n }\n}\n"],"mappings":";;;;;AAAA,IAAAA,SAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAF,uBAAA,CAAAC,OAAA;AAEA,IAAAE,SAAA,GAAAF,OAAA;AACA,IAAAG,gBAAA,GAAAH,OAAA;AACA,IAAAI,MAAA,GAAAJ,OAAA;AACA,IAAAK,MAAA,GAAAL,OAAA;AACA,IAAAM,QAAA,GAAAN,OAAA;AACA,IAAAO,cAAA,GAAAP,OAAA;AAKwC,IAAAQ,IAAA,EAAAC,KAAA,EAAAC,KAAA,EAAAC,MAAA,EAAAC,sBAAA;AAAA,SAAAb,wBAAAc,CAAA,EAAAC,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAhB,uBAAA,YAAAA,CAAAc,CAAA,EAAAC,CAAA,SAAAA,CAAA,IAAAD,CAAA,IAAAA,CAAA,CAAAK,UAAA,SAAAL,CAAA,MAAAM,CAAA,EAAAC,CAAA,EAAAC,CAAA,KAAAC,SAAA,QAAAC,OAAA,EAAAV,CAAA,iBAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,SAAAQ,CAAA,MAAAF,CAAA,GAAAL,CAAA,GAAAG,CAAA,GAAAD,CAAA,QAAAG,CAAA,CAAAK,GAAA,CAAAX,CAAA,UAAAM,CAAA,CAAAM,GAAA,CAAAZ,CAAA,GAAAM,CAAA,CAAAO,GAAA,CAAAb,CAAA,EAAAQ,CAAA,gBAAAP,CAAA,IAAAD,CAAA,gBAAA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ZgB,cACF,CAAC;EACH;EAEUnB,QAAQA,CAChBzD,UAA6B,EAC7B2E,SAAiB,EACjBf,MAAmB,EACnBgB,cAAuB,EACX;IACZ,IAAI5E,UAAU,CAAC8E,MAAM,CAACH,SAAS,CAAC,EAAE;MAChC,OAAO3E,UAAU,CAAC8E,MAAM,CAACH,SAAS,CAAC;IACrC;IACA,OAAO3E,UAAU,CAAC6E,KAAK,CAACF,SAAS,EAAEf,MAAM,EAAEgB,cAAc,CAAC;EAC5D;AACF,CAAC,EAAAlK,sBAAA,CAvUgBqF,WAAW,GAAkB,IAAIgF,GAAG,CAAC,CAAC,EAAArK,sBAAA,GAAAoB,yBAAA,CAAArB,MAAA,CAAAuK,SAAA,2CAAA1K,IAAA,GAAAqB,MAAA,CAAAE,wBAAA,CAAApB,MAAA,CAAAuK,SAAA,2CAAAvK,MAAA,CAAAuK,SAAA,GAAAlJ,yBAAA,CAAArB,MAAA,CAAAuK,SAAA,mCAAAzK,KAAA,GAAAoB,MAAA,CAAAE,wBAAA,CAAApB,MAAA,CAAAuK,SAAA,mCAAAvK,MAAA,CAAAuK,SAAA,GAAAlJ,yBAAA,CAAArB,MAAA,CAAAuK,SAAA,kCAAAxK,KAAA,GAAAmB,MAAA,CAAAE,wBAAA,CAAApB,MAAA,CAAAuK,SAAA,kCAAAvK,MAAA,CAAAuK,SAAA,GAAAvK,MAAA;AAyUhD,MAAewK,qBAAqB,SAAY1H,qBAAqB,CAAC;EAAAW,YAAA,GAAAd,IAAA;IAAA,SAAAA,IAAA;IAAA,KAC/C8H,QAAQ;EAAA;EAEpC,IAAcC,OAAOA,CAAA,EAAa;IAChC,OAAO,IAAI,CAACN,KAAK,CAAC,IAAI,CAACK,QAAQ,CAAC;EAClC;AACF;AAAC1H,OAAA,CAAAyH,qBAAA,GAAAA,qBAAA","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"multi-tenant.repository.js","names":["_mongoose","_interopRequireWildcard","require","crypto","_identity","_keyvaultSecrets","_enums","_cache","_secrets","_configMapping","_dec","_dec2","_dec3","_class","_MultiTenantRepository","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","_applyDecoratedDescriptor","l","a","keys","forEach","enumerable","configurable","initializer","writable","slice","reverse","reduce","value","tenantDbCache","createCache","tenantBridgeCache","encryptionKeyCache","WithTenantDb","_target","_propertyKey","descriptor","originalMethod","args","ensureClientConnection","apply","MultiTenantRepository","exports","Cacheable","cache","key","getContext","instance","context","businessId","appId","serviceDbType","constructor","config","serviceDBType","tenantBridgeConfig","dbConnectionEncryptionKey","clientConnectionString","connectionPromise","tenantBridgeEnvKey","tenantBridgeSecretKey","AzureSecretKeysEnum","DB_CONNECTION_STRING_TENANT_BRIDGE","getConnectionLogLabel","connectionString","match","dbName","toLowerCase","includes","getEncryptionIv","iv","process","env","DB_CONNECTION_STRING_ENCRYPTION_IV","Buffer","alloc","normalizeFixedSize","label","utf8Value","from","length","base64Value","hexValue","Error","getOrCreateCachedConnection","existing","connections","connection","readyState","dbLabel","info","mongoose","Mongoose","connect","serverSelectionTimeoutMS","connectTimeoutMS","socketTimeoutMS","err","error","message","name","code","stack","toObjectId","id","fieldName","Types","ObjectId","isValid","getTenantBridgeSrvDbConnectionString","envKey","localUri","undefined","vault","AZURE_KEY_VAULT_NAME","secretKey","dbUrl","getAzureVaultSecretByKey","getDbConnectionEncryptionKey","_secret$value","DB_CONNECTION_STRING_ENCRYPTION_KEY","vaultUrl","credential","DefaultAzureCredential","client","SecretClient","secret","getSecret","decryptConnectionString","encryptedValue","keyBuffer","normalizeEncryptionKey","ivBuffer","decipher","createDecipheriv","decrypted","update","final","utf8Key","base64Key","hexKey","getClientDbConnectionString","resolvedServiceDbType","tenantBridgeUrl","ConfigMapping","getModel","CONFIG_MAPPING_DOCUMENT_NAME","ConfigMappingModel","schema","CONFIG_MAPPING_COLLECTION_NAME","filter","configMapping","findOne","lean","exec","decryptedConnectionString","getConnection","clientDbUrl","disconnectByConnectionString","disconnect","delete","disconnectClient","getTenantModel","modelName","collectionName","model","models","Map","prototype","TenantModelRepository","modelDef","dbModel"],"sources":["../../../src/repositories/multi-tenant.repository.ts"],"sourcesContent":["import mongoose, { Model, Schema, Types } from \"mongoose\";\nimport * as crypto from \"crypto\";\nimport { InvocationContext } from \"@azure/functions\";\nimport { DefaultAzureCredential } from \"@azure/identity\";\nimport { SecretClient } from \"@azure/keyvault-secrets\";\nimport { AzureSecretKeysEnum } from \"../enums\";\nimport { Cacheable, createCache } from \"../utils/cache\";\nimport { getAzureVaultSecretByKey } from \"../utils/secrets\";\nimport {\n CONFIG_MAPPING_COLLECTION_NAME,\n CONFIG_MAPPING_DOCUMENT_NAME,\n ConfigMappingModel,\n IConfigMapping,\n} from \"../models/config-mapping.model\";\n\ntype ConnectionMap = Map<string, mongoose.Mongoose>;\n\ntype TenantBridgeConfig = {\n tenantBridgeEnvKey?: string;\n tenantBridgeSecretKey?: AzureSecretKeysEnum;\n};\n\nconst tenantDbCache = createCache(\"tenant-db\", 600);\nconst tenantBridgeCache = createCache(\"tenant-bridge-db-connection-string\", 1800);\nconst encryptionKeyCache = createCache(\"db-enc-key\", 1800);\n\n/**\n * Decorator that ensures tenant DB is connected before the method runs.\n */\nexport function WithTenantDb(\n _target: any,\n _propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>,\n): void {\n if (!descriptor.value) return;\n const originalMethod = descriptor.value;\n descriptor.value = async function (\n this: MultiTenantRepository,\n ...args: any[]\n ) {\n await this.ensureClientConnection();\n return originalMethod.apply(this, args);\n };\n}\n\nexport class MultiTenantRepository {\n private static connections: ConnectionMap = new Map();\n private readonly context: InvocationContext;\n private readonly tenantBridgeConfig: TenantBridgeConfig;\n private readonly businessId: string;\n private readonly appId?: string;\n private readonly serviceDBType?: string;\n private dbConnectionEncryptionKey?: string;\n private clientConnectionString?: string;\n private connectionPromise?: Promise<mongoose.Mongoose>;\n\n constructor(\n context: InvocationContext,\n businessId: string,\n appId?: string,\n config?: TenantBridgeConfig,\n serviceDBType?: string,\n ) {\n this.context = context;\n this.businessId = businessId;\n this.appId = appId;\n this.serviceDBType = serviceDBType ?? \"main\";\n this.tenantBridgeConfig = {\n tenantBridgeEnvKey: \"TENANT_BRIDGE_DB_URI\",\n tenantBridgeSecretKey: AzureSecretKeysEnum.DB_CONNECTION_STRING_TENANT_BRIDGE,\n ...config,\n };\n\n this.connectionPromise = this.ensureClientConnection();\n }\n\n private getConnectionLogLabel(connectionString: string): string {\n const match = connectionString.match(/\\/([^/?]+)(\\?|$)/);\n const dbName = match?.[1] || \"unknown\";\n if (dbName.toLowerCase().includes(\"tenantbridge\")) {\n return \"TenantBridge-DB\";\n }\n if (dbName.toLowerCase().includes(\"user\")) {\n return \"Auth-DB\";\n }\n return `${dbName}-DB`;\n }\n\n private getEncryptionIv(): Buffer {\n const iv = process.env.DB_CONNECTION_STRING_ENCRYPTION_IV;\n if (!iv) {\n return Buffer.alloc(16, 0);\n }\n return this.normalizeFixedSize(iv, \"IV\");\n }\n\n private normalizeFixedSize(value: string, label: string): Buffer {\n const utf8Value = Buffer.from(value, \"utf8\");\n if (utf8Value.length === 16) {\n return utf8Value;\n }\n\n const base64Value = Buffer.from(value, \"base64\");\n if (base64Value.length === 16) {\n return base64Value;\n }\n\n const hexValue = Buffer.from(value, \"hex\");\n if (hexValue.length === 16) {\n return hexValue;\n }\n\n throw new Error(\n `${label} must be 16 bytes for aes-128-cbc (got ${utf8Value.length})`,\n );\n }\n\n private async getOrCreateCachedConnection(\n connectionString: string,\n ): Promise<mongoose.Mongoose> {\n const existing = MultiTenantRepository.connections.get(connectionString);\n if (existing && existing.connection.readyState === 1) {\n return existing;\n }\n\n const dbLabel = this.getConnectionLogLabel(connectionString);\n this.context.info(`Initializing database connection (${dbLabel})...`);\n const instance = new mongoose.Mongoose();\n\n try {\n await instance.connect(connectionString, {\n serverSelectionTimeoutMS: 10000,\n connectTimeoutMS: 10000,\n socketTimeoutMS: 45000,\n });\n this.context.info(`✅ MongoDB connected successfully (${dbLabel})`);\n MultiTenantRepository.connections.set(connectionString, instance);\n return instance;\n } catch (err: any) {\n this.context.error(\n `❌ MongoDB connection error for (${dbLabel})`,\n {\n message: err.message,\n name: err.name,\n code: err.code,\n stack: err.stack,\n },\n );\n throw new Error(`Failed to connect to MongoDB: ${err.message}`);\n }\n }\n\n private toObjectId(id: string, fieldName: string): Types.ObjectId {\n if (!Types.ObjectId.isValid(id)) {\n throw new Error(`Invalid ${fieldName}`);\n }\n return new Types.ObjectId(id);\n }\n\n @Cacheable({\n cache: tenantBridgeCache,\n key: () => [\"tenant-bridge\"],\n getContext: (instance: unknown) =>\n (instance as MultiTenantRepository).context,\n })\n async getTenantBridgeSrvDbConnectionString(): Promise<string> {\n const envKey = this.tenantBridgeConfig.tenantBridgeEnvKey;\n const localUri =\n (envKey ? process.env[envKey] : undefined);\n\n if (localUri) {\n return localUri;\n }\n\n const vault = process.env.AZURE_KEY_VAULT_NAME || \"\";\n const secretKey =\n this.tenantBridgeConfig.tenantBridgeSecretKey ||\n AzureSecretKeysEnum.DB_CONNECTION_STRING_TENANT_BRIDGE;\n\n const dbUrl = await getAzureVaultSecretByKey(\n this.context,\n vault,\n secretKey,\n );\n if (!dbUrl) {\n throw new Error(\"TenantBridge database connection string not found\");\n }\n return dbUrl;\n }\n\n @Cacheable({\n cache: encryptionKeyCache,\n key: () => [\"key\"],\n getContext: (instance: unknown) =>\n (instance as MultiTenantRepository).context,\n })\n private async getDbConnectionEncryptionKey(): Promise<string> {\n if (this.dbConnectionEncryptionKey) {\n return this.dbConnectionEncryptionKey;\n }\n\n const envKey = process.env.DB_CONNECTION_STRING_ENCRYPTION_KEY;\n if (envKey) {\n this.dbConnectionEncryptionKey = envKey;\n return envKey;\n }\n\n const vault = process.env.AZURE_KEY_VAULT_NAME || \"\";\n if (!vault) {\n throw new Error(\"AZURE_KEY_VAULT_NAME is required to fetch encryption key\");\n }\n const vaultUrl = `https://${vault}.vault.azure.net`;\n const credential = new DefaultAzureCredential();\n const client = new SecretClient(vaultUrl, credential);\n const secret = await client.getSecret(\"DB-CONNECTION-STRING-ENCRYPTION-KEY\");\n const key = secret.value ?? \"\";\n if (!key) {\n throw new Error(\"DB connection string encryption key not found\");\n }\n this.dbConnectionEncryptionKey = key;\n return key;\n }\n\n private async decryptConnectionString(encryptedValue: string): Promise<string> {\n const key = await this.getDbConnectionEncryptionKey();\n const keyBuffer = this.normalizeEncryptionKey(key);\n\n const ivBuffer = this.getEncryptionIv();\n const decipher = crypto.createDecipheriv(\"aes-128-cbc\", keyBuffer, ivBuffer);\n let decrypted = decipher.update(encryptedValue, \"base64\", \"utf8\");\n decrypted += decipher.final(\"utf8\");\n return decrypted;\n }\n\n private normalizeEncryptionKey(key: string): Buffer {\n const utf8Key = Buffer.from(key, \"utf8\");\n if (utf8Key.length === 16) {\n return utf8Key;\n }\n\n const base64Key = Buffer.from(key, \"base64\");\n if (base64Key.length === 16) {\n return base64Key;\n }\n\n const hexKey = Buffer.from(key, \"hex\");\n if (hexKey.length === 16) {\n return hexKey;\n }\n\n throw new Error(\n `DB connection string encryption key must be 16 bytes for aes-128-cbc (got ${utf8Key.length})`,\n );\n }\n\n @Cacheable({\n cache: tenantDbCache,\n key: (businessId: string, appId?: string, serviceDbType?: string) => [\n businessId,\n appId,\n serviceDbType,\n ],\n getContext: (instance: unknown) =>\n (instance as MultiTenantRepository).context,\n })\n async getClientDbConnectionString(\n businessId: string,\n appId?: string,\n serviceDBType?: string,\n ): Promise<string> {\n if (!appId) {\n throw new Error(\"appId is required to resolve tenant client database\");\n }\n const resolvedServiceDbType = serviceDBType ?? \"main\";\n const tenantBridgeUrl = await this.getTenantBridgeSrvDbConnectionString();\n const connection = await this.getOrCreateCachedConnection(tenantBridgeUrl);\n\n const ConfigMapping = this.getModel(\n connection,\n CONFIG_MAPPING_DOCUMENT_NAME,\n ConfigMappingModel.schema,\n CONFIG_MAPPING_COLLECTION_NAME,\n ) as Model<IConfigMapping>;\n\n const filter: Record<string, unknown> = {\n businessId: this.toObjectId(businessId, \"businessId\"),\n };\n filter.appId = appId;\n filter.serviceDBType = resolvedServiceDbType;\n\n const configMapping =\n (await ConfigMapping.findOne(filter).lean().exec()) as\n | IConfigMapping\n | null;\n if (!configMapping?.connectionString) {\n throw new Error(\"Config mapping not found for this business\");\n }\n const decryptedConnectionString = await this.decryptConnectionString(\n configMapping.connectionString,\n );\n this.context.info(\"Resolved tenant database mapping from TenantBridge\");\n return decryptedConnectionString;\n }\n\n protected getConnection(): mongoose.Mongoose | undefined {\n if (!this.clientConnectionString) return undefined;\n return MultiTenantRepository.connections.get(this.clientConnectionString);\n }\n\n protected async ensureClientConnection(): Promise<mongoose.Mongoose> {\n if (this.connectionPromise) {\n return this.connectionPromise;\n }\n\n if (this.clientConnectionString) {\n const existing = this.getConnection();\n if (existing && existing.connection.readyState === 1) {\n return existing;\n }\n }\n\n const clientDbUrl = await this.getClientDbConnectionString(\n this.businessId,\n this.appId,\n this.serviceDBType,\n );\n this.clientConnectionString = clientDbUrl;\n this.connectionPromise = this.getOrCreateCachedConnection(clientDbUrl);\n return this.connectionPromise;\n }\n\n async disconnectByConnectionString(connectionString: string): Promise<void> {\n const existing = MultiTenantRepository.connections.get(connectionString);\n if (!existing) return;\n try {\n await existing.disconnect();\n this.context.info(`✅ Disconnected from database (${this.getConnectionLogLabel(connectionString)})`);\n } catch (error) {\n this.context.error(`❌ Error disconnecting from database (${this.getConnectionLogLabel(connectionString)})`, error);\n } finally {\n MultiTenantRepository.connections.delete(connectionString);\n }\n }\n\n async disconnectClient(): Promise<void> {\n const clientDbUrl = await this.getClientDbConnectionString(\n this.businessId,\n this.appId,\n );\n await this.disconnectByConnectionString(clientDbUrl);\n this.clientConnectionString = undefined;\n this.connectionPromise = undefined;\n }\n\n protected getTenantModel(\n modelName: string,\n schema: Schema<any>,\n collectionName?: string,\n ): Model<any> {\n const connection = this.getConnection();\n if (!connection) {\n throw new Error(\"database connection not established\");\n }\n return this.getModel(connection, modelName, schema, collectionName);\n }\n\n protected model<T>(model: Model<T>, collectionName?: string): Model<T> {\n return this.getTenantModel(\n model.modelName,\n model.schema,\n collectionName,\n ) as Model<T>;\n }\n\n protected getModel(\n connection: mongoose.Mongoose,\n modelName: string,\n schema: Schema<any>,\n collectionName?: string,\n ): Model<any> {\n if (connection.models[modelName]) {\n return connection.models[modelName] as Model<any>;\n }\n return connection.model(modelName, schema, collectionName);\n }\n}\n\nexport abstract class TenantModelRepository<T> extends MultiTenantRepository {\n protected abstract readonly modelDef: Model<T>;\n\n protected get dbModel(): Model<T> {\n return this.model(this.modelDef);\n }\n}\n"],"mappings":";;;;;AAAA,IAAAA,SAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAF,uBAAA,CAAAC,OAAA;AAEA,IAAAE,SAAA,GAAAF,OAAA;AACA,IAAAG,gBAAA,GAAAH,OAAA;AACA,IAAAI,MAAA,GAAAJ,OAAA;AACA,IAAAK,MAAA,GAAAL,OAAA;AACA,IAAAM,QAAA,GAAAN,OAAA;AACA,IAAAO,cAAA,GAAAP,OAAA;AAKwC,IAAAQ,IAAA,EAAAC,KAAA,EAAAC,KAAA,EAAAC,MAAA,EAAAC,sBAAA;AAAA,SAAAb,wBAAAc,CAAA,EAAAC,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAhB,uBAAA,YAAAA,CAAAc,CAAA,EAAAC,CAAA,SAAAA,CAAA,IAAAD,CAAA,IAAAA,CAAA,CAAAK,UAAA,SAAAL,CAAA,MAAAM,CAAA,EAAAC,CAAA,EAAAC,CAAA,KAAAC,SAAA,QAAAC,OAAA,EAAAV,CAAA,iBAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,SAAAQ,CAAA,MAAAF,CAAA,GAAAL,CAAA,GAAAG,CAAA,GAAAD,CAAA,QAAAG,CAAA,CAAAK,GAAA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qB,MAAA,CAAAE,wBAAA,CAAApB,MAAA,CAAA6K,SAAA,2CAAA7K,MAAA,CAAA6K,SAAA,GAAAxJ,yBAAA,CAAArB,MAAA,CAAA6K,SAAA,mCAAA/K,KAAA,GAAAoB,MAAA,CAAAE,wBAAA,CAAApB,MAAA,CAAA6K,SAAA,mCAAA7K,MAAA,CAAA6K,SAAA,GAAAxJ,yBAAA,CAAArB,MAAA,CAAA6K,SAAA,kCAAA9K,KAAA,GAAAmB,MAAA,CAAAE,wBAAA,CAAApB,MAAA,CAAA6K,SAAA,kCAAA7K,MAAA,CAAA6K,SAAA,GAAA7K,MAAA;AAqVhD,MAAe8K,qBAAqB,SAAYhI,qBAAqB,CAAC;EAAAW,YAAA,GAAAd,IAAA;IAAA,SAAAA,IAAA;IAAA,KAC/CoI,QAAQ;EAAA;EAEpC,IAAcC,OAAOA,CAAA,EAAa;IAChC,OAAO,IAAI,CAACN,KAAK,CAAC,IAAI,CAACK,QAAQ,CAAC;EAClC;AACF;AAAChI,OAAA,CAAA+H,qBAAA,GAAAA,qBAAA","ignoreList":[]}
|
|
@@ -19,6 +19,12 @@ let TenantBaseRepository = exports.TenantBaseRepository = (_class = class Tenant
|
|
|
19
19
|
async createMany(body) {
|
|
20
20
|
return this.dbModel.insertMany(body);
|
|
21
21
|
}
|
|
22
|
+
async findAllWithPagination(query, page, limit, sort = {
|
|
23
|
+
createdAt: -1
|
|
24
|
+
}, projection = {}) {
|
|
25
|
+
const list = await this.dbModel.find(query, projection).sort(sort).skip((page - 1) * limit).limit(limit).lean().exec();
|
|
26
|
+
return list;
|
|
27
|
+
}
|
|
22
28
|
async count(query = {}) {
|
|
23
29
|
return this.dbModel.countDocuments(query).exec();
|
|
24
30
|
}
|
|
@@ -48,5 +54,5 @@ let TenantBaseRepository = exports.TenantBaseRepository = (_class = class Tenant
|
|
|
48
54
|
async deleteMany(query = {}) {
|
|
49
55
|
return this.dbModel.deleteMany(query).exec();
|
|
50
56
|
}
|
|
51
|
-
}, _applyDecoratedDescriptor(_class.prototype, "aggregate", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "aggregate"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "create", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "create"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "createMany", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "createMany"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "count", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "count"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "findById", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "findById"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "findOne", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "findOne"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "find", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "find"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "updateById", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "updateById"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "updateOne", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "updateOne"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "updateMany", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "updateMany"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "deleteById", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "deleteById"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "deleteMany", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "deleteMany"), _class.prototype), _class);
|
|
57
|
+
}, _applyDecoratedDescriptor(_class.prototype, "aggregate", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "aggregate"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "create", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "create"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "createMany", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "createMany"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "findAllWithPagination", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "findAllWithPagination"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "count", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "count"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "findById", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "findById"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "findOne", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "findOne"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "find", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "find"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "updateById", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "updateById"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "updateOne", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "updateOne"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "updateMany", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "updateMany"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "deleteById", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "deleteById"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "deleteMany", [_multiTenant.WithTenantDb], Object.getOwnPropertyDescriptor(_class.prototype, "deleteMany"), _class.prototype), _class);
|
|
52
58
|
//# sourceMappingURL=tenant-base.repository.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tenant-base.repository.js","names":["_multiTenant","require","_class","_applyDecoratedDescriptor","i","e","r","n","l","a","Object","keys","forEach","enumerable","configurable","initializer","writable","slice","reverse","reduce","value","call","defineProperty","TenantBaseRepository","exports","TenantModelRepository","constructor","args","modelDef","aggregate","pipeline","dbModel","exec","create","body","createMany","insertMany","
|
|
1
|
+
{"version":3,"file":"tenant-base.repository.js","names":["_multiTenant","require","_class","_applyDecoratedDescriptor","i","e","r","n","l","a","Object","keys","forEach","enumerable","configurable","initializer","writable","slice","reverse","reduce","value","call","defineProperty","TenantBaseRepository","exports","TenantModelRepository","constructor","args","modelDef","aggregate","pipeline","dbModel","exec","create","body","createMany","insertMany","findAllWithPagination","query","page","limit","sort","createdAt","projection","list","find","skip","lean","count","countDocuments","findById","id","options","findOne","updateById","new","findByIdAndUpdate","updateOne","updateMany","deleteById","findByIdAndDelete","deleteMany","prototype","WithTenantDb","getOwnPropertyDescriptor"],"sources":["../../../src/repositories/tenant-base.repository.ts"],"sourcesContent":["import {\n FilterQuery,\n Model,\n PipelineStage,\n ProjectionType,\n QueryOptions,\n UpdateQuery,\n} from \"mongoose\";\nimport { TenantModelRepository, WithTenantDb } from \"./multi-tenant.repository\";\n\nexport abstract class TenantBaseRepository<T> extends TenantModelRepository<T> {\n protected abstract readonly modelDef: Model<T>;\n\n @WithTenantDb\n async aggregate(\n pipeline: PipelineStage[],\n ): Promise<any[]> {\n return this.dbModel.aggregate(pipeline).exec();\n }\n\n @WithTenantDb\n async create(body: T): Promise<T> {\n return this.dbModel.create(body);\n }\n\n @WithTenantDb\n async createMany(body: T[]): Promise<T[]> {\n return this.dbModel.insertMany(body);\n }\n\n @WithTenantDb\n async findAllWithPagination(\n query: FilterQuery<T>,\n page: number,\n limit: number,\n sort: Record<string, 1 | -1> = { createdAt: -1 },\n projection: ProjectionType<T> = {},\n ): Promise<T[]> {\n const list = await this.dbModel\n .find(query, projection)\n .sort(sort)\n .skip((page - 1) * limit)\n .limit(limit)\n .lean()\n .exec();\n return list as T[];\n }\n\n @WithTenantDb\n async count(query: FilterQuery<T> = {}): Promise<number> {\n return this.dbModel.countDocuments(query).exec();\n }\n\n @WithTenantDb\n async findById(\n id: string,\n projection: ProjectionType<T> = {},\n options: QueryOptions<T> = {},\n ): Promise<T | null> {\n return this.dbModel.findById(id, projection, options).exec();\n }\n\n @WithTenantDb\n async findOne(\n query: FilterQuery<T>,\n projection: ProjectionType<T> = {},\n options: QueryOptions<T> = {},\n ): Promise<T | null> {\n return this.dbModel.findOne(query, projection, options).exec();\n }\n\n @WithTenantDb\n async find(\n query: FilterQuery<T> = {},\n projection: ProjectionType<T> = {},\n options: QueryOptions<T> = {},\n ): Promise<T[]> {\n return this.dbModel.find(query, projection, options).exec();\n }\n\n @WithTenantDb\n async updateById(\n id: string,\n body: UpdateQuery<T>,\n options: any = { new: true },\n ): Promise<T | null> {\n return this.dbModel.findByIdAndUpdate(id, body, options).exec() as Promise<\n T | null\n >;\n }\n\n @WithTenantDb\n async updateOne(\n query: FilterQuery<T>,\n body: UpdateQuery<T>,\n options: any = {},\n ): Promise<any> {\n return this.dbModel.updateOne(query, body, options).exec();\n }\n\n @WithTenantDb\n async updateMany(\n query: FilterQuery<T>,\n body: UpdateQuery<T>,\n options: any = {},\n ): Promise<any> {\n return this.dbModel.updateMany(query, body, options).exec();\n }\n\n @WithTenantDb\n async deleteById(id: string): Promise<T | null> {\n return this.dbModel.findByIdAndDelete(id).exec();\n }\n\n @WithTenantDb\n async deleteMany(query: FilterQuery<T> = {}): Promise<any> {\n return this.dbModel.deleteMany(query).exec();\n }\n}\n"],"mappings":";;;;AAQA,IAAAA,YAAA,GAAAC,OAAA;AAAgF,IAAAC,MAAA;AAAA,SAAAC,0BAAAC,CAAA,EAAAC,CAAA,EAAAC,CAAA,EAAAC,CAAA,EAAAC,CAAA,QAAAC,CAAA,cAAAC,MAAA,CAAAC,IAAA,CAAAJ,CAAA,EAAAK,OAAA,WAAAR,CAA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4D,SAAA,iBASZC,yBAAY,GAAArD,MAAA,CAAAsD,wBAAA,CAAA9D,MAAA,CAAA4D,SAAA,iBAAA5D,MAAA,CAAA4D,SAAA,GAAA3D,yBAAA,CAAAD,MAAA,CAAA4D,SAAA,iBASZC,yBAAY,GAAArD,MAAA,CAAAsD,wBAAA,CAAA9D,MAAA,CAAA4D,SAAA,iBAAA5D,MAAA,CAAA4D,SAAA,GAAA3D,yBAAA,CAAAD,MAAA,CAAA4D,SAAA,iBAKZC,yBAAY,GAAArD,MAAA,CAAAsD,wBAAA,CAAA9D,MAAA,CAAA4D,SAAA,iBAAA5D,MAAA,CAAA4D,SAAA,GAAA5D,MAAA","ignoreList":[]}
|
|
@@ -24,6 +24,11 @@ class Initializers {
|
|
|
24
24
|
this.context = context;
|
|
25
25
|
this.dbConnectionString = dbConnectionString;
|
|
26
26
|
}
|
|
27
|
+
getDbLogLabel() {
|
|
28
|
+
const match = this.dbConnectionString.match(/\/([^/?]+)(\?|$)/);
|
|
29
|
+
const dbName = (match == null ? void 0 : match[1]) || "unknown";
|
|
30
|
+
return `${dbName}`;
|
|
31
|
+
}
|
|
27
32
|
async ensureConnection() {
|
|
28
33
|
// Check if we already have a connection for this specific connection string
|
|
29
34
|
const existingConnection = Initializers.connections.get(this.dbConnectionString);
|
|
@@ -32,7 +37,8 @@ class Initializers {
|
|
|
32
37
|
}
|
|
33
38
|
|
|
34
39
|
// Create a new Mongoose instance for this connection string
|
|
35
|
-
|
|
40
|
+
const dbLabel = this.getDbLogLabel();
|
|
41
|
+
this.context.info(`Initializing database connection (${dbLabel})...`);
|
|
36
42
|
const newMongoose = new _mongoose.default.Mongoose();
|
|
37
43
|
try {
|
|
38
44
|
await newMongoose.connect(this.dbConnectionString, {
|
|
@@ -40,14 +46,14 @@ class Initializers {
|
|
|
40
46
|
connectTimeoutMS: 10000,
|
|
41
47
|
socketTimeoutMS: 45000
|
|
42
48
|
});
|
|
43
|
-
this.context.info(`✅ MongoDB connected successfully ${
|
|
49
|
+
this.context.info(`✅ MongoDB connected successfully (${dbLabel})`);
|
|
44
50
|
this.connectionInitialized = true;
|
|
45
51
|
|
|
46
52
|
// Store the connection for this connection string
|
|
47
53
|
Initializers.connections.set(this.dbConnectionString, newMongoose);
|
|
48
54
|
return newMongoose;
|
|
49
55
|
} catch (err) {
|
|
50
|
-
this.context.error(`❌ MongoDB connection error for ${
|
|
56
|
+
this.context.error(`❌ MongoDB connection error for (${dbLabel})`, {
|
|
51
57
|
message: err.message,
|
|
52
58
|
name: err.name,
|
|
53
59
|
code: err.code,
|
|
@@ -76,9 +82,9 @@ class Initializers {
|
|
|
76
82
|
try {
|
|
77
83
|
// Properly close the connection
|
|
78
84
|
await connection.disconnect();
|
|
79
|
-
this.context.info(`✅ Disconnected from database
|
|
85
|
+
this.context.info(`✅ Disconnected from database (${this.getDbLogLabel()})`);
|
|
80
86
|
} catch (error) {
|
|
81
|
-
this.context.error(`❌ Error disconnecting from database
|
|
87
|
+
this.context.error(`❌ Error disconnecting from database (${this.getDbLogLabel()})`, error);
|
|
82
88
|
} finally {
|
|
83
89
|
// Always remove from the connections map
|
|
84
90
|
Initializers.connections.delete(this.dbConnectionString);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initializers.js","names":["_mongoose","_interopRequireDefault","require","e","__esModule","default","WithDb","_target","_propertyKey","descriptor","value","originalMethod","args","ensureConnection","apply","Initializers","constructor","context","dbConnectionString","connectionInitialized","existingConnection","connections","get","connection","readyState","info","newMongoose","mongoose","Mongoose","connect","serverSelectionTimeoutMS","connectTimeoutMS","socketTimeoutMS","set","err","error","message","name","code","stack","Error","getConnection","forceNewConnection","disconnect","delete","exports","Map"],"sources":["../../../src/utils/initializers.ts"],"sourcesContent":["import mongoose from \"mongoose\";\nimport { InvocationContext } from \"@azure/functions\";\n\n/**\n * Decorator that ensures MongoDB is connected before the method runs.\n */\nexport function WithDb(\n _target: any,\n _propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>\n): void {\n if (!descriptor.value) return;\n const originalMethod = descriptor.value;\n descriptor.value = async function (this: Initializers, ...args: any[]) {\n await this.ensureConnection();\n return originalMethod.apply(this, args);\n };\n}\n\nexport abstract class Initializers {\n protected static connections: Map<string, mongoose.Mongoose> = new Map();\n protected context: InvocationContext;\n protected dbConnectionString: string;\n private connectionInitialized: boolean = false;\n\n constructor(context: InvocationContext, dbConnectionString: string) {\n this.context = context;\n this.dbConnectionString = dbConnectionString;\n }\n\n protected async ensureConnection(): Promise<mongoose.Mongoose> {\n // Check if we already have a connection for this specific connection string\n const existingConnection = Initializers.connections.get(this.dbConnectionString);\n if (existingConnection && existingConnection.connection.readyState === 1) {\n return existingConnection;\n }\n\n // Create a new Mongoose instance for this connection string\n this.context.info(`Initializing database connection
|
|
1
|
+
{"version":3,"file":"initializers.js","names":["_mongoose","_interopRequireDefault","require","e","__esModule","default","WithDb","_target","_propertyKey","descriptor","value","originalMethod","args","ensureConnection","apply","Initializers","constructor","context","dbConnectionString","connectionInitialized","getDbLogLabel","match","dbName","existingConnection","connections","get","connection","readyState","dbLabel","info","newMongoose","mongoose","Mongoose","connect","serverSelectionTimeoutMS","connectTimeoutMS","socketTimeoutMS","set","err","error","message","name","code","stack","Error","getConnection","forceNewConnection","disconnect","delete","exports","Map"],"sources":["../../../src/utils/initializers.ts"],"sourcesContent":["import mongoose from \"mongoose\";\nimport { InvocationContext } from \"@azure/functions\";\n\n/**\n * Decorator that ensures MongoDB is connected before the method runs.\n */\nexport function WithDb(\n _target: any,\n _propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<(...args: any[]) => Promise<any>>\n): void {\n if (!descriptor.value) return;\n const originalMethod = descriptor.value;\n descriptor.value = async function (this: Initializers, ...args: any[]) {\n await this.ensureConnection();\n return originalMethod.apply(this, args);\n };\n}\n\nexport abstract class Initializers {\n protected static connections: Map<string, mongoose.Mongoose> = new Map();\n protected context: InvocationContext;\n protected dbConnectionString: string;\n private connectionInitialized: boolean = false;\n\n constructor(context: InvocationContext, dbConnectionString: string) {\n this.context = context;\n this.dbConnectionString = dbConnectionString;\n }\n\n private getDbLogLabel(): string {\n const match = this.dbConnectionString.match(/\\/([^/?]+)(\\?|$)/);\n const dbName = match?.[1] || \"unknown\";\n return `${dbName}`;\n }\n\n protected async ensureConnection(): Promise<mongoose.Mongoose> {\n // Check if we already have a connection for this specific connection string\n const existingConnection = Initializers.connections.get(this.dbConnectionString);\n if (existingConnection && existingConnection.connection.readyState === 1) {\n return existingConnection;\n }\n\n // Create a new Mongoose instance for this connection string\n const dbLabel = this.getDbLogLabel();\n this.context.info(`Initializing database connection (${dbLabel})...`);\n const newMongoose = new mongoose.Mongoose();\n \n try {\n await newMongoose.connect(this.dbConnectionString, {\n serverSelectionTimeoutMS: 10000,\n connectTimeoutMS: 10000,\n socketTimeoutMS: 45000,\n });\n \n this.context.info(`✅ MongoDB connected successfully (${dbLabel})`);\n this.connectionInitialized = true;\n \n // Store the connection for this connection string\n Initializers.connections.set(this.dbConnectionString, newMongoose);\n \n return newMongoose;\n } catch (err: any) {\n this.context.error(`❌ MongoDB connection error for (${dbLabel})`, {\n message: err.message,\n name: err.name,\n code: err.code,\n stack: err.stack\n });\n this.connectionInitialized = false;\n throw new Error(`Failed to connect to MongoDB: ${err.message}`);\n }\n }\n\n protected getConnection(): mongoose.Mongoose | undefined {\n return Initializers.connections.get(this.dbConnectionString);\n }\n\n async forceNewConnection(): Promise<mongoose.Mongoose> {\n // Disconnect existing connection if any\n await this.disconnect();\n \n // Reset connection state\n this.connectionInitialized = false;\n \n // Create a new connection\n return this.ensureConnection();\n }\n \n async disconnect(): Promise<void> {\n const connection = Initializers.connections.get(this.dbConnectionString);\n if (connection) {\n try {\n // Properly close the connection\n await connection.disconnect();\n this.context.info(`✅ Disconnected from database (${this.getDbLogLabel()})`);\n } catch (error) {\n this.context.error(`❌ Error disconnecting from database (${this.getDbLogLabel()})`, error);\n } finally {\n // Always remove from the connections map\n Initializers.connections.del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,CAAC5B,qBAAqB,GAAG,KAAK;;IAElC;IACA,OAAO,IAAI,CAACN,gBAAgB,CAAC,CAAC;EAChC;EAEA,MAAMkC,UAAUA,CAAA,EAAkB;IAChC,MAAMrB,UAAU,GAAGX,YAAY,CAACS,WAAW,CAACC,GAAG,CAAC,IAAI,CAACP,kBAAkB,CAAC;IACxE,IAAIQ,UAAU,EAAE;MACd,IAAI;QACF;QACA,MAAMA,UAAU,CAACqB,UAAU,CAAC,CAAC;QAC7B,IAAI,CAAC9B,OAAO,CAACY,IAAI,CAAC,iCAAiC,IAAI,CAACT,aAAa,CAAC,CAAC,GAAG,CAAC;MAC7E,CAAC,CAAC,OAAOmB,KAAK,EAAE;QACd,IAAI,CAACtB,OAAO,CAACsB,KAAK,CAAC,wCAAwC,IAAI,CAACnB,aAAa,CAAC,CAAC,GAAG,EAAEmB,KAAK,CAAC;MAC5F,CAAC,SAAS;QACR;QACAxB,YAAY,CAACS,WAAW,CAACwB,MAAM,CAAC,IAAI,CAAC9B,kBAAkB,CAAC;MAC1D;IACF;EACF;AACF;AAAC+B,OAAA,CAAAlC,YAAA,GAAAA,YAAA;AArFqBA,YAAY,CACfS,WAAW,GAAmC,IAAI0B,GAAG,CAAC,CAAC","ignoreList":[]}
|
|
@@ -13,7 +13,6 @@ export let AzureSecretKeysEnum = /*#__PURE__*/function (AzureSecretKeysEnum) {
|
|
|
13
13
|
// in-use,
|
|
14
14
|
AzureSecretKeysEnum["DB_CONNECTING_STRING_AUTH"] = "DB-CONNECTION-STRING-AUTH";
|
|
15
15
|
AzureSecretKeysEnum["DB_CONNECTING_STRING_USER"] = "DB-CONNECTION-STRING-USER";
|
|
16
|
-
AzureSecretKeysEnum["DB_CONNECTING_STRING_TENANT_BRIDGE"] = "DB-Connecting-String-Tenant-Bridge";
|
|
17
16
|
AzureSecretKeysEnum["DB_CONNECTING_STRING_PAYMENT"] = "DB-CONNECTION-STRING-PAYMENT";
|
|
18
17
|
AzureSecretKeysEnum["DB_CONNECTING_STRING_CORE"] = "DB-CONNECTION-STRING-CORE";
|
|
19
18
|
AzureSecretKeysEnum["DB_CONNECTING_STRING_BILLING"] = "DB-CONNECTION-STRING-BILLING";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"secretKeys.enum.js","names":["AzureSecretKeysEnum"],"sources":["../../../src/enums/secretKeys.enum.ts"],"sourcesContent":["// Enum for secret keys\nexport enum AzureSecretKeysEnum {\n KEYCLOAK_ADMIN_CLIENT_SECRET = \"KEYCLOAK-ADMIN-CLIENT-SECRET\",\n KEYCLOAK_ADMIN_CLIENT_ID = \"KEYCLOAK-ADMIN-CLIENT-ID\",\n KEYCLOAK_BASE_URL = \"KEYCLOAK-BASE-URL\",\n STRIPE_PAYMENT_WEBHOOK_SECRET_KEY = \"Stripe-payment-webhook-secret-key\", // in-use\n STRIPE_PRODUCT_WEBHOOK_SECRET = \"Stripe-product-webhook-secret-key\", // in-use\n STRIPE_PRICE_WEBHOOK_SECRET = \"Stripe-price-webhook-secret-key\", // in-use\n EMAIL_SERVICE_URL = \"Email-Service-Url\", // in-use,\n DB_CONNECTING_STRING_AUTH = \"DB-CONNECTION-STRING-AUTH\",\n DB_CONNECTING_STRING_USER = \"DB-CONNECTION-STRING-USER\",\n
|
|
1
|
+
{"version":3,"file":"secretKeys.enum.js","names":["AzureSecretKeysEnum"],"sources":["../../../src/enums/secretKeys.enum.ts"],"sourcesContent":["// Enum for secret keys\nexport enum AzureSecretKeysEnum {\n KEYCLOAK_ADMIN_CLIENT_SECRET = \"KEYCLOAK-ADMIN-CLIENT-SECRET\",\n KEYCLOAK_ADMIN_CLIENT_ID = \"KEYCLOAK-ADMIN-CLIENT-ID\",\n KEYCLOAK_BASE_URL = \"KEYCLOAK-BASE-URL\",\n STRIPE_PAYMENT_WEBHOOK_SECRET_KEY = \"Stripe-payment-webhook-secret-key\", // in-use\n STRIPE_PRODUCT_WEBHOOK_SECRET = \"Stripe-product-webhook-secret-key\", // in-use\n STRIPE_PRICE_WEBHOOK_SECRET = \"Stripe-price-webhook-secret-key\", // in-use\n EMAIL_SERVICE_URL = \"Email-Service-Url\", // in-use,\n DB_CONNECTING_STRING_AUTH = \"DB-CONNECTION-STRING-AUTH\",\n DB_CONNECTING_STRING_USER = \"DB-CONNECTION-STRING-USER\",\n DB_CONNECTING_STRING_PAYMENT = \"DB-CONNECTION-STRING-PAYMENT\",\n DB_CONNECTING_STRING_CORE = \"DB-CONNECTION-STRING-CORE\",\n DB_CONNECTING_STRING_BILLING = \"DB-CONNECTION-STRING-BILLING\",\n DB_CONNECTING_STRING_STAGING = \"DB-CONNECTION-STRING-STAGING\",\n DB_CONNECTING_STRING_BNT_DEV = \"DB-CONNECTION-STRING-BNT-DEV\",\n DB_CONNECTION_STRING_TENANT_BRIDGE = \"DB-CONNECTION-STRING-TENANT-BRIDGE\",\n SERVICE_BUS_CONNECTION_STRING = \"servicebus-connection-string\",\n STRIPE_CUSTOMER_SYNC_WEBHOOK_SECRET = \"stripe-customer-sync-webhook-secret-key\",\n STRIPE_INVOICE_SYNC_WEBHOOK_SECRET = \"stripe-invoice-sync-webhook-secret-key\",\n STRIPE_PRODUCT_SYNC_WEBHOOK_SECRET = \"stripe-product-sync-webhook-secret-key\",\n STRIPE_PRICE_SYNC_WEBHOOK_SECRET = \"stripe-price-sync-webhook-secret-key\",\n STRIPE_SECRET_KEY = \"Stripe-secret-key\",\n STRIPE_WEBHOOK_CUSTOMER_CREATED_SECRET_KEY = \"Stripe-Webhook-Customer-Created-Secret-Key\",\n STRIPE_SUBSCRIPTION_SYNC_WEBHOOK_SECRET = \"stripe-subscription-sync-webhook-secret-key\",\n FIREBASE_SERVICE_ACCOUNTS_VARIABLE = \"firebase_service_accounts_variable\",\n HMS_ACCESS_KEY=\"MEETING-HMS-ACCESS-KEY-APP-SECRET\",\n MEETING_ROOM_APP_SECRET=\"MEETING-ROOM-APP-SECRET\",\n BASE_DB_CLUSTER_CONNECTING_STRING_CHAT = \"BASE-DB-CLUSTER-CONNECTING-STRING-CHAT\",\n AUTH_SERVICE_AUTHENTICATION_URL = \"AUTH-SERVICE-AUTHENTICATION-URL\",\n GCP_PROJECT_ID=\"gcp-project-id\",\n PUBSUB_SERVICE_ACCOUNT_KEYS=\"pubsub-service-account-keys\",\n VAPI_TOKEN = \"vapi-token\",\n GITHUB_TOKEN = \"GITHUB-TOKEN\",\n GITHUB_WORKFLOW_URL = \"GITHUB-WORKFLOW-URL\",\n DB_CONNECTION_STRING_ENCRYPTION_KEY = \"DB-CONNECTION-STRING-ENCRYPTION-KEY\",\n}\n\n// AUTH-SERVICE-AUTHENTICATION-URL\n// https://culturefy-auth-staging.azurewebsites.net/api/verify\n\n// REFRESH-SESSION-URL"],"mappings":"AAAA;AACA,WAAYA,mBAAmB,0BAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAI4C;EAJ/DA,mBAAmB;EAKwC;EAL3DA,mBAAmB;EAMoC;EANvDA,mBAAmB;EAOY;EAP/BA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAnBA,mBAAmB;EAAA,OAAnBA,mBAAmB;AAAA;;AAqC/B;AACA;;AAEA","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"user.js","names":[],"sources":["../../../src/interfaces/user.ts"],"sourcesContent":["export interface ICreateUser {\n userId: string;\n email: string;\n businessId: string;\n}"],"mappings":"","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"user.js","names":[],"sources":["../../../src/interfaces/user.ts"],"sourcesContent":["export interface ICreateUser {\n userId: string;\n email: string;\n businessId: string;\n}\n"],"mappings":"","ignoreList":[]}
|
|
@@ -16,6 +16,7 @@ function pickCookieDomain(appConfig, origin, requestUrl) {
|
|
|
16
16
|
var _appConfig$cookie$dom;
|
|
17
17
|
return (_appConfig$cookie$dom = appConfig.cookie.domain.local) != null ? _appConfig$cookie$dom : undefined;
|
|
18
18
|
}
|
|
19
|
+
// culturefy.app domains
|
|
19
20
|
if (host.endsWith(".dev.culturefy.app") || host === "dev.culturefy.app") {
|
|
20
21
|
return appConfig.cookie.domain.dev;
|
|
21
22
|
}
|
|
@@ -25,6 +26,16 @@ function pickCookieDomain(appConfig, origin, requestUrl) {
|
|
|
25
26
|
if (host.endsWith(".culturefy.app")) {
|
|
26
27
|
return appConfig.cookie.domain.prod;
|
|
27
28
|
}
|
|
29
|
+
// consultex.app domains
|
|
30
|
+
if (host.endsWith(".dev.consultex.app") || host === "dev.consultex.app") {
|
|
31
|
+
return appConfig.cookie.domain.dev;
|
|
32
|
+
}
|
|
33
|
+
if (host.endsWith(".staging.consultex.app") || host === "staging.consultex.app") {
|
|
34
|
+
return appConfig.cookie.domain.staging;
|
|
35
|
+
}
|
|
36
|
+
if (host.endsWith(".consultex.app")) {
|
|
37
|
+
return appConfig.cookie.domain.prod;
|
|
38
|
+
}
|
|
28
39
|
} catch (_unused) {
|
|
29
40
|
return undefined;
|
|
30
41
|
}
|
|
@@ -40,8 +51,24 @@ const parseCookieHeader = header => {
|
|
|
40
51
|
}
|
|
41
52
|
return out;
|
|
42
53
|
};
|
|
54
|
+
function isLocalRequest(origin, requestUrl) {
|
|
55
|
+
const hostCandidate = origin != null ? origin : requestUrl;
|
|
56
|
+
if (!hostCandidate) return false;
|
|
57
|
+
try {
|
|
58
|
+
const host = new URL(hostCandidate).hostname;
|
|
59
|
+
return host === "localhost" || host.startsWith("127.0.0.1");
|
|
60
|
+
} catch (_unused2) {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function getSessionMappingCookieName(appId, origin, requestUrl) {
|
|
65
|
+
if (isLocalRequest(origin, requestUrl)) {
|
|
66
|
+
return `session-v1.${appId}.mapping`;
|
|
67
|
+
}
|
|
68
|
+
return `__Secure-session-v1.${appId}.mapping`;
|
|
69
|
+
}
|
|
43
70
|
export const verifyMw = async (req, ctx, next) => {
|
|
44
|
-
var _APP_MAP$appId, _p, _ref, _ref$state, _ref2, _tokenMapping$userId$, _tokenMapping$userId, _ref3, _p$sub, _ref4, _p$cfy_bid, _ref5, _p$email, _p$name, _ref6, _p$resource_access$
|
|
71
|
+
var _APP_MAP$appId, _req$headers$get, _p, _ref, _ref$state, _ref2, _tokenMapping$userId$, _tokenMapping$userId, _ref3, _p$sub, _ref4, _p$cfy_bid, _ref5, _p$email, _p$name, _ref6, _p$resource_access$to, _p$resource_access, _p$realm_access;
|
|
45
72
|
const appId = req.headers.get("app-id");
|
|
46
73
|
if (!appId || !(APP_MAP != null && (_APP_MAP$appId = APP_MAP[appId]) != null && _APP_MAP$appId.clientId)) {
|
|
47
74
|
return {
|
|
@@ -58,11 +85,12 @@ export const verifyMw = async (req, ctx, next) => {
|
|
|
58
85
|
})
|
|
59
86
|
};
|
|
60
87
|
}
|
|
61
|
-
const
|
|
88
|
+
const clientId = APP_MAP[appId].clientId;
|
|
62
89
|
|
|
63
90
|
// cookies
|
|
64
91
|
const cookies = parseCookieHeader(req.headers.get("cookie"));
|
|
65
|
-
|
|
92
|
+
const requestOrigin = (_req$headers$get = req.headers.get("origin")) != null ? _req$headers$get : undefined;
|
|
93
|
+
let mapping = cookies[getSessionMappingCookieName(appId, requestOrigin, req.url)] || cookies[`__Secure-session-v1.${appId}.mapping`] || cookies[`session-v1.${appId}.mapping`] || req.headers.get("x-session-mapping") || req.headers.get("x-token-mapping");
|
|
66
94
|
if (!mapping) {
|
|
67
95
|
return {
|
|
68
96
|
status: 401,
|
|
@@ -151,13 +179,28 @@ export const verifyMw = async (req, ctx, next) => {
|
|
|
151
179
|
};
|
|
152
180
|
}
|
|
153
181
|
const realm = tokenMapping.realmId;
|
|
154
|
-
const
|
|
182
|
+
const tokenClientId = tokenMapping.clientId;
|
|
183
|
+
if (!tokenClientId || tokenClientId !== clientId) {
|
|
184
|
+
return {
|
|
185
|
+
status: 403,
|
|
186
|
+
headers: {
|
|
187
|
+
"Content-Type": "application/json",
|
|
188
|
+
"Cache-Control": "no-store, no-cache, must-revalidate",
|
|
189
|
+
"Pragma": "no-cache",
|
|
190
|
+
"Vary": "Origin"
|
|
191
|
+
},
|
|
192
|
+
body: JSON.stringify({
|
|
193
|
+
status: "forbidden",
|
|
194
|
+
reason: "client_mismatch"
|
|
195
|
+
})
|
|
196
|
+
};
|
|
197
|
+
}
|
|
155
198
|
|
|
156
199
|
// decode/verify (lightweight; replace with your verifyJsonWebToken if you have it)
|
|
157
200
|
let p;
|
|
158
201
|
try {
|
|
159
202
|
p = jwtDecode(at);
|
|
160
|
-
} catch (
|
|
203
|
+
} catch (_unused3) {
|
|
161
204
|
return {
|
|
162
205
|
status: 401,
|
|
163
206
|
headers: {
|
|
@@ -191,11 +234,11 @@ export const verifyMw = async (req, ctx, next) => {
|
|
|
191
234
|
// Refresh only when expired
|
|
192
235
|
if (typeof p.exp === "number" && p.exp <= now) {
|
|
193
236
|
// Delegate to refresh helper; it will handle setting cookies/state or returning an error
|
|
194
|
-
return await getNewRefreshToken(req, ctx, appId, realm,
|
|
237
|
+
return await getNewRefreshToken(req, ctx, appId, realm, tokenClientId, rt, mapping, p, next);
|
|
195
238
|
}
|
|
196
239
|
|
|
197
240
|
// audience checks
|
|
198
|
-
const audOk = Array.isArray(p.aud) && p.aud.includes(
|
|
241
|
+
const audOk = Array.isArray(p.aud) && p.aud.includes(tokenClientId) || typeof p.aud === "string" && (p.aud === tokenClientId || p.aud === "account") || p.azp === tokenClientId;
|
|
199
242
|
if (!audOk) {
|
|
200
243
|
return {
|
|
201
244
|
status: 403,
|
|
@@ -223,7 +266,7 @@ export const verifyMw = async (req, ctx, next) => {
|
|
|
223
266
|
tenantId,
|
|
224
267
|
email: (_ref5 = (_p$email = p.email) != null ? _p$email : p.preferred_username) != null ? _ref5 : null,
|
|
225
268
|
name: (_p$name = p.name) != null ? _p$name : undefined,
|
|
226
|
-
roles: (_ref6 = (_p$resource_access$
|
|
269
|
+
roles: (_ref6 = (_p$resource_access$to = (_p$resource_access = p.resource_access) == null || (_p$resource_access = _p$resource_access[tokenClientId]) == null ? void 0 : _p$resource_access.roles) != null ? _p$resource_access$to : (_p$realm_access = p.realm_access) == null ? void 0 : _p$realm_access.roles) != null ? _ref6 : [],
|
|
227
270
|
exp: p.exp
|
|
228
271
|
};
|
|
229
272
|
return next();
|
|
@@ -245,15 +288,31 @@ async function getNewRefreshToken(req, ctx, appId, realmId, clientId, rt, mappin
|
|
|
245
288
|
})
|
|
246
289
|
};
|
|
247
290
|
}
|
|
248
|
-
ctx.info("
|
|
291
|
+
ctx.info("Refreshing session token", {
|
|
249
292
|
realmId,
|
|
250
|
-
clientId
|
|
251
|
-
rt
|
|
293
|
+
clientId
|
|
252
294
|
});
|
|
253
295
|
|
|
254
296
|
// Call auth service to refresh
|
|
255
297
|
try {
|
|
256
|
-
var _req$headers$
|
|
298
|
+
var _req$headers$get2, _ref7, _ref7$state, _ref8, _updatedMapping$userI, _updatedMapping$userI2, _ref9, _p2$sub, _ref0, _p2$cfy_bid, _ref1, _p2$email, _p2$name, _ref10, _p2$resource_access$c, _p2$resource_access, _p2$realm_access;
|
|
299
|
+
if (!apiURL) {
|
|
300
|
+
ctx.error == null || ctx.error("Refresh session URL is not configured");
|
|
301
|
+
return {
|
|
302
|
+
status: 401,
|
|
303
|
+
headers: {
|
|
304
|
+
"Content-Type": "application/json",
|
|
305
|
+
"Cache-Control": "no-store, no-cache, must-revalidate",
|
|
306
|
+
"Pragma": "no-cache",
|
|
307
|
+
"Vary": "Origin"
|
|
308
|
+
},
|
|
309
|
+
body: JSON.stringify({
|
|
310
|
+
status: "unauthenticated",
|
|
311
|
+
reason: "refresh_not_configured"
|
|
312
|
+
})
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
const requestOrigin = (_req$headers$get2 = req.headers.get("origin")) != null ? _req$headers$get2 : undefined;
|
|
257
316
|
const resp = await fetch(apiURL, {
|
|
258
317
|
method: "POST",
|
|
259
318
|
headers: {
|
|
@@ -266,8 +325,7 @@ async function getNewRefreshToken(req, ctx, appId, realmId, clientId, rt, mappin
|
|
|
266
325
|
})
|
|
267
326
|
});
|
|
268
327
|
if (!resp.ok) {
|
|
269
|
-
|
|
270
|
-
ctx.warn == null || ctx.warn(`refresh call failed: ${resp.status} ${text}`);
|
|
328
|
+
ctx.warn == null || ctx.warn(`refresh call failed with status ${resp.status}`);
|
|
271
329
|
return {
|
|
272
330
|
status: 401,
|
|
273
331
|
headers: {
|
|
@@ -333,12 +391,15 @@ async function getNewRefreshToken(req, ctx, appId, realmId, clientId, rt, mappin
|
|
|
333
391
|
|
|
334
392
|
const mappingCookieValue = Buffer.from(mapping).toString("base64");
|
|
335
393
|
const appConfig = APP_MAP[appId];
|
|
336
|
-
|
|
337
|
-
|
|
394
|
+
|
|
395
|
+
// 5
|
|
396
|
+
const mappedDomain = pickCookieDomain(appConfig, requestOrigin, req.url);
|
|
397
|
+
const localRequest = isLocalRequest(requestOrigin, req.url);
|
|
398
|
+
setCookieKV(ctx, getSessionMappingCookieName(appId, requestOrigin, req.url), mappingCookieValue, {
|
|
338
399
|
// mapping must be readable by FE in your flow; keep httpOnly default if you prefer server-only
|
|
339
400
|
httpOnly: false,
|
|
340
|
-
secure:
|
|
341
|
-
sameSite: "None",
|
|
401
|
+
secure: !localRequest,
|
|
402
|
+
sameSite: localRequest ? "Lax" : "None",
|
|
342
403
|
maxAge: mappingMaxAge,
|
|
343
404
|
domain: mappedDomain
|
|
344
405
|
});
|
|
@@ -347,7 +408,7 @@ async function getNewRefreshToken(req, ctx, appId, realmId, clientId, rt, mappin
|
|
|
347
408
|
let p2;
|
|
348
409
|
try {
|
|
349
410
|
p2 = jwtDecode(newAT);
|
|
350
|
-
} catch (
|
|
411
|
+
} catch (_unused4) {
|
|
351
412
|
return {
|
|
352
413
|
status: 401,
|
|
353
414
|
headers: {
|
|
@@ -397,7 +458,11 @@ async function getNewRefreshToken(req, ctx, appId, realmId, clientId, rt, mappin
|
|
|
397
458
|
// Continue pipeline after refresh
|
|
398
459
|
return next();
|
|
399
460
|
} catch (e) {
|
|
400
|
-
ctx.error == null || ctx.error("refresh exception",
|
|
461
|
+
ctx.error == null || ctx.error("refresh exception", {
|
|
462
|
+
message: e == null ? void 0 : e.message,
|
|
463
|
+
name: e == null ? void 0 : e.name,
|
|
464
|
+
code: e == null ? void 0 : e.code
|
|
465
|
+
});
|
|
401
466
|
return {
|
|
402
467
|
status: 401,
|
|
403
468
|
headers: {
|