@c-rex/core 0.1.11 → 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.
@@ -6,6 +6,7 @@ import { NextResponse } from 'next/server';
6
6
  * @returns NextResponse with success status or error message
7
7
  * @throws Error if token retrieval fails
8
8
  */
9
- declare const postMethod: () => Promise<NextResponse>;
9
+ declare const getTokenMethod: () => Promise<NextResponse>;
10
+ declare const discoverIssuerMethod: () => Promise<NextResponse>;
10
11
 
11
- export { postMethod };
12
+ export { discoverIssuerMethod, getTokenMethod };
@@ -6,6 +6,7 @@ import { NextResponse } from 'next/server';
6
6
  * @returns NextResponse with success status or error message
7
7
  * @throws Error if token retrieval fails
8
8
  */
9
- declare const postMethod: () => Promise<NextResponse>;
9
+ declare const getTokenMethod: () => Promise<NextResponse>;
10
+ declare const discoverIssuerMethod: () => Promise<NextResponse>;
10
11
 
11
- export { postMethod };
12
+ export { discoverIssuerMethod, getTokenMethod };
@@ -0,0 +1,623 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/api/OIDC.ts
31
+ var OIDC_exports = {};
32
+ __export(OIDC_exports, {
33
+ discoverIssuerMethod: () => discoverIssuerMethod,
34
+ getTokenMethod: () => getTokenMethod
35
+ });
36
+ module.exports = __toCommonJS(OIDC_exports);
37
+ var import_server = require("next/server");
38
+
39
+ // ../constants/src/index.ts
40
+ var ALL = "*";
41
+ var LOG_LEVELS = {
42
+ critical: 2,
43
+ error: 3,
44
+ warning: 4,
45
+ info: 6,
46
+ debug: 7
47
+ };
48
+ var SDK_CONFIG_KEY = "crex-sdk-config";
49
+ var DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1e3;
50
+ var CREX_TOKEN_HEADER_KEY = "crex-token";
51
+
52
+ // src/OIDC.ts
53
+ var import_openid_client = require("openid-client");
54
+
55
+ // src/config.ts
56
+ var import_headers = require("next/headers");
57
+ function getServerConfig() {
58
+ if (!global.__GLOBAL_CONFIG__) {
59
+ throw new Error("Server config not initialized");
60
+ }
61
+ return global.__GLOBAL_CONFIG__;
62
+ }
63
+
64
+ // src/logger.ts
65
+ var import_winston = __toESM(require("winston"));
66
+
67
+ // src/transports/matomo.ts
68
+ var import_winston_transport = __toESM(require("winston-transport"));
69
+ var MatomoTransport = class extends import_winston_transport.default {
70
+ matomoTransport;
71
+ configs;
72
+ /**
73
+ * Creates a new instance of MatomoTransport.
74
+ *
75
+ * @param configs - The application configuration containing logging settings
76
+ */
77
+ constructor(configs) {
78
+ super({
79
+ level: configs.logs.matomo.minimumLevel,
80
+ silent: configs.logs.matomo.silent
81
+ });
82
+ this.matomoTransport = new import_winston_transport.default();
83
+ this.configs = configs;
84
+ }
85
+ /**
86
+ * Logs a message to Matomo if the message category is included in the configured categories.
87
+ *
88
+ * @param info - The log information including level, message, and category
89
+ * @param callback - Callback function to execute after logging
90
+ */
91
+ log(info, callback) {
92
+ const matomoCategory = this.configs.logs.matomo.categoriesLevel;
93
+ if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
94
+ this.matomoTransport.log(info, callback);
95
+ }
96
+ }
97
+ };
98
+
99
+ // src/transports/graylog.ts
100
+ var import_winston_transport2 = __toESM(require("winston-transport"));
101
+ var import_winston_graylog2 = __toESM(require("winston-graylog2"));
102
+ var GraylogTransport = class extends import_winston_transport2.default {
103
+ graylogTransport;
104
+ configs;
105
+ /**
106
+ * Creates a new instance of GraylogTransport.
107
+ *
108
+ * @param configs - The application configuration containing logging settings
109
+ */
110
+ constructor(configs) {
111
+ if (!configs.logs.graylog.hostname || configs.logs.graylog.port === void 0) {
112
+ throw new Error("Graylog hostname and port must be defined");
113
+ }
114
+ super({
115
+ level: configs.logs.graylog.minimumLevel,
116
+ silent: configs.logs.graylog.silent
117
+ });
118
+ this.configs = configs;
119
+ this.graylogTransport = new import_winston_graylog2.default({
120
+ name: configs.logs.graylog.app,
121
+ silent: configs.logs.graylog.silent,
122
+ handleExceptions: false,
123
+ graylog: {
124
+ servers: [
125
+ { host: configs.logs.graylog.hostname, port: configs.logs.graylog.port }
126
+ ]
127
+ }
128
+ });
129
+ }
130
+ /**
131
+ * Logs a message to Graylog if the message category is included in the configured categories.
132
+ *
133
+ * @param info - The log information including level, message, and category
134
+ * @param callback - Callback function to execute after logging
135
+ */
136
+ log(info, callback) {
137
+ const graylogCategory = this.configs.logs.graylog.categoriesLevel;
138
+ if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
139
+ this.graylogTransport.log(info, callback);
140
+ }
141
+ }
142
+ };
143
+
144
+ // src/logger.ts
145
+ var CrexLogger = class {
146
+ customerConfig;
147
+ logger;
148
+ /**
149
+ * Initializes the logger instance if it hasn't been initialized yet.
150
+ * Loads customer configuration and creates the logger with appropriate transports.
151
+ *
152
+ * @private
153
+ */
154
+ async initLogger() {
155
+ try {
156
+ if (!this.customerConfig) {
157
+ this.customerConfig = getServerConfig();
158
+ }
159
+ if (!this.logger) {
160
+ this.logger = this.createLogger();
161
+ }
162
+ } catch (error) {
163
+ console.log("Error initializing logger:", error);
164
+ }
165
+ }
166
+ /**
167
+ * Logs a message with the specified level and optional category.
168
+ *
169
+ * @param options - Logging options
170
+ * @param options.level - The log level (error, warn, info, etc.)
171
+ * @param options.message - The message to log
172
+ * @param options.category - Optional category for the log message
173
+ */
174
+ async log({ level, message, category }) {
175
+ await this.initLogger();
176
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
177
+ const newMessage = `[${timestamp}] ${message}`;
178
+ this.logger.log(level, newMessage, category);
179
+ }
180
+ /**
181
+ * Creates a new Winston logger instance with configured transports.
182
+ *
183
+ * @private
184
+ * @returns A configured Winston logger instance
185
+ */
186
+ createLogger() {
187
+ return import_winston.default.createLogger({
188
+ levels: LOG_LEVELS,
189
+ transports: [
190
+ new import_winston.default.transports.Console({
191
+ level: this.customerConfig.logs.console.minimumLevel,
192
+ silent: this.customerConfig.logs.console.silent
193
+ }),
194
+ new MatomoTransport(this.customerConfig),
195
+ new GraylogTransport(this.customerConfig)
196
+ ]
197
+ });
198
+ }
199
+ };
200
+
201
+ // src/utils.ts
202
+ var formatIssuer = (issuer) => {
203
+ let newIssuer = issuer;
204
+ const lastChar = newIssuer.charAt(newIssuer.length - 1);
205
+ if (lastChar !== "/") {
206
+ newIssuer += "/";
207
+ }
208
+ newIssuer += ".well-known/openid-configuration";
209
+ return newIssuer;
210
+ };
211
+ var mergeConfigs = (defaultConfig, envVars) => {
212
+ const definedEnvVars = {};
213
+ for (const key in envVars) {
214
+ if (envVars[key] !== void 0) {
215
+ definedEnvVars[key] = envVars[key];
216
+ }
217
+ }
218
+ return {
219
+ ...defaultConfig,
220
+ ...definedEnvVars
221
+ };
222
+ };
223
+ var generateWarnings = (vars) => {
224
+ const warnings = [];
225
+ vars.forEach((variable) => {
226
+ const value = process.env[variable.key];
227
+ if (value === void 0) {
228
+ warnings.push(`Missing environment variable ${variable.key}, using default value: ${variable.default}`);
229
+ }
230
+ });
231
+ return warnings;
232
+ };
233
+ var createUserOIDCConfig = () => {
234
+ const warnings = [];
235
+ const userDefaults = {
236
+ secret: "dummy",
237
+ scope: "openid profile crex.ids.api crex.ids.api.public",
238
+ enabled: true
239
+ };
240
+ const userEnvs = {
241
+ id: process.env.CREX_IDS_ID,
242
+ secret: process.env.CREX_IDS_SECRET,
243
+ scope: process.env.CREX_IDS_USER_SCOPES,
244
+ issuer: process.env.CREX_IDS_ISSUER == void 0 ? void 0 : formatIssuer(process.env.CREX_IDS_ISSUER),
245
+ enabled: process.env.CREX_IDS_USER_LOGIN_ENABLE == void 0 ? void 0 : process.env.CREX_IDS_USER_LOGIN_ENABLE == "true"
246
+ };
247
+ const user = mergeConfigs(userDefaults, userEnvs);
248
+ if (user.enabled) {
249
+ const disableOIDCVars = [
250
+ { key: "CREX_IDS_ID", value: process.env.CREX_IDS_ID },
251
+ { key: "CREX_IDS_ISSUER", value: process.env.CREX_IDS_ISSUER }
252
+ ];
253
+ disableOIDCVars.forEach((variable) => {
254
+ if (variable.value === void 0) {
255
+ user.enabled = false;
256
+ warnings.push(`Missing environment variable ${variable.key}, disabling client and login`);
257
+ }
258
+ });
259
+ }
260
+ if (user.enabled) {
261
+ const userWarningVars = [
262
+ { key: "CREX_IDS_USER_SCOPES", default: user.scope },
263
+ { key: "CREX_IDS_SECRET", default: user.secret },
264
+ { key: "CREX_IDS_USER_LOGIN_ENABLE", default: user.enabled }
265
+ ];
266
+ const aux = generateWarnings(userWarningVars);
267
+ warnings.push(...aux);
268
+ }
269
+ return { user, warnings };
270
+ };
271
+ var createClientOIDCConfig = () => {
272
+ const warnings = [];
273
+ const clientDefault = {
274
+ secret: "dummy",
275
+ enabled: true
276
+ };
277
+ const clientEnvs = {
278
+ id: process.env.CREX_IDS_ID,
279
+ issuer: process.env.CREX_IDS_ISSUER == void 0 ? void 0 : formatIssuer(process.env.CREX_IDS_ISSUER),
280
+ secret: process.env.CREX_IDS_SECRET,
281
+ enabled: process.env.CREX_IDS_CLIENT_LOGIN_ENABLE == void 0 ? void 0 : process.env.CREX_IDS_CLIENT_LOGIN_ENABLE == "true"
282
+ };
283
+ const client = mergeConfigs(clientDefault, clientEnvs);
284
+ if (client.enabled) {
285
+ const disableOIDCVars = [
286
+ { key: "CREX_IDS_ID", value: process.env.CREX_IDS_ID },
287
+ { key: "CREX_IDS_ISSUER", value: process.env.CREX_IDS_ISSUER }
288
+ ];
289
+ disableOIDCVars.forEach((variable) => {
290
+ if (variable.value === void 0) {
291
+ client.enabled = false;
292
+ warnings.push(`Missing environment variable ${variable.key}, disabling client and login`);
293
+ }
294
+ });
295
+ }
296
+ if (client.enabled) {
297
+ const clientWarningVars = [
298
+ { key: "CREX_IDS_SECRET", default: client.secret },
299
+ { key: "CREX_IDS_CLIENT_LOGIN_ENABLE", default: client.enabled }
300
+ ];
301
+ const aux = generateWarnings(clientWarningVars);
302
+ warnings.push(...aux);
303
+ }
304
+ return { client, warnings };
305
+ };
306
+ var createConsoleLoggerConfig = () => {
307
+ const warnings = [];
308
+ const consoleLoggerDefaults = {
309
+ minimumLevel: "info",
310
+ silent: false
311
+ };
312
+ const consoleLoggerEnvs = {
313
+ minimumLevel: process.env.LOG_CONSOLE_LEVEL,
314
+ silent: process.env.LOG_CONSOLE_SILENT == void 0 ? void 0 : process.env.LOG_CONSOLE_SILENT == "true"
315
+ };
316
+ const consoleLogger = mergeConfigs(consoleLoggerDefaults, consoleLoggerEnvs);
317
+ if (consoleLogger.silent == false) {
318
+ const consoleWarningsVars = [
319
+ { key: "LOG_CONSOLE_SILENT", default: consoleLogger.silent },
320
+ { key: "LOG_CONSOLE_LEVEL", default: consoleLogger.minimumLevel }
321
+ ];
322
+ const aux = generateWarnings(consoleWarningsVars);
323
+ warnings.push(...aux);
324
+ }
325
+ return {
326
+ consoleLogger,
327
+ warnings
328
+ };
329
+ };
330
+ var createGraylogLoggerConfig = () => {
331
+ const warnings = [];
332
+ const graylogDefaults = {
333
+ app: "app name not set",
334
+ minimumLevel: "info",
335
+ silent: false,
336
+ hostname: "https://log.c-rex.net",
337
+ port: 12202,
338
+ categoriesLevel: ["NoLicense", "Scenario", "Document", "Search", "Notification", "History", "UserProfile"]
339
+ };
340
+ const graylogEnvs = {
341
+ app: process.env.LOG_GRAYLOG_APP_NAME,
342
+ silent: process.env.LOG_GRAYLOG_SILENT == void 0 ? void 0 : process.env.LOG_GRAYLOG_SILENT == "true",
343
+ hostname: process.env.LOG_GRAYLOG_HOSTNAME,
344
+ port: process.env.LOG_GRAYLOG_PORT == void 0 ? void 0 : Number(process.env.LOG_GRAYLOG_PORT),
345
+ minimumLevel: process.env.LOG_GRAYLOG_LEVEL,
346
+ categoriesLevel: process.env.LOG_GRAYLOG_CATEGORIES == void 0 ? void 0 : process.env.LOG_GRAYLOG_CATEGORIES.split(",")
347
+ };
348
+ const graylog = mergeConfigs(graylogDefaults, graylogEnvs);
349
+ if (graylog.silent == false) {
350
+ const graylogWarningVars = [
351
+ { key: "LOG_GRAYLOG_APP_NAME", default: graylog.app },
352
+ { key: "LOG_GRAYLOG_HOSTNAME", default: graylog.hostname },
353
+ { key: "LOG_GRAYLOG_LEVEL", default: graylog.minimumLevel },
354
+ { key: "LOG_GRAYLOG_SILENT", default: graylog.silent },
355
+ { key: "LOG_GRAYLOG_CATEGORIES", default: graylog.categoriesLevel },
356
+ { key: "LOG_GRAYLOG_PORT", default: graylog.port }
357
+ ];
358
+ const aux = generateWarnings(graylogWarningVars);
359
+ warnings.push(...aux);
360
+ }
361
+ return {
362
+ graylog,
363
+ warnings
364
+ };
365
+ };
366
+ var createMatomoLoggerConfig = () => {
367
+ const warnings = [];
368
+ const matomoDefaults = {
369
+ app: "NextJsProjectName",
370
+ minimumLevel: "info",
371
+ silent: true,
372
+ hostname: "",
373
+ port: 0,
374
+ categoriesLevel: ["NoLicense", "Scenario", "Document", "Search", "Notification", "History", "UserProfile"]
375
+ };
376
+ const matomoEnvs = {
377
+ app: process.env.LOG_MATOMO_APP_NAME,
378
+ silent: process.env.LOG_MATOMO_SILENT == void 0 ? void 0 : process.env.LOG_MATOMO_SILENT == "true",
379
+ hostname: process.env.LOG_MATOMO_HOSTNAME,
380
+ port: process.env.LOG_MATOMO_PORT == void 0 ? void 0 : Number(process.env.LOG_MATOMO_PORT),
381
+ minimumLevel: process.env.LOG_MATOMO_LEVEL,
382
+ categoriesLevel: process.env.LOG_MATOMO_CATEGORIES == void 0 ? void 0 : process.env.LOG_MATOMO_CATEGORIES.split(",")
383
+ };
384
+ const matomo = mergeConfigs(matomoDefaults, matomoEnvs);
385
+ const matomoSilentVars = [
386
+ { key: "LOG_MATOMO_SILENT", value: process.env.LOG_MATOMO_SILENT },
387
+ { key: "LOG_MATOMO_HOSTNAME", value: process.env.LOG_MATOMO_HOSTNAME },
388
+ { key: "LOG_MATOMO_PORT", value: process.env.LOG_MATOMO_PORT }
389
+ ];
390
+ matomoSilentVars.forEach((variable) => {
391
+ if (variable.value === void 0) {
392
+ matomo.silent = true;
393
+ warnings.push(`Missing environment variable ${variable.key}, setting matomo logger to silent`);
394
+ }
395
+ });
396
+ if (matomo.silent == false) {
397
+ const matomoWarningVars = [
398
+ { key: "LOG_MATOMO_APP_NAME", default: matomo.app },
399
+ { key: "LOG_MATOMO_LEVEL", default: matomo.minimumLevel },
400
+ { key: "LOG_MATOMO_CATEGORIES", default: matomo.categoriesLevel }
401
+ ];
402
+ const aux = generateWarnings(matomoWarningVars);
403
+ warnings.push(...aux);
404
+ }
405
+ return {
406
+ matomo,
407
+ warnings
408
+ };
409
+ };
410
+
411
+ // src/sdk.ts
412
+ var import_headers2 = require("next/headers");
413
+ var CrexSDK = class {
414
+ userAuthConfig;
415
+ customerConfig;
416
+ cookiesConfig;
417
+ async getUserAuthConfig() {
418
+ if (this.userAuthConfig) {
419
+ return this.userAuthConfig;
420
+ }
421
+ if (!this.customerConfig) {
422
+ this.customerConfig = this.getServerConfig();
423
+ }
424
+ const user = this.customerConfig.OIDC.user;
425
+ const userInfoEndPoint = this.customerConfig.OIDC.issuerMetadata?.userinfo_endpoint;
426
+ if (user.enabled) {
427
+ this.userAuthConfig = {
428
+ providers: [
429
+ {
430
+ id: "crex",
431
+ name: "CREX",
432
+ type: "oauth",
433
+ version: "2.0",
434
+ clientId: user.id,
435
+ wellKnown: user.issuer,
436
+ clientSecret: user.secret,
437
+ authorization: {
438
+ params: {
439
+ scope: user.scope,
440
+ prompt: "login"
441
+ }
442
+ },
443
+ idToken: true,
444
+ checks: ["pkce", "state"],
445
+ async profile(_, tokens) {
446
+ const res = await fetch(userInfoEndPoint, {
447
+ headers: {
448
+ Authorization: `Bearer ${tokens.access_token}`
449
+ }
450
+ });
451
+ const userinfo = await res.json();
452
+ return {
453
+ id: userinfo.sub,
454
+ name: userinfo.name,
455
+ email: userinfo.email
456
+ };
457
+ },
458
+ callbacks: {
459
+ async jwt({ token, account }) {
460
+ if (account) {
461
+ token.id_token = account.id_token;
462
+ }
463
+ return token;
464
+ },
465
+ async session({ session, token }) {
466
+ session.id_token = token.id_token;
467
+ return session;
468
+ }
469
+ }
470
+ }
471
+ ]
472
+ };
473
+ }
474
+ ;
475
+ return this.userAuthConfig;
476
+ }
477
+ createCustomerConfig(CUSTOMER_CONFIG, shouldLog) {
478
+ const requiredEnvVars = ["CREX_API_URL", "NEXT_PUBLIC_API_URL"];
479
+ const errors = requiredEnvVars.map((key) => {
480
+ const value = process.env[key];
481
+ if (value === void 0) {
482
+ return `Missing required environment variable: ${key}`;
483
+ }
484
+ return "";
485
+ }).filter((item) => item.length > 0);
486
+ const { user, warnings: userWarnings } = createUserOIDCConfig();
487
+ const { client, warnings: clientWarnings } = createClientOIDCConfig();
488
+ const { matomo, warnings: matomoWarnings } = createMatomoLoggerConfig();
489
+ const { graylog, warnings: graylogWarnings } = createGraylogLoggerConfig();
490
+ const { consoleLogger, warnings: consoleWarnings } = createConsoleLoggerConfig();
491
+ const warnings = [
492
+ ...clientWarnings,
493
+ ...consoleWarnings,
494
+ ...userWarnings,
495
+ ...graylogWarnings,
496
+ ...matomoWarnings
497
+ ];
498
+ if (shouldLog) {
499
+ if (errors.length > 0) throw new Error(errors.join("\n"));
500
+ if (warnings.length > 0) console.warn(warnings.join("\n"));
501
+ }
502
+ const cookiesConfig = {
503
+ publicNextApiUrl: process.env.NEXT_PUBLIC_API_URL,
504
+ ...CUSTOMER_CONFIG,
505
+ OIDC: {
506
+ clientEnabled: client.enabled,
507
+ userEnabled: user.enabled
508
+ }
509
+ };
510
+ let baseUrl = process.env.CREX_API_URL;
511
+ const lastChar = baseUrl.charAt(baseUrl.length - 1);
512
+ if (lastChar !== "/") {
513
+ baseUrl += "/";
514
+ }
515
+ baseUrl += "iirds/v1/";
516
+ const config = {
517
+ baseUrl,
518
+ OIDC: { client, user },
519
+ logs: { console: consoleLogger, graylog, matomo },
520
+ ...CUSTOMER_CONFIG
521
+ };
522
+ return { cookiesConfig, config };
523
+ }
524
+ getClientConfig = () => {
525
+ const jsonConfigs = (0, import_headers2.cookies)().get(SDK_CONFIG_KEY)?.value;
526
+ if (!jsonConfigs) {
527
+ throw new Error("Configs not found");
528
+ }
529
+ const configs = JSON.parse(jsonConfigs);
530
+ return configs;
531
+ };
532
+ getServerConfig() {
533
+ if (!global.__GLOBAL_CONFIG__) {
534
+ throw new Error("Server config not initialized");
535
+ }
536
+ return global.__GLOBAL_CONFIG__;
537
+ }
538
+ initializeConfig(config) {
539
+ if (global.__GLOBAL_CONFIG__) return global.__GLOBAL_CONFIG__;
540
+ global.__GLOBAL_CONFIG__ = config;
541
+ return global.__GLOBAL_CONFIG__;
542
+ }
543
+ updateConfigProp(key, value) {
544
+ if (!global.__GLOBAL_CONFIG__) {
545
+ throw new Error("Server config not initialized");
546
+ }
547
+ global.__GLOBAL_CONFIG__[key] = value;
548
+ return global.__GLOBAL_CONFIG__;
549
+ }
550
+ };
551
+
552
+ // src/OIDC.ts
553
+ var getToken = async () => {
554
+ try {
555
+ const config = getServerConfig();
556
+ const issuer = await import_openid_client.Issuer.discover(config.OIDC.client.issuer);
557
+ const client = new issuer.Client({
558
+ client_id: config.OIDC.client.id,
559
+ client_secret: config.OIDC.client.secret
560
+ });
561
+ const tokenSet = await client.grant({ grant_type: "client_credentials" });
562
+ const token = tokenSet.access_token;
563
+ const expiresAt = tokenSet.expires_at;
564
+ return { token, expiresAt };
565
+ } catch (error) {
566
+ const logger = new CrexLogger();
567
+ logger.log({
568
+ level: "error",
569
+ message: `getToken error: ${error}`
570
+ });
571
+ return { token: "", expiresAt: 0, error: JSON.stringify(error) };
572
+ }
573
+ };
574
+ var getIssuerMetadata = async () => {
575
+ const sdk = new CrexSDK();
576
+ const config = sdk.getServerConfig();
577
+ const issuer = await import_openid_client.Issuer.discover(config.OIDC.client.issuer);
578
+ return issuer.metadata;
579
+ };
580
+
581
+ // src/api/OIDC.ts
582
+ var getTokenMethod = async () => {
583
+ try {
584
+ const { token, expiresAt, error } = await getToken();
585
+ if (error) {
586
+ return import_server.NextResponse.json({ error }, { status: 500 });
587
+ }
588
+ const response = import_server.NextResponse.json({ token });
589
+ response.cookies.set({
590
+ name: CREX_TOKEN_HEADER_KEY,
591
+ value: token,
592
+ httpOnly: true,
593
+ secure: process.env.NODE_ENV === "production",
594
+ sameSite: "lax",
595
+ path: "/",
596
+ expires: expiresAt ? new Date(expiresAt * 1e3) : void 0
597
+ });
598
+ return response;
599
+ } catch (error) {
600
+ return import_server.NextResponse.json({ error: String(error) }, { status: 500 });
601
+ }
602
+ };
603
+ var discoverIssuerMethod = async () => {
604
+ try {
605
+ const metadata = await getIssuerMetadata();
606
+ const sdk = new CrexSDK();
607
+ const config = sdk.getServerConfig();
608
+ sdk.updateConfigProp("OIDC", {
609
+ ...config.OIDC,
610
+ issuerMetadata: metadata
611
+ });
612
+ const response = import_server.NextResponse.json({ issuerMetadata: metadata });
613
+ return response;
614
+ } catch (error) {
615
+ return import_server.NextResponse.json({ error: String(error) }, { status: 500 });
616
+ }
617
+ };
618
+ // Annotate the CommonJS export names for ESM import in node:
619
+ 0 && (module.exports = {
620
+ discoverIssuerMethod,
621
+ getTokenMethod
622
+ });
623
+ //# sourceMappingURL=OIDC.js.map