@hemia/auth-sdk 0.0.1

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,505 @@
1
+ 'use strict';
2
+
3
+ require('reflect-metadata');
4
+ var common = require('@hemia/common');
5
+ var networkServices = require('@hemia/network-services');
6
+ var crypto = require('crypto');
7
+ var inversify = require('inversify');
8
+ var cacheManager = require('@hemia/cache-manager');
9
+
10
+ /******************************************************************************
11
+ Copyright (c) Microsoft Corporation.
12
+
13
+ Permission to use, copy, modify, and/or distribute this software for any
14
+ purpose with or without fee is hereby granted.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
17
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
19
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
20
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
21
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
22
+ PERFORMANCE OF THIS SOFTWARE.
23
+ ***************************************************************************** */
24
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
25
+
26
+
27
+ function __decorate(decorators, target, key, desc) {
28
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
29
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
30
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
31
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
32
+ }
33
+
34
+ function __param(paramIndex, decorator) {
35
+ return function (target, key) { decorator(target, key, paramIndex); }
36
+ }
37
+
38
+ function __metadata(metadataKey, metadataValue) {
39
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
40
+ }
41
+
42
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
43
+ var e = new Error(message);
44
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
45
+ };
46
+
47
+ class SessionError extends Error {
48
+ constructor(message, code, redirectTo) {
49
+ super(message);
50
+ this.code = code;
51
+ this.redirectTo = redirectTo;
52
+ this.name = this.constructor.name;
53
+ Error.captureStackTrace(this, this.constructor);
54
+ }
55
+ }
56
+ class SessionNotFoundError extends SessionError {
57
+ constructor(message = 'Sesión no encontrada') {
58
+ super(message, 'SESSION_NOT_FOUND', '/?session=required');
59
+ }
60
+ }
61
+ class SessionExpiredError extends SessionError {
62
+ constructor(message = 'Sesión expirada') {
63
+ super(message, 'SESSION_EXPIRED', '/session-expired?session=expired');
64
+ }
65
+ }
66
+ class SessionInvalidError extends SessionError {
67
+ constructor(message = 'Sesión inválida') {
68
+ super(message, 'SESSION_INVALID', '/?session=invalid');
69
+ }
70
+ }
71
+ class TokenRefreshFailedError extends SessionError {
72
+ constructor(message = 'Error al renovar tokens') {
73
+ super(message, 'TOKEN_REFRESH_FAILED', '/session-expired?session=expired');
74
+ }
75
+ }
76
+ class InvalidTokenFormatError extends SessionError {
77
+ constructor(message = 'Formato de token inválido') {
78
+ super(message, 'INVALID_TOKEN_FORMAT', '/?session=invalid');
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Controller Abstracto Reutilizable
84
+ * Gestiona automáticamente Login, Callback, Me y Logout.
85
+ */
86
+ class AbstractAuthController {
87
+ constructor(authService) {
88
+ this.authService = authService;
89
+ }
90
+ async login(req, res) {
91
+ try {
92
+ const autoParam = typeof req.query.auto === 'string' ? req.query.auto : 'false';
93
+ const { loginUrl, tempState } = this.authService.generateLoginParams(autoParam);
94
+ res.cookie('auth_flow', JSON.stringify(tempState), {
95
+ httpOnly: true,
96
+ secure: process.env.NODE_ENV === 'production',
97
+ maxAge: 300000 // 5 min
98
+ });
99
+ res.redirect(loginUrl);
100
+ }
101
+ catch (error) {
102
+ console.error('Login Error:', error);
103
+ res.status(500).send('Login initialization failed');
104
+ }
105
+ }
106
+ async callback(req, res) {
107
+ try {
108
+ const { code, state } = req.query;
109
+ const authFlowCookie = req.cookies['auth_flow'];
110
+ if (!authFlowCookie) {
111
+ res.status(400).send('Missing auth flow cookie');
112
+ return;
113
+ }
114
+ const storedState = JSON.parse(authFlowCookie);
115
+ const result = await this.authService.handleCallback(code, state, storedState);
116
+ res.cookie('x-session', result.sessionId, {
117
+ httpOnly: true,
118
+ secure: process.env.NODE_ENV === 'production',
119
+ sameSite: 'lax',
120
+ maxAge: result.expiresIn * 1000,
121
+ path: '/'
122
+ });
123
+ res.clearCookie('auth_flow');
124
+ res.redirect(result.redirectUrl);
125
+ }
126
+ catch (error) {
127
+ console.error('Callback Error:', error);
128
+ if (error instanceof common.HttpError) {
129
+ res.status(error.statusCode).json({
130
+ success: false,
131
+ message: error.message,
132
+ error: error.error
133
+ });
134
+ return;
135
+ }
136
+ res.status(500).json({
137
+ success: false,
138
+ message: 'Failed to complete authentication',
139
+ error: error.message
140
+ });
141
+ }
142
+ }
143
+ async me(req, res) {
144
+ const sessionId = req.cookies['x-session'];
145
+ if (!sessionId) {
146
+ return res.status(401).json({
147
+ success: false,
148
+ message: 'No session found',
149
+ data: {
150
+ redirect_to: '/?session=required'
151
+ },
152
+ error: {
153
+ message: 'Session is missing',
154
+ code: 'SESSION_MISSING'
155
+ }
156
+ });
157
+ }
158
+ try {
159
+ const result = await this.authService.getSessionUser(sessionId);
160
+ return res.status(200).json({
161
+ success: true,
162
+ data: result
163
+ });
164
+ }
165
+ catch (error) {
166
+ res.clearCookie('x-session', {
167
+ httpOnly: true,
168
+ secure: process.env.NODE_ENV === 'production',
169
+ sameSite: 'lax',
170
+ });
171
+ if (error instanceof SessionError) {
172
+ return res.status(401).json({
173
+ success: false,
174
+ message: error.message,
175
+ data: {
176
+ redirect_to: error.redirectTo || '/login'
177
+ },
178
+ error: {
179
+ message: error.message,
180
+ code: error.code
181
+ }
182
+ });
183
+ }
184
+ else {
185
+ return res.status(500).json({
186
+ success: false,
187
+ message: 'Failed to retrieve session user',
188
+ error: error.message
189
+ });
190
+ }
191
+ }
192
+ }
193
+ async logout(req, res) {
194
+ const sessionId = req.cookies['x-session'];
195
+ if (sessionId) {
196
+ await this.authService.logout(sessionId);
197
+ }
198
+ res.clearCookie('x-session', {
199
+ httpOnly: true,
200
+ secure: process.env.NODE_ENV === 'production',
201
+ sameSite: 'lax',
202
+ });
203
+ return res.status(200).json({ success: true });
204
+ }
205
+ }
206
+ __decorate([
207
+ common.Get('/login'),
208
+ __param(0, common.Req()),
209
+ __param(1, common.Res()),
210
+ __metadata("design:type", Function),
211
+ __metadata("design:paramtypes", [Object, Object]),
212
+ __metadata("design:returntype", Promise)
213
+ ], AbstractAuthController.prototype, "login", null);
214
+ __decorate([
215
+ common.Get('/callback'),
216
+ __metadata("design:type", Function),
217
+ __metadata("design:paramtypes", [Object, Object]),
218
+ __metadata("design:returntype", Promise)
219
+ ], AbstractAuthController.prototype, "callback", null);
220
+ __decorate([
221
+ common.Get('/me'),
222
+ __param(0, common.Req()),
223
+ __param(1, common.Res()),
224
+ __metadata("design:type", Function),
225
+ __metadata("design:paramtypes", [Object, Object]),
226
+ __metadata("design:returntype", Promise)
227
+ ], AbstractAuthController.prototype, "me", null);
228
+ __decorate([
229
+ common.Post('/logout'),
230
+ __param(0, common.Req()),
231
+ __param(1, common.Res()),
232
+ __metadata("design:type", Function),
233
+ __metadata("design:paramtypes", [Object, Object]),
234
+ __metadata("design:returntype", Promise)
235
+ ], AbstractAuthController.prototype, "logout", null);
236
+
237
+ /**
238
+ * Utilidades para manejo de PKCE y codificación Base64URL
239
+ */
240
+ class Generators {
241
+ /**
242
+ * Base64URL Encoding
243
+ * Reemplaza la implementación manual con Buffer de Node.js
244
+ */
245
+ static base64urlEncode(strOrBuffer) {
246
+ const buffer = Buffer.isBuffer(strOrBuffer)
247
+ ? strOrBuffer
248
+ : Buffer.from(strOrBuffer);
249
+ return buffer
250
+ .toString('base64')
251
+ .replace(/\+/g, '-')
252
+ .replace(/\//g, '_')
253
+ .replace(/=+$/, '');
254
+ }
255
+ /**
256
+ * Genera un Code Verifier para el flujo PKCE (OAuth 2.0).
257
+ * Crea una cadena aleatoria de 43 a 128 caracteres, codificada en Base64URL.
258
+ */
259
+ static generateCodeVerifier() {
260
+ const buffer = crypto.randomBytes(32);
261
+ return this.base64urlEncode(buffer);
262
+ }
263
+ /**
264
+ * Generate Code Challenge (SHA-256)
265
+ */
266
+ static generateCodeChallenge(verifier) {
267
+ const hash = crypto.createHash('sha256')
268
+ .update(verifier)
269
+ .digest();
270
+ return this.base64urlEncode(hash);
271
+ }
272
+ /**
273
+ * Genera un estado aleatorio para la protección CSRF.
274
+ */
275
+ static state() {
276
+ const buffer = crypto.randomBytes(16);
277
+ return this.base64urlEncode(buffer);
278
+ }
279
+ }
280
+
281
+ exports.AuthCacheService = class AuthCacheService {
282
+ constructor(cacheClient) {
283
+ this.cacheClient = cacheClient;
284
+ }
285
+ async set(key, value, ttlSeconds) {
286
+ await this.cacheClient.setObject(key, value, ttlSeconds);
287
+ }
288
+ async get(key) {
289
+ return await this.cacheClient.getObject(key);
290
+ }
291
+ async delete(key) {
292
+ await this.cacheClient.deleteKey(key);
293
+ }
294
+ };
295
+ exports.AuthCacheService = __decorate([
296
+ inversify.injectable(),
297
+ __metadata("design:paramtypes", [cacheManager.CacheService])
298
+ ], exports.AuthCacheService);
299
+
300
+ exports.AuthService = class AuthService {
301
+ constructor(config, storage, jwtManager) {
302
+ this.config = config;
303
+ this.storage = storage;
304
+ this.jwtManager = jwtManager;
305
+ this.networkServices = new networkServices.HMNetworkServices(this.config.ssoBaseUrl);
306
+ }
307
+ /**
308
+ * Genera los parámetros necesarios para iniciar el login SSO
309
+ * @param auto
310
+ * @returns
311
+ */
312
+ generateLoginParams(auto = 'false') {
313
+ const codeVerifier = Generators.generateCodeVerifier();
314
+ const codeChallenge = Generators.generateCodeChallenge(codeVerifier);
315
+ const state = Generators.state();
316
+ const params = new URLSearchParams({
317
+ response_type: 'code',
318
+ client_id: this.config.clientId,
319
+ redirect_uri: this.config.redirectUri,
320
+ state: state,
321
+ code_challenge: codeChallenge,
322
+ code_challenge_method: 'S256',
323
+ auto: auto
324
+ });
325
+ const loginUrl = `${this.config.ssoBaseUrl}${this.config.ssoAuthUrl}?${params.toString()}`;
326
+ const tempState = {
327
+ state,
328
+ codeVerifier
329
+ };
330
+ return {
331
+ loginUrl,
332
+ tempState
333
+ };
334
+ }
335
+ /**
336
+ * Maneja el callback del SSO, intercambiando el código por tokens y creando la sesión.
337
+ * @param code Código de autorización recibido del SSO
338
+ * @param incomingState Estado recibido del SSO
339
+ * @param storedState Estado temporal almacenado antes de redirigir al SSO
340
+ * @returns Información de la sesión creada
341
+ */
342
+ async handleCallback(code, incomingState, storedState) {
343
+ if (incomingState !== storedState.state) {
344
+ throw new common.BadRequestError('Invalid state parameter', 'invalid_state');
345
+ }
346
+ try {
347
+ const response = await this.networkServices.post(this.config.ssoTokenEndpoint, {
348
+ grantType: 'authorization_code',
349
+ clientId: this.config.clientId,
350
+ clientSecret: this.config.clientSecret,
351
+ code,
352
+ redirectUri: this.config.redirectUri,
353
+ codeVerifier: storedState.codeVerifier
354
+ });
355
+ if (response.status !== 200) {
356
+ throw new common.CustomHttpError('Token exchange failed', response.status, 'token_exchange_failed');
357
+ }
358
+ if (!response.data.access_token) {
359
+ throw new common.InternalServerError('No access token received from SSO', 'invalid_token_response');
360
+ }
361
+ const { access_token, refresh_token, id_token, expires_in, session_id } = response.data;
362
+ const sessionId = crypto.randomBytes(16).toString('hex');
363
+ const sessionData = {
364
+ accessToken: access_token,
365
+ refreshToken: refresh_token,
366
+ idToken: id_token,
367
+ expiresAt: Date.now() + (expires_in * 1000),
368
+ createdAt: new Date().toISOString(),
369
+ ssoSessionId: session_id
370
+ };
371
+ await this.storage.set(`x-session:${sessionId}`, sessionData, expires_in);
372
+ return {
373
+ sessionId,
374
+ expiresIn: expires_in,
375
+ redirectUrl: `${this.config.uiBaseUrl}`
376
+ };
377
+ }
378
+ catch (error) {
379
+ console.error('Token Exchange Error:', error);
380
+ throw error;
381
+ }
382
+ }
383
+ /**
384
+ * Obtiene y valida la sesión del usuario a partir del sessionId.
385
+ * Si la sesión está cerca de expirar, intenta refrescar los tokens.
386
+ * @param sessionId Identificador de la sesión
387
+ * @returns Información del usuario o error si la sesión no es válida
388
+ */
389
+ async getSessionUser(sessionId) {
390
+ const key = `x-session:${sessionId}`;
391
+ let session = await this.storage.get(key);
392
+ if (!session) {
393
+ throw new SessionNotFoundError();
394
+ }
395
+ if (session.expiresAt < Date.now()) {
396
+ throw new SessionExpiredError();
397
+ }
398
+ const timeUntilExpiry = session.expiresAt - Date.now();
399
+ if (timeUntilExpiry < 2 * 60 * 1000) {
400
+ try {
401
+ session = await this.refreshTokens(session, sessionId);
402
+ }
403
+ catch (error) {
404
+ throw new TokenRefreshFailedError();
405
+ }
406
+ }
407
+ try {
408
+ const userData = await this.decodeIdToken(session.idToken);
409
+ if (!userData) {
410
+ throw new SessionInvalidError();
411
+ }
412
+ return userData;
413
+ }
414
+ catch (e) {
415
+ throw new InvalidTokenFormatError();
416
+ }
417
+ }
418
+ /**
419
+ * Cierra la sesión del usuario tanto en el SSO como localmente.
420
+ * @param sessionId Identificador de la sesión
421
+ */
422
+ async logout(sessionId) {
423
+ const key = `x-session:${sessionId}`;
424
+ const session = await this.storage.get(key);
425
+ if (session) {
426
+ try {
427
+ await this.networkServices.post(this.config.ssoLogoutEndpoint, {
428
+ ssoSessionId: session.sessionId
429
+ });
430
+ }
431
+ catch (e) { /* Silent error */ }
432
+ await this.storage.delete(key);
433
+ }
434
+ }
435
+ /**
436
+ * Decodifica el ID token para extraer la información del usuario.
437
+ * @param idToken Token de identificación JWT
438
+ * @returns Información del usuario o null si no se puede decodificar
439
+ */
440
+ async decodeIdToken(idToken) {
441
+ try {
442
+ const decode = this.jwtManager.decode(idToken);
443
+ if (!decode) {
444
+ return null;
445
+ }
446
+ const data = {
447
+ email: decode.email || '',
448
+ name: decode.name || '',
449
+ given_name: decode.given_name,
450
+ family_name: decode.family_name,
451
+ picture: decode.picture,
452
+ ...decode
453
+ };
454
+ return data;
455
+ }
456
+ catch (error) {
457
+ throw new Error('Failed to decode ID token');
458
+ }
459
+ }
460
+ /**
461
+ * Refresca los tokens de la sesión utilizando el refresh token.
462
+ * @param session Datos actuales de la sesión
463
+ * @param sessionId Identificador de la sesión
464
+ * @returns Datos actualizados de la sesión
465
+ */
466
+ async refreshTokens(session, sessionId) {
467
+ const response = await this.networkServices.post(this.config.ssoTokenEndpoint, {
468
+ grantType: 'refresh_token',
469
+ clientId: this.config.clientId,
470
+ clientSecret: this.config.clientSecret,
471
+ refreshToken: session.refreshToken,
472
+ sessionId: session.ssoSessionId
473
+ });
474
+ const { access_token, refresh_token, id_token, expires_in } = response.data;
475
+ const updatedSession = {
476
+ accessToken: access_token,
477
+ refreshToken: refresh_token || session.refreshToken,
478
+ idToken: id_token || session.idToken,
479
+ expiresAt: Date.now() + (expires_in * 1000),
480
+ sessionId: response.data.session_id || '',
481
+ createdAt: Date.now().toString()
482
+ };
483
+ await this.storage.set(`x-session:${sessionId}`, updatedSession, expires_in);
484
+ return updatedSession;
485
+ }
486
+ };
487
+ exports.AuthService = __decorate([
488
+ inversify.injectable(),
489
+ __metadata("design:paramtypes", [Object, exports.AuthCacheService, Object])
490
+ ], exports.AuthService);
491
+
492
+ const registerAuthSdk = (container, config, cacheService, jwtManager) => {
493
+ container.bind(exports.AuthService).toDynamicValue(() => {
494
+ return new exports.AuthService(config, cacheService, jwtManager);
495
+ }).inSingletonScope();
496
+ };
497
+
498
+ exports.AbstractAuthController = AbstractAuthController;
499
+ exports.InvalidTokenFormatError = InvalidTokenFormatError;
500
+ exports.SessionError = SessionError;
501
+ exports.SessionExpiredError = SessionExpiredError;
502
+ exports.SessionInvalidError = SessionInvalidError;
503
+ exports.SessionNotFoundError = SessionNotFoundError;
504
+ exports.TokenRefreshFailedError = TokenRefreshFailedError;
505
+ exports.registerAuthSdk = registerAuthSdk;
@@ -0,0 +1,14 @@
1
+ import { Request, Response } from "express";
2
+ import { AuthService } from "../services/auth.service";
3
+ /**
4
+ * Controller Abstracto Reutilizable
5
+ * Gestiona automáticamente Login, Callback, Me y Logout.
6
+ */
7
+ export declare abstract class AbstractAuthController {
8
+ protected readonly authService: AuthService;
9
+ protected constructor(authService: AuthService);
10
+ login(req: Request, res: Response): Promise<void>;
11
+ callback(req: Request, res: Response): Promise<void>;
12
+ me(req: Request, res: Response): Promise<Response>;
13
+ logout(req: Request, res: Response): Promise<Response>;
14
+ }
@@ -0,0 +1 @@
1
+ export * from "./session.error";
@@ -0,0 +1,20 @@
1
+ export declare class SessionError extends Error {
2
+ code: string;
3
+ redirectTo?: string | undefined;
4
+ constructor(message: string, code: string, redirectTo?: string | undefined);
5
+ }
6
+ export declare class SessionNotFoundError extends SessionError {
7
+ constructor(message?: string);
8
+ }
9
+ export declare class SessionExpiredError extends SessionError {
10
+ constructor(message?: string);
11
+ }
12
+ export declare class SessionInvalidError extends SessionError {
13
+ constructor(message?: string);
14
+ }
15
+ export declare class TokenRefreshFailedError extends SessionError {
16
+ constructor(message?: string);
17
+ }
18
+ export declare class InvalidTokenFormatError extends SessionError {
19
+ constructor(message?: string);
20
+ }
@@ -0,0 +1,6 @@
1
+ import "reflect-metadata";
2
+ export * from "./controllers/abstract-auth.controller";
3
+ export * from "./services";
4
+ export * from "./types";
5
+ export * from "./errors";
6
+ export * from "./ioc";
@@ -0,0 +1,4 @@
1
+ import { Container } from "inversify";
2
+ import { IAuthConfig, IJwtManager } from "./types";
3
+ import { AuthCacheService } from "./services";
4
+ export declare const registerAuthSdk: (container: Container, config: IAuthConfig, cacheService: AuthCacheService, jwtManager: IJwtManager) => void;
@@ -0,0 +1,48 @@
1
+ import { IAuthConfig, ICallbackResponse, IJwtManager, ILoginParams, ISessionUser, IStoredState } from '../types';
2
+ import { AuthCacheService } from './cache.service';
3
+ export declare class AuthService {
4
+ private config;
5
+ private storage;
6
+ private jwtManager;
7
+ private networkServices;
8
+ constructor(config: IAuthConfig, storage: AuthCacheService, jwtManager: IJwtManager);
9
+ /**
10
+ * Genera los parámetros necesarios para iniciar el login SSO
11
+ * @param auto
12
+ * @returns
13
+ */
14
+ generateLoginParams(auto?: string): ILoginParams;
15
+ /**
16
+ * Maneja el callback del SSO, intercambiando el código por tokens y creando la sesión.
17
+ * @param code Código de autorización recibido del SSO
18
+ * @param incomingState Estado recibido del SSO
19
+ * @param storedState Estado temporal almacenado antes de redirigir al SSO
20
+ * @returns Información de la sesión creada
21
+ */
22
+ handleCallback(code: string, incomingState: string, storedState: IStoredState): Promise<ICallbackResponse>;
23
+ /**
24
+ * Obtiene y valida la sesión del usuario a partir del sessionId.
25
+ * Si la sesión está cerca de expirar, intenta refrescar los tokens.
26
+ * @param sessionId Identificador de la sesión
27
+ * @returns Información del usuario o error si la sesión no es válida
28
+ */
29
+ getSessionUser(sessionId: string): Promise<ISessionUser>;
30
+ /**
31
+ * Cierra la sesión del usuario tanto en el SSO como localmente.
32
+ * @param sessionId Identificador de la sesión
33
+ */
34
+ logout(sessionId: string): Promise<void>;
35
+ /**
36
+ * Decodifica el ID token para extraer la información del usuario.
37
+ * @param idToken Token de identificación JWT
38
+ * @returns Información del usuario o null si no se puede decodificar
39
+ */
40
+ private decodeIdToken;
41
+ /**
42
+ * Refresca los tokens de la sesión utilizando el refresh token.
43
+ * @param session Datos actuales de la sesión
44
+ * @param sessionId Identificador de la sesión
45
+ * @returns Datos actualizados de la sesión
46
+ */
47
+ private refreshTokens;
48
+ }
@@ -0,0 +1,8 @@
1
+ import { CacheService as CacheServiceClient } from "@hemia/cache-manager";
2
+ export declare class AuthCacheService {
3
+ private cacheClient;
4
+ constructor(cacheClient: CacheServiceClient);
5
+ set<T>(key: string, value: T, ttlSeconds?: number): Promise<void>;
6
+ get<T>(key: string): Promise<T | null>;
7
+ delete(key: string): Promise<void>;
8
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./auth.service";
2
+ export * from "./cache.service";
@@ -0,0 +1,12 @@
1
+ export interface IAuthConfig {
2
+ ssoBaseUrl: string;
3
+ ssoAuthUrl: string;
4
+ ssoTokenEndpoint: string;
5
+ ssoLogoutEndpoint: string;
6
+ clientId: string;
7
+ clientSecret: string;
8
+ redirectUri: string;
9
+ uiBaseUrl?: string;
10
+ cookieDomain?: string;
11
+ isProduction: boolean;
12
+ }
@@ -0,0 +1,5 @@
1
+ export interface ICallbackResponse {
2
+ sessionId: string;
3
+ expiresIn: number;
4
+ redirectUrl: string;
5
+ }
@@ -0,0 +1,10 @@
1
+ export * from "./auth-config.interface";
2
+ export * from "./session-user.interface";
3
+ export * from "./token-response";
4
+ export * from "./store-state.interface";
5
+ export * from "./login-params.interface";
6
+ export * from "./callback-response.interface";
7
+ export * from "./session-user-response.interface";
8
+ export * from "./jwt-manager.interface";
9
+ export * from "./standard-claims.interface";
10
+ export * from "./session-data.interface";
@@ -0,0 +1,3 @@
1
+ export interface IJwtManager {
2
+ decode<T>(token: string): T | null;
3
+ }
@@ -0,0 +1,5 @@
1
+ import { IStoredState } from "./store-state.interface";
2
+ export interface ILoginParams {
3
+ loginUrl: string;
4
+ tempState: IStoredState;
5
+ }
@@ -0,0 +1,8 @@
1
+ export interface ISessionData {
2
+ accessToken: string;
3
+ refreshToken: string;
4
+ idToken: string;
5
+ expiresAt: number;
6
+ createdAt: string;
7
+ sessionId?: string;
8
+ }
@@ -0,0 +1,6 @@
1
+ import { ISessionUser } from "./session-user.interface";
2
+ export interface ISessionUserResponse {
3
+ valid: boolean;
4
+ data?: ISessionUser;
5
+ error?: string;
6
+ }