@culturefy/shared 1.0.63 → 1.0.65
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 +72 -18
- package/build/cjs/middlewares/verify-middleware.js.map +1 -1
- package/build/cjs/repositories/multi-tenant.repository.js +82 -34
- 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 +74 -20
- package/build/esm/middlewares/verify-middleware.js.map +1 -1
- package/build/esm/repositories/multi-tenant.repository.js +82 -34
- 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 +79 -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 +83 -34
- 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","_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","Error","getOrCreateCachedConnection","existing","connections","connection","readyState","dbLabel","info","mongoose","Mongoose","connect","serverSelectionTimeoutMS","connectTimeoutMS","socketTimeoutMS","err","message","name","code","stack","toObjectId","id","fieldName","Types","ObjectId","isValid","getTenantBridgeSrvDbConnectionString","envKey","localUri","undefined","vault","AZURE_KEY_VAULT_NAME","secretKey","dbUrl","getAzureVaultSecretByKey","getDbConnectionEncryptionKey","DB_CONNECTION_STRING_ENCRYPTION_KEY","decryptConnectionString","encryptedValue","startsWith","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 this.context.error(`${label} must be 16 bytes for aes-128-cbc (got ${utf8Value.length})`);\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 try {\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 const key = await getAzureVaultSecretByKey(\n this.context, vault, AzureSecretKeysEnum.DB_CONNECTION_STRING_ENCRYPTION_KEY\n );\n if (!key) {\n this.context.error(\"DB connection string encryption key not found in vault\");\n throw new Error(\"DB connection string encryption key not found in vault\");\n }\n this.dbConnectionEncryptionKey = key;\n return key;\n } catch (error) {\n this.context.error(`Error getting DB connection string encryption key from vault: ${error}`);\n throw new Error(`Error getting DB connection string encryption key from vault: ${error}`);\n }\n }\n\n private async decryptConnectionString(encryptedValue: string): Promise<string> {\n if (!encryptedValue) {\n this.context.error(\"Encrypted value not found\");\n throw new Error(\"Encrypted value not found\");\n }\n\n if (encryptedValue.startsWith(\"mongodb://\")) {\n return encryptedValue;\n }\n\n const key = await this.getDbConnectionEncryptionKey();\n if (!key) {\n this.context.error(\"DB connection string encryption key not found during decryption\");\n throw new Error(\"DB connection string encryption key not found during decryption\");\n }\n this.context.info(`Decrypting DB connection string with key: ${key}`);\n\n const keyBuffer = this.normalizeEncryptionKey(key);\n if (!keyBuffer) {\n this.context.error(\"Key buffer not found\");\n throw new Error(\"Key buffer not found\");\n }\n this.context.info(`Decrypting DB connection string with key buffer: ${keyBuffer}`);\n\n const ivBuffer = this.getEncryptionIv();\n if (!ivBuffer) {\n this.context.error(\"IV buffer not found\");\n throw new Error(\"IV buffer not found\");\n }\n this.context.info(`Decrypting DB connection string with IV buffer: ${ivBuffer}`);\n\n const decipher = crypto.createDecipheriv(\"aes-128-cbc\", keyBuffer, ivBuffer);\n if (!decipher) {\n this.context.error(\"Decipher not found\");\n throw new Error(\"Decipher not found\");\n }\n this.context.info(`Decrypting DB connection string with decipher: ${decipher}`);\n\n let decrypted = decipher.update(encryptedValue, \"base64\", \"utf8\");\n if (!decrypted) {\n this.context.error(\"Decrypted value not found\");\n throw new Error(\"Decrypted value not found\");\n }\n this.context.info(`Decrypting DB connection string with decrypted value: ${decrypted}`);\n\n decrypted += decipher.final(\"utf8\");\n if (!decrypted) {\n this.context.error(\"Decrypted value not found\");\n throw new Error(\"Decrypted value not found\");\n }\n this.context.info(`Decrypting DB connection string with decrypted value: ${decrypted}`);\n\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 this.context.error(`DB connection string encryption key must be 16 bytes for aes-128-cbc (got ${utf8Key.length})`);\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);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,GAAAjJ,yBAAA,CAAArB,MAAA,CAAAsK,SAAA,mCAAAxK,KAAA,GAAAoB,MAAA,CAAAE,wBAAA,CAAApB,MAAA,CAAAsK,SAAA,mCAAAtK,MAAA,CAAAsK,SAAA,GAAAjJ,yBAAA,CAAArB,MAAA,CAAAsK,SAAA,kCAAAvK,KAAA,GAAAmB,MAAA,CAAAE,wBAAA,CAAApB,MAAA,CAAAsK,SAAA,kCAAAtK,MAAA,CAAAsK,SAAA,GAAAtK,MAAA;AAoYhD,MAAeuK,qBAAqB,SAAYzH,qBAAqB,CAAC;EAAAW,YAAA,GAAAd,IAAA;IAAA,SAAAA,IAAA;IAAA,KAC/C6H,QAAQ;EAAA;EAEpC,IAAcC,OAAOA,CAAA,EAAa;IAChC,OAAO,IAAI,CAACN,KAAK,CAAC,IAAI,CAACK,QAAQ,CAAC;EAClC;AACF;AAACzH,OAAA,CAAAwH,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,CAAA,IAAAK,CAAA,CAAAL,CAAA,IAAAG,CAAA,CAAAH,CAAA,OAAAK,CAAA,CAAAI,UAAA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,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.delete(this.dbConnectionString);\n }\n }\n }\n}\n"],"mappings":";;;;;AAAA,IAAAA,SAAA,GAAAC,sBAAA,C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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":[]}
|
|
@@ -51,8 +51,24 @@ const parseCookieHeader = header => {
|
|
|
51
51
|
}
|
|
52
52
|
return out;
|
|
53
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
|
+
}
|
|
54
70
|
export const verifyMw = async (req, ctx, next) => {
|
|
55
|
-
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;
|
|
56
72
|
const appId = req.headers.get("app-id");
|
|
57
73
|
if (!appId || !(APP_MAP != null && (_APP_MAP$appId = APP_MAP[appId]) != null && _APP_MAP$appId.clientId)) {
|
|
58
74
|
return {
|
|
@@ -69,11 +85,12 @@ export const verifyMw = async (req, ctx, next) => {
|
|
|
69
85
|
})
|
|
70
86
|
};
|
|
71
87
|
}
|
|
72
|
-
const
|
|
88
|
+
const clientId = APP_MAP[appId].clientId;
|
|
73
89
|
|
|
74
90
|
// cookies
|
|
75
91
|
const cookies = parseCookieHeader(req.headers.get("cookie"));
|
|
76
|
-
|
|
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");
|
|
77
94
|
if (!mapping) {
|
|
78
95
|
return {
|
|
79
96
|
status: 401,
|
|
@@ -162,13 +179,28 @@ export const verifyMw = async (req, ctx, next) => {
|
|
|
162
179
|
};
|
|
163
180
|
}
|
|
164
181
|
const realm = tokenMapping.realmId;
|
|
165
|
-
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
|
+
}
|
|
166
198
|
|
|
167
199
|
// decode/verify (lightweight; replace with your verifyJsonWebToken if you have it)
|
|
168
200
|
let p;
|
|
169
201
|
try {
|
|
170
202
|
p = jwtDecode(at);
|
|
171
|
-
} catch (
|
|
203
|
+
} catch (_unused3) {
|
|
172
204
|
return {
|
|
173
205
|
status: 401,
|
|
174
206
|
headers: {
|
|
@@ -202,11 +234,11 @@ export const verifyMw = async (req, ctx, next) => {
|
|
|
202
234
|
// Refresh only when expired
|
|
203
235
|
if (typeof p.exp === "number" && p.exp <= now) {
|
|
204
236
|
// Delegate to refresh helper; it will handle setting cookies/state or returning an error
|
|
205
|
-
return await getNewRefreshToken(req, ctx, appId, realm,
|
|
237
|
+
return await getNewRefreshToken(req, ctx, appId, realm, tokenClientId, rt, mapping, p, next);
|
|
206
238
|
}
|
|
207
239
|
|
|
208
240
|
// audience checks
|
|
209
|
-
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;
|
|
210
242
|
if (!audOk) {
|
|
211
243
|
return {
|
|
212
244
|
status: 403,
|
|
@@ -234,7 +266,7 @@ export const verifyMw = async (req, ctx, next) => {
|
|
|
234
266
|
tenantId,
|
|
235
267
|
email: (_ref5 = (_p$email = p.email) != null ? _p$email : p.preferred_username) != null ? _ref5 : null,
|
|
236
268
|
name: (_p$name = p.name) != null ? _p$name : undefined,
|
|
237
|
-
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 : [],
|
|
238
270
|
exp: p.exp
|
|
239
271
|
};
|
|
240
272
|
return next();
|
|
@@ -256,15 +288,31 @@ async function getNewRefreshToken(req, ctx, appId, realmId, clientId, rt, mappin
|
|
|
256
288
|
})
|
|
257
289
|
};
|
|
258
290
|
}
|
|
259
|
-
ctx.info("
|
|
291
|
+
ctx.info("Refreshing session token", {
|
|
260
292
|
realmId,
|
|
261
|
-
clientId
|
|
262
|
-
rt
|
|
293
|
+
clientId
|
|
263
294
|
});
|
|
264
295
|
|
|
265
296
|
// Call auth service to refresh
|
|
266
297
|
try {
|
|
267
|
-
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;
|
|
268
316
|
const resp = await fetch(apiURL, {
|
|
269
317
|
method: "POST",
|
|
270
318
|
headers: {
|
|
@@ -277,8 +325,7 @@ async function getNewRefreshToken(req, ctx, appId, realmId, clientId, rt, mappin
|
|
|
277
325
|
})
|
|
278
326
|
});
|
|
279
327
|
if (!resp.ok) {
|
|
280
|
-
|
|
281
|
-
ctx.warn == null || ctx.warn(`refresh call failed: ${resp.status} ${text}`);
|
|
328
|
+
ctx.warn == null || ctx.warn(`refresh call failed with status ${resp.status}`);
|
|
282
329
|
return {
|
|
283
330
|
status: 401,
|
|
284
331
|
headers: {
|
|
@@ -344,12 +391,15 @@ async function getNewRefreshToken(req, ctx, appId, realmId, clientId, rt, mappin
|
|
|
344
391
|
|
|
345
392
|
const mappingCookieValue = Buffer.from(mapping).toString("base64");
|
|
346
393
|
const appConfig = APP_MAP[appId];
|
|
347
|
-
|
|
348
|
-
|
|
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, {
|
|
349
399
|
// mapping must be readable by FE in your flow; keep httpOnly default if you prefer server-only
|
|
350
400
|
httpOnly: false,
|
|
351
|
-
secure:
|
|
352
|
-
sameSite: "None",
|
|
401
|
+
secure: !localRequest,
|
|
402
|
+
sameSite: localRequest ? "Lax" : "None",
|
|
353
403
|
maxAge: mappingMaxAge,
|
|
354
404
|
domain: mappedDomain
|
|
355
405
|
});
|
|
@@ -358,7 +408,7 @@ async function getNewRefreshToken(req, ctx, appId, realmId, clientId, rt, mappin
|
|
|
358
408
|
let p2;
|
|
359
409
|
try {
|
|
360
410
|
p2 = jwtDecode(newAT);
|
|
361
|
-
} catch (
|
|
411
|
+
} catch (_unused4) {
|
|
362
412
|
return {
|
|
363
413
|
status: 401,
|
|
364
414
|
headers: {
|
|
@@ -408,7 +458,11 @@ async function getNewRefreshToken(req, ctx, appId, realmId, clientId, rt, mappin
|
|
|
408
458
|
// Continue pipeline after refresh
|
|
409
459
|
return next();
|
|
410
460
|
} catch (e) {
|
|
411
|
-
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
|
+
});
|
|
412
466
|
return {
|
|
413
467
|
status: 401,
|
|
414
468
|
headers: {
|