@futdevpro/nts-dynamo 1.10.23 → 1.10.24

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.
Files changed (71) hide show
  1. package/build/_modules/oauth2/_routes/oauth2.controller.d.ts +17 -0
  2. package/build/_modules/oauth2/_routes/oauth2.controller.d.ts.map +1 -0
  3. package/build/_modules/oauth2/_routes/oauth2.controller.js +97 -0
  4. package/build/_modules/oauth2/_routes/oauth2.controller.js.map +1 -0
  5. package/build/_modules/oauth2/_services/oauth2.auth-service.d.ts +31 -0
  6. package/build/_modules/oauth2/_services/oauth2.auth-service.d.ts.map +1 -0
  7. package/build/_modules/oauth2/_services/oauth2.auth-service.js +216 -0
  8. package/build/_modules/oauth2/_services/oauth2.auth-service.js.map +1 -0
  9. package/build/_modules/oauth2/_services/oauth2.control-service.d.ts +133 -0
  10. package/build/_modules/oauth2/_services/oauth2.control-service.d.ts.map +1 -0
  11. package/build/_modules/oauth2/_services/oauth2.control-service.js +574 -0
  12. package/build/_modules/oauth2/_services/oauth2.control-service.js.map +1 -0
  13. package/build/_modules/oauth2/index.d.ts +4 -0
  14. package/build/_modules/oauth2/index.d.ts.map +1 -0
  15. package/build/_modules/oauth2/index.js +7 -0
  16. package/build/_modules/oauth2/index.js.map +1 -0
  17. package/build/_modules/open-ai/_enums/open-ai-model.enum.d.ts +11 -0
  18. package/build/_modules/open-ai/_enums/open-ai-model.enum.d.ts.map +1 -0
  19. package/build/_modules/open-ai/_enums/open-ai-model.enum.js +110 -0
  20. package/build/_modules/open-ai/_enums/open-ai-model.enum.js.map +1 -0
  21. package/build/_modules/open-ai/_models/gpt-call-settings.interface.d.ts +54 -0
  22. package/build/_modules/open-ai/_models/gpt-call-settings.interface.d.ts.map +1 -0
  23. package/build/_modules/open-ai/_models/gpt-call-settings.interface.js +65 -0
  24. package/build/_modules/open-ai/_models/gpt-call-settings.interface.js.map +1 -0
  25. package/build/_modules/open-ai/_models/open-ai-api-env-settings.interface.d.ts +7 -0
  26. package/build/_modules/open-ai/_models/open-ai-api-env-settings.interface.d.ts.map +1 -0
  27. package/build/_modules/open-ai/_models/open-ai-api-env-settings.interface.js +3 -0
  28. package/build/_modules/open-ai/_models/open-ai-api-env-settings.interface.js.map +1 -0
  29. package/build/_modules/open-ai/_models/open-ai-settings.interface.d.ts +17 -0
  30. package/build/_modules/open-ai/_models/open-ai-settings.interface.d.ts.map +1 -0
  31. package/build/_modules/open-ai/_models/open-ai-settings.interface.js +25 -0
  32. package/build/_modules/open-ai/_models/open-ai-settings.interface.js.map +1 -0
  33. package/build/_modules/open-ai/_services/embedding.control-service.d.ts +26 -0
  34. package/build/_modules/open-ai/_services/embedding.control-service.d.ts.map +1 -0
  35. package/build/_modules/open-ai/_services/embedding.control-service.js +54 -0
  36. package/build/_modules/open-ai/_services/embedding.control-service.js.map +1 -0
  37. package/build/_modules/open-ai/_services/gpt.service-base.d.ts +98 -0
  38. package/build/_modules/open-ai/_services/gpt.service-base.d.ts.map +1 -0
  39. package/build/_modules/open-ai/_services/gpt.service-base.js +284 -0
  40. package/build/_modules/open-ai/_services/gpt.service-base.js.map +1 -0
  41. package/build/_modules/open-ai/_services/open-ai.service-base.d.ts +23 -0
  42. package/build/_modules/open-ai/_services/open-ai.service-base.d.ts.map +1 -0
  43. package/build/_modules/open-ai/_services/open-ai.service-base.js +50 -0
  44. package/build/_modules/open-ai/_services/open-ai.service-base.js.map +1 -0
  45. package/build/_modules/open-ai/index.d.ts +8 -0
  46. package/build/_modules/open-ai/index.d.ts.map +1 -0
  47. package/build/_modules/open-ai/index.js +11 -0
  48. package/build/_modules/open-ai/index.js.map +1 -0
  49. package/build/_services/base/db.service.d.ts +38 -0
  50. package/build/_services/base/db.service.d.ts.map +1 -1
  51. package/build/_services/base/db.service.js +40 -0
  52. package/build/_services/base/db.service.js.map +1 -1
  53. package/build/_services/server/app.server.d.ts +17 -0
  54. package/build/_services/server/app.server.d.ts.map +1 -1
  55. package/build/_services/server/app.server.js +17 -0
  56. package/build/_services/server/app.server.js.map +1 -1
  57. package/package.json +47 -17
  58. package/src/_modules/oauth2/_routes/oauth2.controller.ts +99 -0
  59. package/src/_modules/oauth2/_services/oauth2.auth-service.ts +232 -0
  60. package/src/_modules/oauth2/_services/oauth2.control-service.ts +651 -0
  61. package/src/_modules/oauth2/index.ts +9 -0
  62. package/src/_modules/open-ai/_enums/open-ai-model.enum.ts +137 -0
  63. package/src/_modules/open-ai/_models/gpt-call-settings.interface.ts +69 -0
  64. package/src/_modules/open-ai/_models/open-ai-api-env-settings.interface.ts +12 -0
  65. package/src/_modules/open-ai/_models/open-ai-settings.interface.ts +31 -0
  66. package/src/_modules/open-ai/_services/embedding.control-service.ts +61 -0
  67. package/src/_modules/open-ai/_services/gpt.service-base.ts +440 -0
  68. package/src/_modules/open-ai/_services/open-ai.service-base.ts +73 -0
  69. package/src/_modules/open-ai/index.ts +13 -0
  70. package/src/_services/base/db.service.ts +41 -0
  71. package/src/_services/server/app.server.ts +18 -0
