@c-rex/core 0.1.12 → 0.1.13

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/api/OIDC.ts","../../../constants/src/index.ts","../../src/OIDC.ts","../../src/config.ts","../../src/logger.ts","../../src/transports/matomo.ts","../../src/transports/graylog.ts","../../src/utils.ts","../../src/sdk.ts"],"sourcesContent":["import { NextResponse } from 'next/server';\nimport { CREX_TOKEN_HEADER_KEY } from '@c-rex/constants';\nimport { getIssuerMetadata, getToken } from '../OIDC';\nimport { CrexSDK } from '../sdk';\n\n/**\n * Retrieves an access token using client credentials flow from the configured OIDC provider\n * \n * @returns NextResponse with success status or error message\n * @throws Error if token retrieval fails\n */\nexport const getTokenMethod = async (): Promise<NextResponse> => {\n try {\n const { token, expiresAt, error } = await getToken();\n\n if (error) {\n return NextResponse.json({ error }, { status: 500 });\n }\n\n const response = NextResponse.json({ token: token });\n\n response.cookies.set({\n name: CREX_TOKEN_HEADER_KEY,\n value: token,\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n expires: expiresAt ? new Date(expiresAt * 1000) : undefined\n });\n\n return response;\n\n } catch (error) {\n return NextResponse.json({ error: String(error) }, { status: 500 });\n }\n}\n\nexport const discoverIssuerMethod = async (): Promise<NextResponse> => {\n try {\n const metadata = await getIssuerMetadata();\n const sdk = new CrexSDK();\n const config = sdk.getServerConfig();\n sdk.updateConfigProp('OIDC', {\n ...config.OIDC,\n issuerMetadata: metadata\n });\n\n const response = NextResponse.json({ issuerMetadata: metadata });\n\n return response;\n\n } catch (error) {\n return NextResponse.json({ error: String(error) }, { status: 500 });\n }\n}\n","export const ALL = \"*\"\n\nexport const LOG_CATEGORIES = [\n \"NoLicense\",\n \"Scenario\",\n \"Favorites\",\n \"Subscription\",\n \"Share\",\n \"Document\",\n \"Search\",\n \"History\",\n \"Notification\",\n \"UserProfile\",\n] as const;\n\nexport const LOG_LEVELS = {\n critical: 2,\n error: 3,\n warning: 4,\n info: 6,\n debug: 7,\n} as const;\n\nexport const RESULT_VIEW_STYLES = [\n \"cards\",\n \"table\",\n \"table-with-images\",\n] as const;\n\nexport const API = {\n MAX_RETRY: 3,\n API_TIMEOUT: 10000,\n RETRY_DELAY: 500,\n API_HEADERS: {\n \"content-Type\": \"application/json\",\n },\n};\n\nexport const SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport const CONTENT_LANG_KEY = \"CONTENT_LANG_KEY\";\n\nexport const AVAILABLE_CONTENT_LANG_KEY = \"AVAILABLE_CONTENT_LANG_KEY\";\n\nexport const UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_LANG = \"en-US\";\n\nexport const EN_LANG = \"en\";\n\nexport const UI_LANG_OPTIONS = [\"en-us\", \"de-de\"];\n\nexport const TOPICS_TYPE_AND_LINK = \"topics\";\nexport const BLOG_TYPE_AND_LINK = \"blog\";\nexport const DOCUMENTS_TYPE_AND_LINK = \"documents\";\n\nexport const TOPIC = \"TOPIC\";\nexport const DOCUMENT = \"DOCUMENT\";\nexport const PACKAGE = \"PACKAGE\";\nexport const FRAGMENT = \"FRAGMENT\";\n\nexport const RESULT_TYPES = {\n TOPIC: TOPIC,\n DOCUMENT: DOCUMENT,\n PACKAGE: PACKAGE,\n FRAGMENT: FRAGMENT\n} as const;\n\nexport const FILES_EXTENSIONS = {\n PDF: \"application/pdf\",\n HTML: \"text/html\",\n} as const;\n\nexport const DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1000; // 30 days in milliseconds\n\nexport const ICONS_BY_FILE_EXTENSION = {\n \"application/pdf\": \"FaFilePdf\",\n} as const;\n\nexport const DEFAULT_ICON = \"file\";\n\nexport const CREX_TOKEN_HEADER_KEY = \"crex-token\";\n\nexport const WILD_CARD_OPTIONS = {\n BOTH: \"BOTH\",\n END: \"END\",\n START: \"START\",\n NONE: \"NONE\",\n} as const;\n\nexport const OPERATOR_OPTIONS = {\n AND: \"AND\",\n OR: \"OR\",\n} as const;\n\nexport const ARTICLE_PAGE_LAYOUT = {\n BLOG: \"BLOG\",\n DOCUMENT: \"DOCUMENT\",\n} as const;\n\nexport const DEVICE_OPTIONS = {\n MOBILE: \"mobile\",\n TABLET: \"tablet\",\n DESKTOP: \"desktop\",\n}\nexport const BREAKPOINTS = {\n sm: 640,\n md: 768,\n lg: 1024,\n xl: 1280,\n \"2xl\": 1536,\n};\n\nexport const MARKER_COLORS = [\n \"red-500\",\n \"orange-500\",\n \"yellow-400\",\n \"green-500\",\n \"teal-500\",\n \"blue-500\",\n \"sky-500\",\n \"purple-500\",\n \"pink-500\",\n \"gray-500\",\n \"neutral-800\",\n \"cyan-500\",\n \"lime-500\",\n \"amber-500\",\n \"indigo-500\",\n];","import { Issuer } from 'openid-client';\nimport { getServerConfig } from './config';\nimport { CrexLogger } from './logger';\nimport { CrexSDK } from './sdk';\n\n/**\n * Retrieves an access token using client credentials flow from the configured OIDC provider\n * \n * @returns NextResponse with success status or error message\n * @throws Error if token retrieval fails\n */\nexport const getToken = async (): Promise<{ token: string; expiresAt: number; error?: string }> => {\n try {\n const config = getServerConfig();\n const issuer = await Issuer.discover(config.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: config.OIDC.client.id,\n client_secret: config.OIDC.client.secret,\n });\n const tokenSet = await client.grant({ grant_type: 'client_credentials' });\n\n const token = tokenSet.access_token!;\n const expiresAt = tokenSet.expires_at!;\n\n return { token, expiresAt };\n\n } catch (error) {\n const logger = new CrexLogger()\n logger.log({\n level: \"error\",\n message: `getToken error: ${error}`\n })\n return { token: '', expiresAt: 0, error: JSON.stringify(error) };\n\n }\n}\n\nexport const getIssuerMetadata = async (): Promise<any> => {\n const sdk = new CrexSDK();\n const config = sdk.getServerConfig();\n const issuer = await Issuer.discover(config.OIDC.client.issuer);\n return issuer.metadata;\n}\n","import { ConfigInterface, CookiesConfigs } from \"@c-rex/interfaces\";\nimport { SDK_CONFIG_KEY } from '@c-rex/constants';\nimport { cookies } from 'next/headers';\n\n/**\n * Retrieves and parses configuration data from a cookie.\n * @returns The parsed configuration object\n * @throws Error if the configuration cookie is not found or cannot be parsed\n */\nexport const getClientConfig = (): CookiesConfigs => {\n const jsonConfigs = cookies().get(SDK_CONFIG_KEY)?.value;\n if (!jsonConfigs) {\n throw new Error('Configs not found');\n }\n\n const configs: CookiesConfigs = JSON.parse(jsonConfigs);\n\n return configs;\n}\n\ndeclare global {\n // eslint-disable-next-line no-var\n var __GLOBAL_CONFIG__: ConfigInterface | null;\n}\n\nexport function initializeConfig(config: ConfigInterface) {\n if (global.__GLOBAL_CONFIG__) return global.__GLOBAL_CONFIG__;\n global.__GLOBAL_CONFIG__ = config;\n return global.__GLOBAL_CONFIG__;\n}\n\nexport function getServerConfig() {\n if (!global.__GLOBAL_CONFIG__) {\n throw new Error('Server config not initialized');\n }\n return global.__GLOBAL_CONFIG__;\n}\n\nexport function updateConfigProp(key: keyof ConfigInterface, value: any) {\n if (!global.__GLOBAL_CONFIG__) {\n throw new Error('Server config not initialized');\n }\n global.__GLOBAL_CONFIG__[key] = value;\n return global.__GLOBAL_CONFIG__;\n}","import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS } from \"@c-rex/constants\";\nimport { getServerConfig } from \"./config\";\n\n\n/**\n * Logger class for the CREX application.\n * Provides logging functionality with multiple transports (Console, Matomo, Graylog).\n */\nexport class CrexLogger {\n private customerConfig!: ConfigInterface;\n public logger!: winston.Logger;\n\n /**\n * Initializes the logger instance if it hasn't been initialized yet.\n * Loads customer configuration and creates the logger with appropriate transports.\n * \n * @private\n */\n private async initLogger() {\n try {\n if (!this.customerConfig) {\n this.customerConfig = getServerConfig();\n }\n if (!this.logger) {\n this.logger = this.createLogger();\n }\n } catch (error) {\n console.log(\"Error initializing logger:\", error);\n }\n }\n\n /**\n * Logs a message with the specified level and optional category.\n * \n * @param options - Logging options\n * @param options.level - The log level (error, warn, info, etc.)\n * @param options.message - The message to log\n * @param options.category - Optional category for the log message\n */\n public async log({ level, message, category }: {\n level: LogLevelType,\n message: string,\n category?: LogCategoriesType\n }) {\n await this.initLogger();\n const timestamp = new Date().toISOString();\n const newMessage = `[${timestamp}] ${message}`;\n this.logger.log(level, newMessage, category);\n }\n\n /**\n * Creates a new Winston logger instance with configured transports.\n * \n * @private\n * @returns A configured Winston logger instance\n */\n private createLogger() {\n return winston.createLogger({\n levels: LOG_LEVELS,\n transports: [\n new winston.transports.Console({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new MatomoTransport(this.customerConfig),\n new GraylogTransport(this.customerConfig),\n ],\n });\n }\n}","import Transport from \"winston-transport\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\n/**\n * Winston transport for sending logs to Matomo analytics.\n * Extends the base Winston transport with Matomo-specific functionality.\n */\nexport class MatomoTransport extends Transport {\n public matomoTransport: any;\n private configs: ConfigInterface;\n\n /**\n * Creates a new instance of MatomoTransport.\n * \n * @param configs - The application configuration containing logging settings\n */\n constructor(configs: ConfigInterface) {\n super({\n level: configs.logs.matomo.minimumLevel,\n silent: configs.logs.matomo.silent,\n });\n\n this.matomoTransport = new Transport();\n this.configs = configs;\n }\n\n /**\n * Logs a message to Matomo if the message category is included in the configured categories.\n * \n * @param info - The log information including level, message, and category\n * @param callback - Callback function to execute after logging\n */\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const matomoCategory = this.configs.logs.matomo.categoriesLevel\n\n if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {\n this.matomoTransport.log(info, callback);\n }\n }\n}\n","import Transport from \"winston-transport\";\nimport Graylog2Transport from \"winston-graylog2\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\n\n/**\n * Winston transport for sending logs to Graylog.\n * Extends the base Winston transport with Graylog-specific functionality.\n */\nexport class GraylogTransport extends Transport {\n public graylogTransport: any;\n private configs: ConfigInterface\n\n /**\n * Creates a new instance of GraylogTransport.\n * \n * @param configs - The application configuration containing logging settings\n */\n constructor(configs: ConfigInterface) {\n if (!configs.logs.graylog.hostname || configs.logs.graylog.port === undefined) {\n throw new Error(\"Graylog hostname and port must be defined\");\n }\n\n super({\n level: configs.logs.graylog.minimumLevel,\n silent: configs.logs.graylog.silent,\n });\n\n this.configs = configs;\n this.graylogTransport = new Graylog2Transport({\n name: configs.logs.graylog.app,\n silent: configs.logs.graylog.silent,\n handleExceptions: false,\n graylog: {\n servers: [\n { host: configs.logs.graylog.hostname, port: configs.logs.graylog.port }\n ],\n },\n });\n }\n\n /**\n * Logs a message to Graylog if the message category is included in the configured categories.\n * \n * @param info - The log information including level, message, and category\n * @param callback - Callback function to execute after logging\n */\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const graylogCategory = this.configs.logs.graylog.categoriesLevel\n\n if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {\n this.graylogTransport.log(info, callback);\n }\n }\n}\n","import { WarningVars } from \"@c-rex/types\";\nimport { logInfo, OIDCInterface } from \"@c-rex/interfaces\";\nimport { LogLevelType } from \"@c-rex/types\";\nimport { LogCategoriesType } from \"@c-rex/types\";\n\nconst formatIssuer = (issuer: string): string => {\n let newIssuer = issuer\n const lastChar = newIssuer.charAt(newIssuer.length - 1)\n if (lastChar !== \"/\") {\n newIssuer += \"/\"\n }\n newIssuer += \".well-known/openid-configuration\"\n\n return newIssuer;\n}\n\nexport const mergeConfigs = <T>(defaultConfig: Partial<T>, envVars: Partial<T>): T => {\n const definedEnvVars: T = {} as T;\n\n for (const key in envVars) {\n if (envVars[key] !== undefined) {\n definedEnvVars[key] = envVars[key];\n }\n }\n\n return {\n ...defaultConfig,\n ...definedEnvVars,\n };\n}\n\nexport const generateWarnings = (vars: WarningVars[]): string[] => {\n\n const warnings: string[] = []\n\n vars.forEach((variable) => {\n const value = process.env[variable.key];\n if (value === undefined) {\n warnings.push(`Missing environment variable ${variable.key}, using default value: ${variable.default}`)\n }\n })\n\n return warnings;\n}\n\nexport const createUserOIDCConfig = (): { user: OIDCInterface, warnings: string[] } => {\n const warnings: string[] = []\n const userDefaults: Partial<OIDCInterface> = {\n secret: \"dummy\",\n scope: \"openid profile crex.ids.api crex.ids.api.public\",\n enabled: true,\n }\n const userEnvs: Partial<OIDCInterface> = {\n id: process.env.CREX_IDS_ID,\n secret: process.env.CREX_IDS_SECRET,\n scope: process.env.CREX_IDS_USER_SCOPES,\n issuer: process.env.CREX_IDS_ISSUER == undefined ? undefined : formatIssuer(process.env.CREX_IDS_ISSUER),\n enabled: process.env.CREX_IDS_USER_LOGIN_ENABLE == undefined ? undefined : process.env.CREX_IDS_USER_LOGIN_ENABLE == \"true\",\n }\n const user: OIDCInterface = mergeConfigs<OIDCInterface>(userDefaults, userEnvs);\n\n if (user.enabled) {\n const disableOIDCVars = [\n { key: \"CREX_IDS_ID\", value: process.env.CREX_IDS_ID },\n { key: \"CREX_IDS_ISSUER\", value: process.env.CREX_IDS_ISSUER },\n ]\n disableOIDCVars.forEach((variable) => {\n if (variable.value === undefined) {\n user.enabled = false\n\n warnings.push(`Missing environment variable ${variable.key}, disabling client and login`)\n }\n })\n\n }\n\n if (user.enabled) {\n const userWarningVars = [\n { key: \"CREX_IDS_USER_SCOPES\", default: user.scope },\n { key: \"CREX_IDS_SECRET\", default: user.secret },\n { key: \"CREX_IDS_USER_LOGIN_ENABLE\", default: user.enabled }\n ]\n const aux = generateWarnings(userWarningVars)\n warnings.push(...aux);\n }\n\n return { user, warnings }\n}\n\nexport const createClientOIDCConfig = (): { client: OIDCInterface, warnings: string[] } => {\n const warnings: string[] = []\n const clientDefault: Partial<OIDCInterface> = {\n secret: \"dummy\",\n enabled: true,\n }\n const clientEnvs: Partial<OIDCInterface> = {\n id: process.env.CREX_IDS_ID,\n issuer: process.env.CREX_IDS_ISSUER == undefined ? undefined : formatIssuer(process.env.CREX_IDS_ISSUER),\n secret: process.env.CREX_IDS_SECRET,\n enabled: process.env.CREX_IDS_CLIENT_LOGIN_ENABLE == undefined ? undefined : process.env.CREX_IDS_CLIENT_LOGIN_ENABLE == \"true\",\n }\n const client: OIDCInterface = mergeConfigs<OIDCInterface>(clientDefault, clientEnvs);\n\n if (client.enabled) {\n const disableOIDCVars = [\n { key: \"CREX_IDS_ID\", value: process.env.CREX_IDS_ID },\n { key: \"CREX_IDS_ISSUER\", value: process.env.CREX_IDS_ISSUER },\n ]\n disableOIDCVars.forEach((variable) => {\n if (variable.value === undefined) {\n client.enabled = false\n warnings.push(`Missing environment variable ${variable.key}, disabling client and login`)\n }\n })\n }\n\n if (client.enabled) {\n const clientWarningVars = [\n { key: \"CREX_IDS_SECRET\", default: client.secret },\n { key: \"CREX_IDS_CLIENT_LOGIN_ENABLE\", default: client.enabled }\n ]\n\n const aux = generateWarnings(clientWarningVars)\n warnings.push(...aux);\n }\n\n return { client, warnings }\n}\n\nexport const createConsoleLoggerConfig = (): { consoleLogger: Omit<logInfo, \"hostname\" | \"app\" | \"categoriesLevel\">, warnings: string[]; } => {\n const warnings: string[] = []\n\n const consoleLoggerDefaults: Partial<logInfo> = {\n minimumLevel: \"info\" as LogLevelType,\n silent: false,\n }\n const consoleLoggerEnvs: Partial<logInfo> = {\n minimumLevel: process.env.LOG_CONSOLE_LEVEL as LogLevelType,\n silent: process.env.LOG_CONSOLE_SILENT == undefined ? undefined : process.env.LOG_CONSOLE_SILENT == \"true\",\n }\n const consoleLogger: logInfo = mergeConfigs<logInfo>(consoleLoggerDefaults, consoleLoggerEnvs);\n\n if (consoleLogger.silent == false) {\n const consoleWarningsVars = [\n { key: \"LOG_CONSOLE_SILENT\", default: consoleLogger.silent },\n { key: \"LOG_CONSOLE_LEVEL\", default: consoleLogger.minimumLevel }\n ]\n const aux = generateWarnings(consoleWarningsVars)\n warnings.push(...aux);\n }\n\n return {\n consoleLogger,\n warnings\n }\n}\n\nexport const createGraylogLoggerConfig = (): { graylog: logInfo, warnings: string[] } => {\n const warnings: string[] = []\n\n const graylogDefaults: Partial<logInfo> = {\n app: \"app name not set\",\n minimumLevel: \"info\" as LogLevelType,\n silent: false,\n hostname: \"https://log.c-rex.net\",\n port: 12202,\n categoriesLevel: [\"NoLicense\", \"Scenario\", \"Document\", \"Search\", \"Notification\", \"History\", \"UserProfile\"],\n }\n const graylogEnvs: Partial<logInfo> = {\n app: process.env.LOG_GRAYLOG_APP_NAME,\n silent: process.env.LOG_GRAYLOG_SILENT == undefined ? undefined : process.env.LOG_GRAYLOG_SILENT == \"true\",\n hostname: process.env.LOG_GRAYLOG_HOSTNAME,\n port: process.env.LOG_GRAYLOG_PORT == undefined ? undefined : Number(process.env.LOG_GRAYLOG_PORT),\n minimumLevel: process.env.LOG_GRAYLOG_LEVEL as any,\n categoriesLevel: process.env.LOG_GRAYLOG_CATEGORIES == undefined ? undefined : process.env.LOG_GRAYLOG_CATEGORIES.split(\",\") as LogCategoriesType[],\n }\n const graylog: logInfo = mergeConfigs<logInfo>(graylogDefaults, graylogEnvs);\n\n if (graylog.silent == false) {\n const graylogWarningVars = [\n { key: \"LOG_GRAYLOG_APP_NAME\", default: graylog.app },\n { key: \"LOG_GRAYLOG_HOSTNAME\", default: graylog.hostname },\n { key: \"LOG_GRAYLOG_LEVEL\", default: graylog.minimumLevel },\n { key: \"LOG_GRAYLOG_SILENT\", default: graylog.silent },\n { key: \"LOG_GRAYLOG_CATEGORIES\", default: graylog.categoriesLevel },\n { key: \"LOG_GRAYLOG_PORT\", default: graylog.port }\n ]\n const aux = generateWarnings(graylogWarningVars)\n warnings.push(...aux);\n }\n\n return {\n graylog,\n warnings\n }\n}\n\nexport const createMatomoLoggerConfig = (): { matomo: logInfo, warnings: string[] } => {\n const warnings: string[] = []\n\n const matomoDefaults: Partial<logInfo> = {\n app: \"NextJsProjectName\",\n minimumLevel: \"info\" as LogLevelType,\n silent: true,\n hostname: \"\",\n port: 0,\n categoriesLevel: [\"NoLicense\", \"Scenario\", \"Document\", \"Search\", \"Notification\", \"History\", \"UserProfile\"],\n }\n const matomoEnvs: Partial<logInfo> = {\n app: process.env.LOG_MATOMO_APP_NAME,\n silent: process.env.LOG_MATOMO_SILENT == undefined ? undefined : process.env.LOG_MATOMO_SILENT == \"true\",\n hostname: process.env.LOG_MATOMO_HOSTNAME,\n port: process.env.LOG_MATOMO_PORT == undefined ? undefined : Number(process.env.LOG_MATOMO_PORT),\n minimumLevel: process.env.LOG_MATOMO_LEVEL as any,\n categoriesLevel: process.env.LOG_MATOMO_CATEGORIES == undefined ? undefined : process.env.LOG_MATOMO_CATEGORIES.split(\",\") as LogCategoriesType[],\n }\n const matomo: logInfo = mergeConfigs<logInfo>(matomoDefaults, matomoEnvs);\n\n\n const matomoSilentVars = [\n { key: \"LOG_MATOMO_SILENT\", value: process.env.LOG_MATOMO_SILENT },\n { key: \"LOG_MATOMO_HOSTNAME\", value: process.env.LOG_MATOMO_HOSTNAME },\n { key: \"LOG_MATOMO_PORT\", value: process.env.LOG_MATOMO_PORT }\n ]\n matomoSilentVars.forEach((variable) => {\n if (variable.value === undefined) {\n matomo.silent = true\n warnings.push(`Missing environment variable ${variable.key}, setting matomo logger to silent`)\n }\n })\n\n if (matomo.silent == false) {\n const matomoWarningVars = [\n { key: \"LOG_MATOMO_APP_NAME\", default: matomo.app },\n { key: \"LOG_MATOMO_LEVEL\", default: matomo.minimumLevel },\n { key: \"LOG_MATOMO_CATEGORIES\", default: matomo.categoriesLevel }\n ]\n const aux = generateWarnings(matomoWarningVars)\n warnings.push(...aux);\n }\n\n return {\n matomo,\n warnings\n }\n}\n\n","import { ConfigInterface, CookiesConfigs, CustomerConfig } from \"@c-rex/interfaces\";\nimport {\n createClientOIDCConfig,\n createConsoleLoggerConfig,\n createGraylogLoggerConfig,\n createMatomoLoggerConfig,\n createUserOIDCConfig\n} from \"./utils\";\nimport { cookies } from \"next/headers\";\nimport { SDK_CONFIG_KEY } from \"@c-rex/constants\";\n\ndeclare global {\n // eslint-disable-next-line no-var\n var __GLOBAL_CONFIG__: ConfigInterface | null;\n}\n\n/**\n * SDK class for the CREX application.\n * Provides configuration and authentication functionality.\n */\nexport class CrexSDK {\n public userAuthConfig!: any;\n public customerConfig!: ConfigInterface;\n public cookiesConfig!: CookiesConfigs;\n\n public async getUserAuthConfig() {\n if (this.userAuthConfig) {\n return this.userAuthConfig;\n }\n\n if (!this.customerConfig) {\n this.customerConfig = this.getServerConfig()\n }\n\n const user = this.customerConfig.OIDC.user;\n const userInfoEndPoint = this.customerConfig.OIDC.issuerMetadata?.userinfo_endpoint;\n if (user.enabled) {\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n version: \"2.0\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: {\n params: {\n scope: user.scope,\n prompt: \"login\"\n }\n },\n idToken: true,\n checks: [\"pkce\", \"state\"],\n async profile(_: any, tokens: any) {\n const res = await fetch(userInfoEndPoint, {\n headers: {\n Authorization: `Bearer ${tokens.access_token}`,\n },\n });\n\n const userinfo = await res.json();\n\n return {\n id: userinfo.sub,\n name: userinfo.name,\n email: userinfo.email,\n };\n },\n callbacks: {\n async jwt({ token, account }: any) {\n if (account) {\n token.id_token = account.id_token;\n }\n return token;\n },\n async session({ session, token }: any) {\n session.id_token = token.id_token;\n return session;\n },\n },\n },\n ]\n }\n };\n\n return this.userAuthConfig;\n }\n\n public createCustomerConfig(CUSTOMER_CONFIG: CustomerConfig, shouldLog: boolean): { cookiesConfig: CookiesConfigs, config: ConfigInterface } {\n\n const requiredEnvVars = [\"CREX_API_URL\", \"NEXT_PUBLIC_API_URL\"]\n\n const errors = requiredEnvVars.map(key => {\n const value = process.env[key];\n if (value === undefined) {\n return `Missing required environment variable: ${key}`;\n }\n\n return \"\"\n }).filter(item => item.length > 0)\n\n const { user, warnings: userWarnings } = createUserOIDCConfig()\n const { client, warnings: clientWarnings } = createClientOIDCConfig()\n const { matomo, warnings: matomoWarnings } = createMatomoLoggerConfig()\n const { graylog, warnings: graylogWarnings } = createGraylogLoggerConfig()\n const { consoleLogger, warnings: consoleWarnings } = createConsoleLoggerConfig()\n\n const warnings = [\n ...clientWarnings,\n ...consoleWarnings,\n ...userWarnings,\n ...graylogWarnings,\n ...matomoWarnings\n ]\n\n if (shouldLog) {\n if (errors.length > 0) throw new Error(errors.join('\\n'));\n if (warnings.length > 0) console.warn(warnings.join('\\n'));\n }\n\n const cookiesConfig: CookiesConfigs = {\n publicNextApiUrl: process.env.NEXT_PUBLIC_API_URL!,\n ...CUSTOMER_CONFIG,\n OIDC: {\n clientEnabled: client.enabled,\n userEnabled: user.enabled,\n },\n }\n\n let baseUrl = process.env.CREX_API_URL!\n const lastChar = baseUrl.charAt(baseUrl.length - 1)\n if (lastChar !== \"/\") {\n baseUrl += \"/\"\n }\n baseUrl += \"iirds/v1/\"\n\n const config: ConfigInterface = {\n baseUrl,\n OIDC: { client, user },\n logs: { console: consoleLogger, graylog, matomo, },\n ...CUSTOMER_CONFIG,\n }\n\n return { cookiesConfig, config };\n }\n\n public getClientConfig = (): CookiesConfigs => {\n const jsonConfigs = cookies().get(SDK_CONFIG_KEY)?.value;\n if (!jsonConfigs) {\n throw new Error('Configs not found');\n }\n\n const configs: CookiesConfigs = JSON.parse(jsonConfigs);\n\n return configs;\n }\n\n public getServerConfig() {\n if (!global.__GLOBAL_CONFIG__) {\n throw new Error('Server config not initialized');\n }\n return global.__GLOBAL_CONFIG__;\n }\n\n public initializeConfig(config: ConfigInterface) {\n if (global.__GLOBAL_CONFIG__) return global.__GLOBAL_CONFIG__;\n global.__GLOBAL_CONFIG__ = config;\n return global.__GLOBAL_CONFIG__;\n }\n\n public updateConfigProp(key: keyof ConfigInterface, value: any) {\n if (!global.__GLOBAL_CONFIG__) {\n throw new Error('Server config not initialized');\n }\n global.__GLOBAL_CONFIG__[key] = value;\n return global.__GLOBAL_CONFIG__;\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA6B;;;ACAtB,IAAM,MAAM;AAeZ,IAAM,aAAa;AAAA,EACtB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AACX;AAiBO,IAAM,iBAAiB;AAwCvB,IAAM,uBAAuB,KAAK,KAAK,KAAK,KAAK;AAQjD,IAAM,wBAAwB;;;ACtFrC,2BAAuB;;;ACEvB,qBAAwB;AA6BjB,SAAS,kBAAkB;AAC9B,MAAI,CAAC,OAAO,mBAAmB;AAC3B,UAAM,IAAI,MAAM,+BAA+B;AAAA,EACnD;AACA,SAAO,OAAO;AAClB;;;ACpCA,qBAAoB;;;ACApB,+BAAsB;AASf,IAAM,kBAAN,cAA8B,yBAAAA,QAAU;AAAA,EACpC;AAAA,EACC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOR,YAAY,SAA0B;AAClC,UAAM;AAAA,MACF,OAAO,QAAQ,KAAK,OAAO;AAAA,MAC3B,QAAQ,QAAQ,KAAK,OAAO;AAAA,IAChC,CAAC;AAED,SAAK,kBAAkB,IAAI,yBAAAA,QAAU;AACrC,SAAK,UAAU;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IACI,MACA,UACI;AACJ,UAAM,iBAAiB,KAAK,QAAQ,KAAK,OAAO;AAEhD,QAAI,eAAe,SAAS,KAAK,QAAQ,KAAK,eAAe,SA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,aAAO,2BAAa,KAAK,EAAE,MAAM,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACvD;AAEA,UAAM,WAAW,2BAAa,KAAK,EAAE,MAAa,CAAC;AAEnD,aAAS,QAAQ,IAAI;AAAA,MACjB,MAAM;AAAA,MACN,OAAO;AAAA,MACP,UAAU;AAAA,MACV,QAAQ,QAAQ,IAAI,aAAa;AAAA,MACjC,UAAU;AAAA,MACV,MAAM;AAAA,MACN,SAAS,YAAY,IAAI,KAAK,YAAY,GAAI,IAAI;AAAA,IACtD,CAAC;AAED,WAAO;AAAA,EAEX,SAAS,OAAO;AACZ,WAAO,2BAAa,KAAK,EAAE,OAAO,OAAO,KAAK,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACtE;AACJ;AAEO,IAAM,uBAAuB,YAAmC;AACnE,MAAI;AACA,UAAM,WAAW,MAAM,kBAAkB;AACzC,UAAM,MAAM,IAAI,QAAQ;AACxB,UAAM,SAAS,IAAI,gBAAgB;AACnC,QAAI,iBAAiB,QAAQ;AAAA,MACzB,GAAG,OAAO;AAAA,MACV,gBAAgB;AAAA,IACpB,CAAC;AAED,UAAM,WAAW,2BAAa,KAAK,EAAE,gBAAgB,SAAS,CAAC;AAE/D,WAAO;AAAA,EAEX,SAAS,OAAO;AACZ,WAAO,2BAAa,KAAK,EAAE,OAAO,OAAO,KAAK,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACtE;AACJ;","names":["Transport","import_winston_transport","Transport","Graylog2Transport","winston","import_headers"]}
@@ -0,0 +1,587 @@
1
+ // src/api/OIDC.ts
2
+ import { NextResponse } from "next/server";
3
+
4
+ // ../constants/src/index.ts
5
+ var ALL = "*";
6
+ var LOG_LEVELS = {
7
+ critical: 2,
8
+ error: 3,
9
+ warning: 4,
10
+ info: 6,
11
+ debug: 7
12
+ };
13
+ var SDK_CONFIG_KEY = "crex-sdk-config";
14
+ var DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1e3;
15
+ var CREX_TOKEN_HEADER_KEY = "crex-token";
16
+
17
+ // src/OIDC.ts
18
+ import { Issuer } from "openid-client";
19
+
20
+ // src/config.ts
21
+ import { cookies } from "next/headers";
22
+ function getServerConfig() {
23
+ if (!global.__GLOBAL_CONFIG__) {
24
+ throw new Error("Server config not initialized");
25
+ }
26
+ return global.__GLOBAL_CONFIG__;
27
+ }
28
+
29
+ // src/logger.ts
30
+ import winston from "winston";
31
+
32
+ // src/transports/matomo.ts
33
+ import Transport from "winston-transport";
34
+ var MatomoTransport = class extends Transport {
35
+ matomoTransport;
36
+ configs;
37
+ /**
38
+ * Creates a new instance of MatomoTransport.
39
+ *
40
+ * @param configs - The application configuration containing logging settings
41
+ */
42
+ constructor(configs) {
43
+ super({
44
+ level: configs.logs.matomo.minimumLevel,
45
+ silent: configs.logs.matomo.silent
46
+ });
47
+ this.matomoTransport = new Transport();
48
+ this.configs = configs;
49
+ }
50
+ /**
51
+ * Logs a message to Matomo if the message category is included in the configured categories.
52
+ *
53
+ * @param info - The log information including level, message, and category
54
+ * @param callback - Callback function to execute after logging
55
+ */
56
+ log(info, callback) {
57
+ const matomoCategory = this.configs.logs.matomo.categoriesLevel;
58
+ if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
59
+ this.matomoTransport.log(info, callback);
60
+ }
61
+ }
62
+ };
63
+
64
+ // src/transports/graylog.ts
65
+ import Transport2 from "winston-transport";
66
+ import Graylog2Transport from "winston-graylog2";
67
+ var GraylogTransport = class extends Transport2 {
68
+ graylogTransport;
69
+ configs;
70
+ /**
71
+ * Creates a new instance of GraylogTransport.
72
+ *
73
+ * @param configs - The application configuration containing logging settings
74
+ */
75
+ constructor(configs) {
76
+ if (!configs.logs.graylog.hostname || configs.logs.graylog.port === void 0) {
77
+ throw new Error("Graylog hostname and port must be defined");
78
+ }
79
+ super({
80
+ level: configs.logs.graylog.minimumLevel,
81
+ silent: configs.logs.graylog.silent
82
+ });
83
+ this.configs = configs;
84
+ this.graylogTransport = new Graylog2Transport({
85
+ name: configs.logs.graylog.app,
86
+ silent: configs.logs.graylog.silent,
87
+ handleExceptions: false,
88
+ graylog: {
89
+ servers: [
90
+ { host: configs.logs.graylog.hostname, port: configs.logs.graylog.port }
91
+ ]
92
+ }
93
+ });
94
+ }
95
+ /**
96
+ * Logs a message to Graylog if the message category is included in the configured categories.
97
+ *
98
+ * @param info - The log information including level, message, and category
99
+ * @param callback - Callback function to execute after logging
100
+ */
101
+ log(info, callback) {
102
+ const graylogCategory = this.configs.logs.graylog.categoriesLevel;
103
+ if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
104
+ this.graylogTransport.log(info, callback);
105
+ }
106
+ }
107
+ };
108
+
109
+ // src/logger.ts
110
+ var CrexLogger = class {
111
+ customerConfig;
112
+ logger;
113
+ /**
114
+ * Initializes the logger instance if it hasn't been initialized yet.
115
+ * Loads customer configuration and creates the logger with appropriate transports.
116
+ *
117
+ * @private
118
+ */
119
+ async initLogger() {
120
+ try {
121
+ if (!this.customerConfig) {
122
+ this.customerConfig = getServerConfig();
123
+ }
124
+ if (!this.logger) {
125
+ this.logger = this.createLogger();
126
+ }
127
+ } catch (error) {
128
+ console.log("Error initializing logger:", error);
129
+ }
130
+ }
131
+ /**
132
+ * Logs a message with the specified level and optional category.
133
+ *
134
+ * @param options - Logging options
135
+ * @param options.level - The log level (error, warn, info, etc.)
136
+ * @param options.message - The message to log
137
+ * @param options.category - Optional category for the log message
138
+ */
139
+ async log({ level, message, category }) {
140
+ await this.initLogger();
141
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
142
+ const newMessage = `[${timestamp}] ${message}`;
143
+ this.logger.log(level, newMessage, category);
144
+ }
145
+ /**
146
+ * Creates a new Winston logger instance with configured transports.
147
+ *
148
+ * @private
149
+ * @returns A configured Winston logger instance
150
+ */
151
+ createLogger() {
152
+ return winston.createLogger({
153
+ levels: LOG_LEVELS,
154
+ transports: [
155
+ new winston.transports.Console({
156
+ level: this.customerConfig.logs.console.minimumLevel,
157
+ silent: this.customerConfig.logs.console.silent
158
+ }),
159
+ new MatomoTransport(this.customerConfig),
160
+ new GraylogTransport(this.customerConfig)
161
+ ]
162
+ });
163
+ }
164
+ };
165
+
166
+ // src/utils.ts
167
+ var formatIssuer = (issuer) => {
168
+ let newIssuer = issuer;
169
+ const lastChar = newIssuer.charAt(newIssuer.length - 1);
170
+ if (lastChar !== "/") {
171
+ newIssuer += "/";
172
+ }
173
+ newIssuer += ".well-known/openid-configuration";
174
+ return newIssuer;
175
+ };
176
+ var mergeConfigs = (defaultConfig, envVars) => {
177
+ const definedEnvVars = {};
178
+ for (const key in envVars) {
179
+ if (envVars[key] !== void 0) {
180
+ definedEnvVars[key] = envVars[key];
181
+ }
182
+ }
183
+ return {
184
+ ...defaultConfig,
185
+ ...definedEnvVars
186
+ };
187
+ };
188
+ var generateWarnings = (vars) => {
189
+ const warnings = [];
190
+ vars.forEach((variable) => {
191
+ const value = process.env[variable.key];
192
+ if (value === void 0) {
193
+ warnings.push(`Missing environment variable ${variable.key}, using default value: ${variable.default}`);
194
+ }
195
+ });
196
+ return warnings;
197
+ };
198
+ var createUserOIDCConfig = () => {
199
+ const warnings = [];
200
+ const userDefaults = {
201
+ secret: "dummy",
202
+ scope: "openid profile crex.ids.api crex.ids.api.public",
203
+ enabled: true
204
+ };
205
+ const userEnvs = {
206
+ id: process.env.CREX_IDS_ID,
207
+ secret: process.env.CREX_IDS_SECRET,
208
+ scope: process.env.CREX_IDS_USER_SCOPES,
209
+ issuer: process.env.CREX_IDS_ISSUER == void 0 ? void 0 : formatIssuer(process.env.CREX_IDS_ISSUER),
210
+ enabled: process.env.CREX_IDS_USER_LOGIN_ENABLE == void 0 ? void 0 : process.env.CREX_IDS_USER_LOGIN_ENABLE == "true"
211
+ };
212
+ const user = mergeConfigs(userDefaults, userEnvs);
213
+ if (user.enabled) {
214
+ const disableOIDCVars = [
215
+ { key: "CREX_IDS_ID", value: process.env.CREX_IDS_ID },
216
+ { key: "CREX_IDS_ISSUER", value: process.env.CREX_IDS_ISSUER }
217
+ ];
218
+ disableOIDCVars.forEach((variable) => {
219
+ if (variable.value === void 0) {
220
+ user.enabled = false;
221
+ warnings.push(`Missing environment variable ${variable.key}, disabling client and login`);
222
+ }
223
+ });
224
+ }
225
+ if (user.enabled) {
226
+ const userWarningVars = [
227
+ { key: "CREX_IDS_USER_SCOPES", default: user.scope },
228
+ { key: "CREX_IDS_SECRET", default: user.secret },
229
+ { key: "CREX_IDS_USER_LOGIN_ENABLE", default: user.enabled }
230
+ ];
231
+ const aux = generateWarnings(userWarningVars);
232
+ warnings.push(...aux);
233
+ }
234
+ return { user, warnings };
235
+ };
236
+ var createClientOIDCConfig = () => {
237
+ const warnings = [];
238
+ const clientDefault = {
239
+ secret: "dummy",
240
+ enabled: true
241
+ };
242
+ const clientEnvs = {
243
+ id: process.env.CREX_IDS_ID,
244
+ issuer: process.env.CREX_IDS_ISSUER == void 0 ? void 0 : formatIssuer(process.env.CREX_IDS_ISSUER),
245
+ secret: process.env.CREX_IDS_SECRET,
246
+ enabled: process.env.CREX_IDS_CLIENT_LOGIN_ENABLE == void 0 ? void 0 : process.env.CREX_IDS_CLIENT_LOGIN_ENABLE == "true"
247
+ };
248
+ const client = mergeConfigs(clientDefault, clientEnvs);
249
+ if (client.enabled) {
250
+ const disableOIDCVars = [
251
+ { key: "CREX_IDS_ID", value: process.env.CREX_IDS_ID },
252
+ { key: "CREX_IDS_ISSUER", value: process.env.CREX_IDS_ISSUER }
253
+ ];
254
+ disableOIDCVars.forEach((variable) => {
255
+ if (variable.value === void 0) {
256
+ client.enabled = false;
257
+ warnings.push(`Missing environment variable ${variable.key}, disabling client and login`);
258
+ }
259
+ });
260
+ }
261
+ if (client.enabled) {
262
+ const clientWarningVars = [
263
+ { key: "CREX_IDS_SECRET", default: client.secret },
264
+ { key: "CREX_IDS_CLIENT_LOGIN_ENABLE", default: client.enabled }
265
+ ];
266
+ const aux = generateWarnings(clientWarningVars);
267
+ warnings.push(...aux);
268
+ }
269
+ return { client, warnings };
270
+ };
271
+ var createConsoleLoggerConfig = () => {
272
+ const warnings = [];
273
+ const consoleLoggerDefaults = {
274
+ minimumLevel: "info",
275
+ silent: false
276
+ };
277
+ const consoleLoggerEnvs = {
278
+ minimumLevel: process.env.LOG_CONSOLE_LEVEL,
279
+ silent: process.env.LOG_CONSOLE_SILENT == void 0 ? void 0 : process.env.LOG_CONSOLE_SILENT == "true"
280
+ };
281
+ const consoleLogger = mergeConfigs(consoleLoggerDefaults, consoleLoggerEnvs);
282
+ if (consoleLogger.silent == false) {
283
+ const consoleWarningsVars = [
284
+ { key: "LOG_CONSOLE_SILENT", default: consoleLogger.silent },
285
+ { key: "LOG_CONSOLE_LEVEL", default: consoleLogger.minimumLevel }
286
+ ];
287
+ const aux = generateWarnings(consoleWarningsVars);
288
+ warnings.push(...aux);
289
+ }
290
+ return {
291
+ consoleLogger,
292
+ warnings
293
+ };
294
+ };
295
+ var createGraylogLoggerConfig = () => {
296
+ const warnings = [];
297
+ const graylogDefaults = {
298
+ app: "app name not set",
299
+ minimumLevel: "info",
300
+ silent: false,
301
+ hostname: "https://log.c-rex.net",
302
+ port: 12202,
303
+ categoriesLevel: ["NoLicense", "Scenario", "Document", "Search", "Notification", "History", "UserProfile"]
304
+ };
305
+ const graylogEnvs = {
306
+ app: process.env.LOG_GRAYLOG_APP_NAME,
307
+ silent: process.env.LOG_GRAYLOG_SILENT == void 0 ? void 0 : process.env.LOG_GRAYLOG_SILENT == "true",
308
+ hostname: process.env.LOG_GRAYLOG_HOSTNAME,
309
+ port: process.env.LOG_GRAYLOG_PORT == void 0 ? void 0 : Number(process.env.LOG_GRAYLOG_PORT),
310
+ minimumLevel: process.env.LOG_GRAYLOG_LEVEL,
311
+ categoriesLevel: process.env.LOG_GRAYLOG_CATEGORIES == void 0 ? void 0 : process.env.LOG_GRAYLOG_CATEGORIES.split(",")
312
+ };
313
+ const graylog = mergeConfigs(graylogDefaults, graylogEnvs);
314
+ if (graylog.silent == false) {
315
+ const graylogWarningVars = [
316
+ { key: "LOG_GRAYLOG_APP_NAME", default: graylog.app },
317
+ { key: "LOG_GRAYLOG_HOSTNAME", default: graylog.hostname },
318
+ { key: "LOG_GRAYLOG_LEVEL", default: graylog.minimumLevel },
319
+ { key: "LOG_GRAYLOG_SILENT", default: graylog.silent },
320
+ { key: "LOG_GRAYLOG_CATEGORIES", default: graylog.categoriesLevel },
321
+ { key: "LOG_GRAYLOG_PORT", default: graylog.port }
322
+ ];
323
+ const aux = generateWarnings(graylogWarningVars);
324
+ warnings.push(...aux);
325
+ }
326
+ return {
327
+ graylog,
328
+ warnings
329
+ };
330
+ };
331
+ var createMatomoLoggerConfig = () => {
332
+ const warnings = [];
333
+ const matomoDefaults = {
334
+ app: "NextJsProjectName",
335
+ minimumLevel: "info",
336
+ silent: true,
337
+ hostname: "",
338
+ port: 0,
339
+ categoriesLevel: ["NoLicense", "Scenario", "Document", "Search", "Notification", "History", "UserProfile"]
340
+ };
341
+ const matomoEnvs = {
342
+ app: process.env.LOG_MATOMO_APP_NAME,
343
+ silent: process.env.LOG_MATOMO_SILENT == void 0 ? void 0 : process.env.LOG_MATOMO_SILENT == "true",
344
+ hostname: process.env.LOG_MATOMO_HOSTNAME,
345
+ port: process.env.LOG_MATOMO_PORT == void 0 ? void 0 : Number(process.env.LOG_MATOMO_PORT),
346
+ minimumLevel: process.env.LOG_MATOMO_LEVEL,
347
+ categoriesLevel: process.env.LOG_MATOMO_CATEGORIES == void 0 ? void 0 : process.env.LOG_MATOMO_CATEGORIES.split(",")
348
+ };
349
+ const matomo = mergeConfigs(matomoDefaults, matomoEnvs);
350
+ const matomoSilentVars = [
351
+ { key: "LOG_MATOMO_SILENT", value: process.env.LOG_MATOMO_SILENT },
352
+ { key: "LOG_MATOMO_HOSTNAME", value: process.env.LOG_MATOMO_HOSTNAME },
353
+ { key: "LOG_MATOMO_PORT", value: process.env.LOG_MATOMO_PORT }
354
+ ];
355
+ matomoSilentVars.forEach((variable) => {
356
+ if (variable.value === void 0) {
357
+ matomo.silent = true;
358
+ warnings.push(`Missing environment variable ${variable.key}, setting matomo logger to silent`);
359
+ }
360
+ });
361
+ if (matomo.silent == false) {
362
+ const matomoWarningVars = [
363
+ { key: "LOG_MATOMO_APP_NAME", default: matomo.app },
364
+ { key: "LOG_MATOMO_LEVEL", default: matomo.minimumLevel },
365
+ { key: "LOG_MATOMO_CATEGORIES", default: matomo.categoriesLevel }
366
+ ];
367
+ const aux = generateWarnings(matomoWarningVars);
368
+ warnings.push(...aux);
369
+ }
370
+ return {
371
+ matomo,
372
+ warnings
373
+ };
374
+ };
375
+
376
+ // src/sdk.ts
377
+ import { cookies as cookies2 } from "next/headers";
378
+ var CrexSDK = class {
379
+ userAuthConfig;
380
+ customerConfig;
381
+ cookiesConfig;
382
+ async getUserAuthConfig() {
383
+ if (this.userAuthConfig) {
384
+ return this.userAuthConfig;
385
+ }
386
+ if (!this.customerConfig) {
387
+ this.customerConfig = this.getServerConfig();
388
+ }
389
+ const user = this.customerConfig.OIDC.user;
390
+ const userInfoEndPoint = this.customerConfig.OIDC.issuerMetadata?.userinfo_endpoint;
391
+ if (user.enabled) {
392
+ this.userAuthConfig = {
393
+ providers: [
394
+ {
395
+ id: "crex",
396
+ name: "CREX",
397
+ type: "oauth",
398
+ version: "2.0",
399
+ clientId: user.id,
400
+ wellKnown: user.issuer,
401
+ clientSecret: user.secret,
402
+ authorization: {
403
+ params: {
404
+ scope: user.scope,
405
+ prompt: "login"
406
+ }
407
+ },
408
+ idToken: true,
409
+ checks: ["pkce", "state"],
410
+ async profile(_, tokens) {
411
+ const res = await fetch(userInfoEndPoint, {
412
+ headers: {
413
+ Authorization: `Bearer ${tokens.access_token}`
414
+ }
415
+ });
416
+ const userinfo = await res.json();
417
+ return {
418
+ id: userinfo.sub,
419
+ name: userinfo.name,
420
+ email: userinfo.email
421
+ };
422
+ },
423
+ callbacks: {
424
+ async jwt({ token, account }) {
425
+ if (account) {
426
+ token.id_token = account.id_token;
427
+ }
428
+ return token;
429
+ },
430
+ async session({ session, token }) {
431
+ session.id_token = token.id_token;
432
+ return session;
433
+ }
434
+ }
435
+ }
436
+ ]
437
+ };
438
+ }
439
+ ;
440
+ return this.userAuthConfig;
441
+ }
442
+ createCustomerConfig(CUSTOMER_CONFIG, shouldLog) {
443
+ const requiredEnvVars = ["CREX_API_URL", "NEXT_PUBLIC_API_URL"];
444
+ const errors = requiredEnvVars.map((key) => {
445
+ const value = process.env[key];
446
+ if (value === void 0) {
447
+ return `Missing required environment variable: ${key}`;
448
+ }
449
+ return "";
450
+ }).filter((item) => item.length > 0);
451
+ const { user, warnings: userWarnings } = createUserOIDCConfig();
452
+ const { client, warnings: clientWarnings } = createClientOIDCConfig();
453
+ const { matomo, warnings: matomoWarnings } = createMatomoLoggerConfig();
454
+ const { graylog, warnings: graylogWarnings } = createGraylogLoggerConfig();
455
+ const { consoleLogger, warnings: consoleWarnings } = createConsoleLoggerConfig();
456
+ const warnings = [
457
+ ...clientWarnings,
458
+ ...consoleWarnings,
459
+ ...userWarnings,
460
+ ...graylogWarnings,
461
+ ...matomoWarnings
462
+ ];
463
+ if (shouldLog) {
464
+ if (errors.length > 0) throw new Error(errors.join("\n"));
465
+ if (warnings.length > 0) console.warn(warnings.join("\n"));
466
+ }
467
+ const cookiesConfig = {
468
+ publicNextApiUrl: process.env.NEXT_PUBLIC_API_URL,
469
+ ...CUSTOMER_CONFIG,
470
+ OIDC: {
471
+ clientEnabled: client.enabled,
472
+ userEnabled: user.enabled
473
+ }
474
+ };
475
+ let baseUrl = process.env.CREX_API_URL;
476
+ const lastChar = baseUrl.charAt(baseUrl.length - 1);
477
+ if (lastChar !== "/") {
478
+ baseUrl += "/";
479
+ }
480
+ baseUrl += "iirds/v1/";
481
+ const config = {
482
+ baseUrl,
483
+ OIDC: { client, user },
484
+ logs: { console: consoleLogger, graylog, matomo },
485
+ ...CUSTOMER_CONFIG
486
+ };
487
+ return { cookiesConfig, config };
488
+ }
489
+ getClientConfig = () => {
490
+ const jsonConfigs = cookies2().get(SDK_CONFIG_KEY)?.value;
491
+ if (!jsonConfigs) {
492
+ throw new Error("Configs not found");
493
+ }
494
+ const configs = JSON.parse(jsonConfigs);
495
+ return configs;
496
+ };
497
+ getServerConfig() {
498
+ if (!global.__GLOBAL_CONFIG__) {
499
+ throw new Error("Server config not initialized");
500
+ }
501
+ return global.__GLOBAL_CONFIG__;
502
+ }
503
+ initializeConfig(config) {
504
+ if (global.__GLOBAL_CONFIG__) return global.__GLOBAL_CONFIG__;
505
+ global.__GLOBAL_CONFIG__ = config;
506
+ return global.__GLOBAL_CONFIG__;
507
+ }
508
+ updateConfigProp(key, value) {
509
+ if (!global.__GLOBAL_CONFIG__) {
510
+ throw new Error("Server config not initialized");
511
+ }
512
+ global.__GLOBAL_CONFIG__[key] = value;
513
+ return global.__GLOBAL_CONFIG__;
514
+ }
515
+ };
516
+
517
+ // src/OIDC.ts
518
+ var getToken = async () => {
519
+ try {
520
+ const config = getServerConfig();
521
+ const issuer = await Issuer.discover(config.OIDC.client.issuer);
522
+ const client = new issuer.Client({
523
+ client_id: config.OIDC.client.id,
524
+ client_secret: config.OIDC.client.secret
525
+ });
526
+ const tokenSet = await client.grant({ grant_type: "client_credentials" });
527
+ const token = tokenSet.access_token;
528
+ const expiresAt = tokenSet.expires_at;
529
+ return { token, expiresAt };
530
+ } catch (error) {
531
+ const logger = new CrexLogger();
532
+ logger.log({
533
+ level: "error",
534
+ message: `getToken error: ${error}`
535
+ });
536
+ return { token: "", expiresAt: 0, error: JSON.stringify(error) };
537
+ }
538
+ };
539
+ var getIssuerMetadata = async () => {
540
+ const sdk = new CrexSDK();
541
+ const config = sdk.getServerConfig();
542
+ const issuer = await Issuer.discover(config.OIDC.client.issuer);
543
+ return issuer.metadata;
544
+ };
545
+
546
+ // src/api/OIDC.ts
547
+ var getTokenMethod = async () => {
548
+ try {
549
+ const { token, expiresAt, error } = await getToken();
550
+ if (error) {
551
+ return NextResponse.json({ error }, { status: 500 });
552
+ }
553
+ const response = NextResponse.json({ token });
554
+ response.cookies.set({
555
+ name: CREX_TOKEN_HEADER_KEY,
556
+ value: token,
557
+ httpOnly: true,
558
+ secure: process.env.NODE_ENV === "production",
559
+ sameSite: "lax",
560
+ path: "/",
561
+ expires: expiresAt ? new Date(expiresAt * 1e3) : void 0
562
+ });
563
+ return response;
564
+ } catch (error) {
565
+ return NextResponse.json({ error: String(error) }, { status: 500 });
566
+ }
567
+ };
568
+ var discoverIssuerMethod = async () => {
569
+ try {
570
+ const metadata = await getIssuerMetadata();
571
+ const sdk = new CrexSDK();
572
+ const config = sdk.getServerConfig();
573
+ sdk.updateConfigProp("OIDC", {
574
+ ...config.OIDC,
575
+ issuerMetadata: metadata
576
+ });
577
+ const response = NextResponse.json({ issuerMetadata: metadata });
578
+ return response;
579
+ } catch (error) {
580
+ return NextResponse.json({ error: String(error) }, { status: 500 });
581
+ }
582
+ };
583
+ export {
584
+ discoverIssuerMethod,
585
+ getTokenMethod
586
+ };
587
+ //# sourceMappingURL=OIDC.mjs.map