@@ -0,0 +1,651 @@
1
+ import { Request, Response } from 'express';
2
+ import { DyFM_Error, DyFM_Log } from '@futdevpro/fsm-dynamo';
3
+ import { DyNTS_SingletonService } from '../../../_services/base/singleton.service';
4
+ import { DyNTS_global_settings } from '../../../_collections/global-settings.const';
5
+ import { DyNTS_OAuth2_AuthService } from './oauth2.auth-service';
6
+ import { randomBytes } from 'crypto';
7
+
8
+ /**
9
+ * OAuth2 Control Service implementation
10
+ *
11
+ * This service handles OAuth2 specific business logic and token management
12
+ *
13
+ * @example
14
+ * const oauth2Service = DyNTS_OAuth2_ControlService.getInstance();
15
+ * await oauth2Service.handleAuthorizationRequest(req, res);
16
+ */
17
+ export class DyNTS_OAuth2_ControlService extends DyNTS_SingletonService {
18
+ static getInstance(): DyNTS_OAuth2_ControlService {
19
+ return DyNTS_OAuth2_ControlService.getSingletonInstance();
20
+ }
21
+
22
+ readonly serviceName: string = 'OAuth2ControlService';
23
+
24
+ private readonly authService: DyNTS_OAuth2_AuthService = DyNTS_OAuth2_AuthService.getInstance();
25
+ private readonly authorizationCodes: Map<string, { clientId: string; scope: string; expiresAt: number }> = new Map();
26
+ private readonly accessTokens: Map<string, { clientId: string; scope: string; expiresAt: number }> = new Map();
27
+ private readonly refreshTokens: Map<string, { clientId: string; scope: string; accessToken: string }> = new Map();
28
+ private readonly clients: Map<string, {
29
+ clientId: string;
30
+ clientSecret: string;
31
+ redirectUris: string[];
32
+ allowedScopes: string[];
33
+ isActive: boolean;
34
+ }> = new Map();
35
+ private readonly users: Map<string, {
36
+ username: string;
37
+ password: string; // In a real implementation, this would be a hashed password
38
+ scopes: string[];
39
+ }> = new Map();
40
+
41
+ /**
42
+ * Handles the OAuth2 authorization request
43
+ * @param req Express Request object
44
+ * @param res Express Response object
45
+ */
46
+ async handleAuthorizationRequest(req: Request, res: Response): Promise<void> {
47
+ try {
48
+ const { response_type, client_id, redirect_uri, scope, state } = req.query;
49
+
50
+ // Validate required parameters
51
+ if (!response_type || !client_id || !redirect_uri) {
52
+ throw new DyFM_Error({
53
+ status: 400,
54
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HA0`,
55
+ addECToUserMsg: true,
56
+ message: 'Missing required OAuth2 parameters',
57
+ userMessage: 'Invalid authorization request',
58
+ issuerService: this.serviceName,
59
+ });
60
+ }
61
+
62
+ // Validate client_id against registered clients
63
+ if (!this.isValidClient(client_id as string)) {
64
+ throw new DyFM_Error({
65
+ status: 400,
66
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HA2`,
67
+ addECToUserMsg: true,
68
+ message: 'Invalid client_id',
69
+ userMessage: 'Invalid authorization request',
70
+ issuerService: this.serviceName,
71
+ });
72
+ }
73
+
74
+ // Validate redirect_uri against registered redirect URIs
75
+ if (!this.isValidRedirectUri(client_id as string, redirect_uri as string)) {
76
+ throw new DyFM_Error({
77
+ status: 400,
78
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HA3`,
79
+ addECToUserMsg: true,
80
+ message: 'Invalid redirect_uri',
81
+ userMessage: 'Invalid authorization request',
82
+ issuerService: this.serviceName,
83
+ });
84
+ }
85
+
86
+ // Validate scope against allowed scopes
87
+ if (!this.isValidScope(client_id as string, scope as string)) {
88
+ throw new DyFM_Error({
89
+ status: 400,
90
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HA4`,
91
+ addECToUserMsg: true,
92
+ message: 'Invalid scope',
93
+ userMessage: 'Invalid authorization request',
94
+ issuerService: this.serviceName,
95
+ });
96
+ }
97
+
98
+ // For authorization code flow
99
+ if (response_type === 'code') {
100
+ const authorizationCode = await this.generateAuthorizationCode(client_id as string, scope as string);
101
+
102
+ // Redirect with authorization code
103
+ const redirectUrl = new URL(redirect_uri as string);
104
+ redirectUrl.searchParams.append('code', authorizationCode);
105
+ if (state) redirectUrl.searchParams.append('state', state as string);
106
+
107
+ res.redirect(redirectUrl.toString());
108
+ return;
109
+ }
110
+
111
+ // For implicit flow
112
+ if (response_type === 'token') {
113
+ const accessToken = await this.generateAccessToken(client_id as string, scope as string);
114
+
115
+ // Redirect with access token
116
+ const redirectUrl = new URL(redirect_uri as string);
117
+ redirectUrl.hash = `access_token=${accessToken}`;
118
+ if (state) redirectUrl.hash += `&state=${state}`;
119
+
120
+ res.redirect(redirectUrl.toString());
121
+ return;
122
+ }
123
+
124
+ throw new DyFM_Error({
125
+ status: 400,
126
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HA1`,
127
+ addECToUserMsg: true,
128
+ message: 'Unsupported response_type',
129
+ userMessage: 'Invalid authorization request',
130
+ issuerService: this.serviceName,
131
+ });
132
+ } catch (error) {
133
+ DyFM_Log.error('Authorization request failed', error);
134
+ throw error;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Validates if the client is registered and active
140
+ * @param clientId The client ID to validate
141
+ * @returns true if the client is valid
142
+ */
143
+ private isValidClient(clientId: string): boolean {
144
+ const client = this.clients.get(clientId);
145
+ return client?.isActive ?? false;
146
+ }
147
+
148
+ /**
149
+ * Validates if the redirect URI is registered for the client
150
+ * @param clientId The client ID
151
+ * @param redirectUri The redirect URI to validate
152
+ * @returns true if the redirect URI is valid
153
+ */
154
+ private isValidRedirectUri(clientId: string, redirectUri: string): boolean {
155
+ const client = this.clients.get(clientId);
156
+ if (!client) return false;
157
+
158
+ // Check if the redirect URI matches any of the registered URIs
159
+ return client.redirectUris.some(uri => {
160
+ // Simple exact match for now
161
+ // TODO: Implement more sophisticated URI matching (e.g., wildcards, regex)
162
+ return uri === redirectUri;
163
+ });
164
+ }
165
+
166
+ /**
167
+ * Validates if the scope is allowed for the client
168
+ * @param clientId The client ID
169
+ * @param scope The scope to validate
170
+ * @returns true if the scope is valid
171
+ */
172
+ private isValidScope(clientId: string, scope: string): boolean {
173
+ const client = this.clients.get(clientId);
174
+ if (!client) return false;
175
+
176
+ // If no scope is requested, it's valid
177
+ if (!scope) return true;
178
+
179
+ // Split scope string into individual scopes
180
+ const requestedScopes = scope.split(' ');
181
+
182
+ // Check if all requested scopes are allowed
183
+ return requestedScopes.every(s => client.allowedScopes.includes(s));
184
+ }
185
+
186
+ /**
187
+ * Handles the OAuth2 token request
188
+ * @param req Express Request object
189
+ * @param res Express Response object
190
+ */
191
+ async handleTokenRequest(req: Request, res: Response): Promise<void> {
192
+ try {
193
+ const { grant_type, code, refresh_token, client_id, client_secret, username, password } = req.body;
194
+
195
+ // Validate required parameters
196
+ if (!grant_type || !client_id || !client_secret) {
197
+ throw new DyFM_Error({
198
+ status: 400,
199
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HT0`,
200
+ addECToUserMsg: true,
201
+ message: 'Missing required OAuth2 parameters',
202
+ userMessage: 'Invalid token request',
203
+ issuerService: this.serviceName,
204
+ });
205
+ }
206
+
207
+ // Validate client credentials
208
+ if (!this.validateClientCredentials(client_id, client_secret)) {
209
+ throw new DyFM_Error({
210
+ status: 401,
211
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HT4`,
212
+ addECToUserMsg: true,
213
+ message: 'Invalid client credentials',
214
+ userMessage: 'Invalid token request',
215
+ issuerService: this.serviceName,
216
+ });
217
+ }
218
+
219
+ switch (grant_type) {
220
+ case 'authorization_code':
221
+ if (!code) {
222
+ throw new DyFM_Error({
223
+ status: 400,
224
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HT1`,
225
+ addECToUserMsg: true,
226
+ message: 'Missing authorization code',
227
+ userMessage: 'Invalid token request',
228
+ issuerService: this.serviceName,
229
+ });
230
+ }
231
+
232
+ // Validate authorization code
233
+ const authCodeData = this.authorizationCodes.get(code);
234
+ if (!authCodeData || authCodeData.expiresAt < Date.now()) {
235
+ throw new DyFM_Error({
236
+ status: 400,
237
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HT5`,
238
+ addECToUserMsg: true,
239
+ message: 'Invalid or expired authorization code',
240
+ userMessage: 'Invalid token request',
241
+ issuerService: this.serviceName,
242
+ });
243
+ }
244
+
245
+ // Remove used authorization code
246
+ this.authorizationCodes.delete(code);
247
+
248
+ const accessToken = await this.generateAccessToken(client_id, authCodeData.scope);
249
+ const refreshToken = await this.generateRefreshToken(client_id);
250
+
251
+ // Store refresh token with access token reference
252
+ this.refreshTokens.set(refreshToken, {
253
+ clientId: client_id,
254
+ scope: authCodeData.scope,
255
+ accessToken
256
+ });
257
+
258
+ res.json({
259
+ access_token: accessToken,
260
+ token_type: 'Bearer',
261
+ expires_in: 3600,
262
+ refresh_token: refreshToken,
263
+ scope: authCodeData.scope
264
+ });
265
+ break;
266
+
267
+ case 'refresh_token':
268
+ if (!refresh_token) {
269
+ throw new DyFM_Error({
270
+ status: 400,
271
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HT2`,
272
+ addECToUserMsg: true,
273
+ message: 'Missing refresh token',
274
+ userMessage: 'Invalid token request',
275
+ issuerService: this.serviceName,
276
+ });
277
+ }
278
+
279
+ // Validate refresh token
280
+ const refreshTokenData = this.refreshTokens.get(refresh_token);
281
+ if (!refreshTokenData) {
282
+ throw new DyFM_Error({
283
+ status: 400,
284
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HT6`,
285
+ addECToUserMsg: true,
286
+ message: 'Invalid refresh token',
287
+ userMessage: 'Invalid token request',
288
+ issuerService: this.serviceName,
289
+ });
290
+ }
291
+
292
+ // Revoke old access token
293
+ this.accessTokens.delete(refreshTokenData.accessToken);
294
+
295
+ // Generate new access token
296
+ const newAccessToken = await this.generateAccessToken(client_id, refreshTokenData.scope);
297
+ const newRefreshToken = await this.generateRefreshToken(client_id);
298
+
299
+ // Store new refresh token
300
+ this.refreshTokens.set(newRefreshToken, {
301
+ clientId: client_id,
302
+ scope: refreshTokenData.scope,
303
+ accessToken: newAccessToken
304
+ });
305
+
306
+ res.json({
307
+ access_token: newAccessToken,
308
+ token_type: 'Bearer',
309
+ expires_in: 3600,
310
+ refresh_token: newRefreshToken,
311
+ scope: refreshTokenData.scope
312
+ });
313
+ break;
314
+
315
+ case 'client_credentials':
316
+ const clientAccessToken = await this.generateAccessToken(client_id, '');
317
+ res.json({
318
+ access_token: clientAccessToken,
319
+ token_type: 'Bearer',
320
+ expires_in: 3600
321
+ });
322
+ break;
323
+
324
+ case 'password':
325
+ if (!username || !password) {
326
+ throw new DyFM_Error({
327
+ status: 400,
328
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HT7`,
329
+ addECToUserMsg: true,
330
+ message: 'Missing username or password',
331
+ userMessage: 'Invalid token request',
332
+ issuerService: this.serviceName,
333
+ });
334
+ }
335
+
336
+ // Authenticate user
337
+ const userScopes = this.authenticateUser(username, password);
338
+ if (!userScopes) {
339
+ throw new DyFM_Error({
340
+ status: 401,
341
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HT8`,
342
+ addECToUserMsg: true,
343
+ message: 'Invalid username or password',
344
+ userMessage: 'Invalid token request',
345
+ issuerService: this.serviceName,
346
+ });
347
+ }
348
+
349
+ // Generate access token
350
+ const userAccessToken = await this.generateAccessToken(client_id, userScopes.join(' '));
351
+ const userRefreshToken = await this.generateRefreshToken(client_id);
352
+
353
+ // Store refresh token with access token reference
354
+ this.refreshTokens.set(userRefreshToken, {
355
+ clientId: client_id,
356
+ scope: userScopes.join(' '),
357
+ accessToken: userAccessToken
358
+ });
359
+
360
+ res.json({
361
+ access_token: userAccessToken,
362
+ token_type: 'Bearer',
363
+ expires_in: 3600,
364
+ refresh_token: userRefreshToken,
365
+ scope: userScopes.join(' ')
366
+ });
367
+ break;
368
+
369
+ default:
370
+ throw new DyFM_Error({
371
+ status: 400,
372
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HT3`,
373
+ addECToUserMsg: true,
374
+ message: 'Unsupported grant_type',
375
+ userMessage: 'Invalid token request',
376
+ issuerService: this.serviceName,
377
+ });
378
+ }
379
+ } catch (error) {
380
+ DyFM_Log.error('Token request failed', error);
381
+ throw error;
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Validates client credentials
387
+ * @param clientId The client ID
388
+ * @param clientSecret The client secret
389
+ * @returns true if the credentials are valid
390
+ */
391
+ private validateClientCredentials(clientId: string, clientSecret: string): boolean {
392
+ const client = this.clients.get(clientId);
393
+ return (client?.clientSecret === clientSecret) && (client?.isActive ?? false);
394
+ }
395
+
396
+ /**
397
+ * Handles the OAuth2 userinfo request
398
+ * @param req Express Request object
399
+ * @param res Express Response object
400
+ */
401
+ async handleUserInfoRequest(req: Request, res: Response): Promise<void> {
402
+ try {
403
+ const token = this.authService.getTokenFromRequest(req);
404
+
405
+ // Validate token
406
+ const tokenData = this.accessTokens.get(token);
407
+ if (!tokenData || tokenData.expiresAt < Date.now()) {
408
+ throw new DyFM_Error({
409
+ status: 401,
410
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HU0`,
411
+ addECToUserMsg: true,
412
+ message: 'Invalid or expired access token',
413
+ userMessage: 'Invalid token',
414
+ issuerService: this.serviceName,
415
+ });
416
+ }
417
+
418
+ // Extract user information based on token scope
419
+ const userInfo = await this.getUserInfoFromToken(token);
420
+
421
+ res.json(userInfo);
422
+ } catch (error) {
423
+ DyFM_Log.error('Userinfo request failed', error);
424
+ throw error;
425
+ }
426
+ }
427
+
428
+ /**
429
+ * Gets user information from the token
430
+ * @param token The access token
431
+ * @returns The user information object
432
+ */
433
+ private async getUserInfoFromToken(token: string): Promise<any> {
434
+ const tokenData = this.accessTokens.get(token);
435
+ if (!tokenData) {
436
+ throw new DyFM_Error({
437
+ status: 401,
438
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HU1`,
439
+ addECToUserMsg: true,
440
+ message: 'Invalid access token',
441
+ userMessage: 'Invalid token',
442
+ issuerService: this.serviceName,
443
+ });
444
+ }
445
+
446
+ // TODO: Implement user information retrieval from database/storage
447
+ // For now, return mock user information
448
+ return {
449
+ sub: 'user123',
450
+ name: 'John Doe',
451
+ email: 'john.doe@example.com',
452
+ // Add other user information based on scope
453
+ ...(tokenData.scope.includes('profile') && {
454
+ given_name: 'John',
455
+ family_name: 'Doe',
456
+ picture: 'https://example.com/john.jpg'
457
+ }),
458
+ ...(tokenData.scope.includes('email') && {
459
+ email_verified: true
460
+ })
461
+ };
462
+ }
463
+
464
+ /**
465
+ * Handles the OAuth2 token revocation request
466
+ * @param req Express Request object
467
+ * @param res Express Response object
468
+ */
469
+ async handleTokenRevocation(req: Request, res: Response): Promise<void> {
470
+ try {
471
+ const { token, token_type_hint } = req.body;
472
+
473
+ if (!token) {
474
+ throw new DyFM_Error({
475
+ status: 400,
476
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HR0`,
477
+ addECToUserMsg: true,
478
+ message: 'Missing token',
479
+ userMessage: 'Invalid revocation request',
480
+ issuerService: this.serviceName,
481
+ });
482
+ }
483
+
484
+ // Try to revoke the token based on token_type_hint
485
+ let revoked = false;
486
+
487
+ if (!token_type_hint || token_type_hint === 'access_token') {
488
+ // Try to revoke as access token
489
+ if (this.accessTokens.delete(token)) {
490
+ revoked = true;
491
+ }
492
+ }
493
+
494
+ if (!revoked && (!token_type_hint || token_type_hint === 'refresh_token')) {
495
+ // Try to revoke as refresh token
496
+ const refreshTokenData = this.refreshTokens.get(token);
497
+ if (refreshTokenData) {
498
+ // Also revoke the associated access token
499
+ this.accessTokens.delete(refreshTokenData.accessToken);
500
+ this.refreshTokens.delete(token);
501
+ revoked = true;
502
+ }
503
+ }
504
+
505
+ if (!revoked) {
506
+ // Token not found or already revoked
507
+ throw new DyFM_Error({
508
+ status: 400,
509
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-OA2-HR1`,
510
+ addECToUserMsg: true,
511
+ message: 'Token not found or already revoked',
512
+ userMessage: 'Invalid revocation request',
513
+ issuerService: this.serviceName,
514
+ });
515
+ }
516
+
517
+ res.status(200).send();
518
+ } catch (error) {
519
+ DyFM_Log.error('Token revocation failed', error);
520
+ throw error;
521
+ }
522
+ }
523
+
524
+ /**
525
+ * Generates an authorization code
526
+ * @param clientId The client ID
527
+ * @param scope The requested scope
528
+ * @returns The generated authorization code
529
+ */
530
+ private async generateAuthorizationCode(clientId: string, scope: string): Promise<string> {
531
+ const code = randomBytes(32).toString('hex');
532
+ const expiresAt = Date.now() + 600000; // 10 minutes expiration
533
+
534
+ this.authorizationCodes.set(code, {
535
+ clientId,
536
+ scope,
537
+ expiresAt
538
+ });
539
+
540
+ return code;
541
+ }
542
+
543
+ /**
544
+ * Generates an access token
545
+ * @param clientId The client ID
546
+ * @param scope The requested scope
547
+ * @returns The generated access token
548
+ */
549
+ private async generateAccessToken(clientId: string, scope: string): Promise<string> {
550
+ const token = randomBytes(32).toString('hex');
551
+ const expiresAt = Date.now() + 3600000; // 1 hour expiration
552
+
553
+ this.accessTokens.set(token, {
554
+ clientId,
555
+ scope,
556
+ expiresAt
557
+ });
558
+
559
+ return token;
560
+ }
561
+
562
+ /**
563
+ * Generates a refresh token
564
+ * @param clientId The client ID
565
+ * @returns The generated refresh token
566
+ */
567
+ private async generateRefreshToken(clientId: string): Promise<string> {
568
+ const token = randomBytes(32).toString('hex');
569
+
570
+ this.refreshTokens.set(token, {
571
+ clientId,
572
+ scope: '',
573
+ accessToken: ''
574
+ });
575
+
576
+ return token;
577
+ }
578
+
579
+ /**
580
+ * Gets the access token data
581
+ * @param token The access token
582
+ * @returns The access token data or undefined if not found
583
+ */
584
+ getAccessTokenData(token: string): { clientId: string; scope: string; expiresAt: number } | undefined {
585
+ return this.accessTokens.get(token);
586
+ }
587
+
588
+ /**
589
+ * Registers a new OAuth2 client
590
+ * @param clientId The client ID
591
+ * @param clientSecret The client secret
592
+ * @param redirectUris The allowed redirect URIs
593
+ * @param allowedScopes The allowed scopes
594
+ * @returns true if the client was registered successfully
595
+ */
596
+ registerClient(
597
+ clientId: string,
598
+ clientSecret: string,
599
+ redirectUris: string[],
600
+ allowedScopes: string[]
601
+ ): boolean {
602
+ if (this.clients.has(clientId)) {
603
+ return false;
604
+ }
605
+
606
+ this.clients.set(clientId, {
607
+ clientId,
608
+ clientSecret,
609
+ redirectUris,
610
+ allowedScopes,
611
+ isActive: true
612
+ });
613
+
614
+ return true;
615
+ }
616
+
617
+ /**
618
+ * Authenticates a user with username and password
619
+ * @param username The username
620
+ * @param password The password
621
+ * @returns The user's scopes if authentication is successful, undefined otherwise
622
+ */
623
+ private authenticateUser(username: string, password: string): string[] | undefined {
624
+ const user = this.users.get(username);
625
+ if (!user || user.password !== password) { // In a real implementation, compare hashed passwords
626
+ return undefined;
627
+ }
628
+ return user.scopes;
629
+ }
630
+
631
+ /**
632
+ * Registers a new user
633
+ * @param username The username
634
+ * @param password The password
635
+ * @param scopes The user's scopes
636
+ * @returns true if the user was registered successfully
637
+ */
638
+ registerUser(username: string, password: string, scopes: string[]): boolean {
639
+ if (this.users.has(username)) {
640
+ return false;
641
+ }
642
+
643
+ this.users.set(username, {
644
+ username,
645
+ password, // In a real implementation, hash the password
646
+ scopes
647
+ });
648
+
649
+ return true;
650
+ }
651
+ }
@@ -0,0 +1,9 @@
1
+
2
+
3
+
4
+ export * from './_routes/oauth2.controller';
5
+
6
+ export * from './_services/oauth2.auth-service';
7
+ export * from './_services/oauth2.control-service';
8
+
9
+