@vunexa/lixa 0.0.1-alpha.8 → 0.1.0

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 (52) hide show
  1. package/README.md +263 -143
  2. package/dist/dao/session-cache.d.ts +11 -0
  3. package/dist/dao/session-cache.d.ts.map +1 -0
  4. package/dist/dao/state-cache.d.ts +8 -6
  5. package/dist/dao/state-cache.d.ts.map +1 -1
  6. package/dist/dao/types.d.ts +376 -3
  7. package/dist/dao/types.d.ts.map +1 -1
  8. package/dist/export-types/index.d.ts +1397 -0
  9. package/dist/export-types/tsdoc-metadata.json +11 -0
  10. package/dist/index.cjs +1035 -0
  11. package/dist/index.cjs.map +1 -0
  12. package/dist/index.d.cts +1361 -0
  13. package/dist/index.d.ts +11 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +992 -9
  16. package/dist/index.js.map +1 -1
  17. package/dist/lixa.d.ts +286 -19
  18. package/dist/lixa.d.ts.map +1 -1
  19. package/dist/models/session.d.ts +316 -0
  20. package/dist/models/session.d.ts.map +1 -0
  21. package/dist/providers/IProvider.d.ts +127 -4
  22. package/dist/providers/IProvider.d.ts.map +1 -1
  23. package/dist/providers/index.d.ts +0 -2
  24. package/dist/providers/index.d.ts.map +1 -1
  25. package/dist/types.d.ts +195 -24
  26. package/dist/types.d.ts.map +1 -1
  27. package/dist/utils/user-info.d.ts +82 -0
  28. package/dist/utils/user-info.d.ts.map +1 -0
  29. package/package.json +15 -10
  30. package/dist/dao/state-cache.js +0 -18
  31. package/dist/dao/state-cache.js.map +0 -1
  32. package/dist/dao/types.js +0 -2
  33. package/dist/dao/types.js.map +0 -1
  34. package/dist/lixa.js +0 -248
  35. package/dist/lixa.js.map +0 -1
  36. package/dist/providers/IProvider.js +0 -2
  37. package/dist/providers/IProvider.js.map +0 -1
  38. package/dist/providers/github.d.ts +0 -9
  39. package/dist/providers/github.d.ts.map +0 -1
  40. package/dist/providers/github.js +0 -8
  41. package/dist/providers/github.js.map +0 -1
  42. package/dist/providers/google.d.ts +0 -9
  43. package/dist/providers/google.d.ts.map +0 -1
  44. package/dist/providers/google.js +0 -8
  45. package/dist/providers/google.js.map +0 -1
  46. package/dist/providers/index.js +0 -3
  47. package/dist/providers/index.js.map +0 -1
  48. package/dist/types.js +0 -2
  49. package/dist/types.js.map +0 -1
  50. package/dist/utils/constants.js +0 -4
  51. package/dist/utils/constants.js.map +0 -1
  52. package/index.d.ts +0 -227
package/dist/index.js CHANGED
@@ -1,10 +1,993 @@
1
- /**
2
- * A flexible, provider-agnostic OAuth 2.0 and OpenID Connect (OIDC) client library for backend applications.
3
- *
4
- * @remarks
5
- * This package simplifies multi-provider authentication flows (e.g., Google, GitHub), supports extensible session management, and enables custom provider registration.
6
- *
7
- * @packageDocumentation
8
- */
9
- export { Lixa } from "./lixa";
1
+ // src/lixa.ts
2
+ import { randomBytes as randomBytes2 } from "crypto";
3
+
4
+ // src/types.ts
5
+ var AccountLinkingStrategy = /* @__PURE__ */ ((AccountLinkingStrategy2) => {
6
+ AccountLinkingStrategy2["AUTO_LINK_BY_VERIFIED_EMAIL"] = "AUTO_LINK_BY_VERIFIED_EMAIL";
7
+ AccountLinkingStrategy2["ISOLATED"] = "ISOLATED";
8
+ return AccountLinkingStrategy2;
9
+ })(AccountLinkingStrategy || {});
10
+
11
+ // src/dao/state-cache.ts
12
+ import NodeCache from "node-cache";
13
+ import { randomBytes } from "crypto";
14
+ var LocalStateHandler = class {
15
+ cache;
16
+ stateStorage;
17
+ constructor(defaultTtlSeconds = 600) {
18
+ this.cache = new NodeCache({ stdTTL: defaultTtlSeconds });
19
+ this.stateStorage = {
20
+ saveState: async (state, data, expiresInSeconds) => {
21
+ this.cache.set(state, data, expiresInSeconds);
22
+ },
23
+ getState: async (state) => {
24
+ return this.cache.get(state) || null;
25
+ },
26
+ deleteState: async (state) => {
27
+ this.cache.del(state);
28
+ }
29
+ };
30
+ }
31
+ // Default GenerateState implementation
32
+ async generateState(provider) {
33
+ const state = randomBytes(16).toString("hex");
34
+ const codeVerifier = randomBytes(32).toString("hex");
35
+ return {
36
+ state,
37
+ data: {
38
+ provider,
39
+ codeVerifier,
40
+ createdAt: Date.now()
41
+ }
42
+ };
43
+ }
44
+ };
45
+
46
+ // src/lixa.ts
47
+ import crypto from "crypto";
48
+
49
+ // src/dao/session-cache.ts
50
+ import NodeCache2 from "node-cache";
51
+ var LocalSessionHandler = class {
52
+ cache;
53
+ emailToSessionMap = /* @__PURE__ */ new Map();
54
+ sessionStorage;
55
+ constructor(defaultTtlSeconds = 600) {
56
+ this.cache = new NodeCache2({ stdTTL: defaultTtlSeconds });
57
+ this.sessionStorage = {
58
+ saveSession: async (sessionId, session, expiresInSeconds) => {
59
+ this.cache.set(sessionId, session, expiresInSeconds);
60
+ if (session.email) {
61
+ this.emailToSessionMap.set(session.email.toLowerCase(), sessionId);
62
+ }
63
+ },
64
+ getSession: async (sessionId) => {
65
+ return this.cache.get(sessionId) || null;
66
+ },
67
+ deleteSession: async (sessionId) => {
68
+ const session = this.cache.get(sessionId);
69
+ if (session?.email) {
70
+ this.emailToSessionMap.delete(session.email.toLowerCase());
71
+ }
72
+ this.cache.del(sessionId);
73
+ },
74
+ getSessionByEmail: async (email) => {
75
+ const normalizedEmail = email.toLowerCase();
76
+ const sessionId = this.emailToSessionMap.get(normalizedEmail);
77
+ if (!sessionId) return null;
78
+ const session = this.cache.get(sessionId);
79
+ if (!session) {
80
+ this.emailToSessionMap.delete(normalizedEmail);
81
+ return null;
82
+ }
83
+ return { sessionId, session };
84
+ }
85
+ };
86
+ }
87
+ // Default GenerateSession implementation
88
+ async GenerateSession(tokenData, providerMetadata) {
89
+ if (!tokenData.access_token || typeof tokenData.access_token !== "string") {
90
+ throw new Error("No valid access token found in OAuth response");
91
+ }
92
+ const session = {
93
+ token: tokenData.access_token,
94
+ raw: tokenData
95
+ };
96
+ return session;
97
+ }
98
+ };
99
+
100
+ // src/utils/user-info.ts
101
+ function decodeIdToken(idToken) {
102
+ const parts = idToken.split(".");
103
+ if (parts.length !== 3) {
104
+ throw new Error("Invalid ID token format: expected 3 parts separated by dots");
105
+ }
106
+ const base64Payload = parts[1];
107
+ if (!base64Payload) {
108
+ throw new Error("Invalid ID token: missing payload section");
109
+ }
110
+ const payload = Buffer.from(base64Payload, "base64").toString();
111
+ try {
112
+ return JSON.parse(payload);
113
+ } catch (error) {
114
+ throw new Error("Invalid ID token: failed to parse payload JSON");
115
+ }
116
+ }
117
+ function determineProviderFromIssuer(userInfo) {
118
+ if (!userInfo.iss) {
119
+ return null;
120
+ }
121
+ const issuer = userInfo.iss.toLowerCase();
122
+ if (issuer.includes("accounts.google.com")) {
123
+ return "google";
124
+ }
125
+ if (issuer.includes("github")) {
126
+ return "github";
127
+ }
128
+ return null;
129
+ }
130
+ async function fetchUserInfo(accessToken, userInfoEndpoint) {
131
+ const response = await fetch(userInfoEndpoint, {
132
+ headers: {
133
+ Authorization: `Bearer ${accessToken}`,
134
+ Accept: "application/json"
135
+ }
136
+ });
137
+ if (!response.ok) {
138
+ throw new Error(`Failed to fetch user info: ${response.status} ${response.statusText}`);
139
+ }
140
+ const data = await response.json();
141
+ if (!data || typeof data !== "object" || !("email" in data) || typeof data.email !== "string") {
142
+ throw new Error(`Invalid user info response: missing or invalid email`);
143
+ }
144
+ return {
145
+ email: data.email,
146
+ id: "id" in data ? String(data.id) : void 0,
147
+ sub: "sub" in data ? String(data.sub) : void 0,
148
+ given_name: "given_name" in data ? String(data.given_name) : void 0,
149
+ family_name: "family_name" in data ? String(data.family_name) : void 0,
150
+ name: "name" in data ? String(data.name) : void 0,
151
+ picture: "picture" in data ? String(data.picture) : void 0,
152
+ email_verified: "email_verified" in data ? Boolean(data.email_verified) : void 0,
153
+ iss: "iss" in data ? String(data.iss) : void 0
154
+ };
155
+ }
156
+ async function extractUserInfo(tokenData, providerMetadata) {
157
+ let userInfo;
158
+ const userInfoEndpoint = providerMetadata.endpoints.userInfo;
159
+ if (tokenData.id_token) {
160
+ userInfo = decodeIdToken(tokenData.id_token);
161
+ } else if (tokenData.access_token) {
162
+ userInfo = await fetchUserInfo(tokenData.access_token, userInfoEndpoint);
163
+ } else {
164
+ throw new Error("No ID token or access token available to fetch user info");
165
+ }
166
+ return { userInfo };
167
+ }
168
+
169
+ // src/lixa.ts
170
+ var Lixa = class _Lixa {
171
+ static DEFAULT_PROVIDERS = /* @__PURE__ */ new Map();
172
+ static CONFIGURED_PROVIDERS = /* @__PURE__ */ new Map();
173
+ // Legacy registry for backward compatibility
174
+ static LOCAL_STATE_HANDLER = new LocalStateHandler();
175
+ static LOCAL_SESSION_HANDLER = new LocalSessionHandler();
176
+ config;
177
+ stateHandler;
178
+ sessionHandler;
179
+ debug;
180
+ /**
181
+ * Creates a new Lixa instance with the provided configuration.
182
+ *
183
+ * @remarks
184
+ * Providers can be passed inline in the configuration using the `provider` field.
185
+ * Provider resolution priority: inline custom provider \> default providers \> legacy registry.
186
+ *
187
+ * @param config - The configuration object containing provider settings and optional session strategy
188
+ *
189
+ * @throws Error when provider configuration is missing required fields
190
+ * @throws Error when provider implementation is missing required properties
191
+ * @throws Error when provider is not available and no inline implementation is provided
192
+ */
193
+ constructor(config) {
194
+ this.config = config;
195
+ this.stateHandler = config.stateHandler || _Lixa.LOCAL_STATE_HANDLER;
196
+ this.sessionHandler = config.sessionHandler || _Lixa.LOCAL_SESSION_HANDLER;
197
+ this.debug = config.debug || false;
198
+ this.log("INFO", "Init", "Initializing Lixa instance", {
199
+ providers: Object.keys(config.providers),
200
+ debug: this.debug
201
+ });
202
+ for (const [providerName, providerConfig] of Object.entries(config.providers)) {
203
+ const name = providerName.toLowerCase();
204
+ const typedConfig = providerConfig;
205
+ this.validateProviderConfig(providerName, typedConfig);
206
+ if (typedConfig.provider) {
207
+ this.validateProviderImplementation(providerName, typedConfig.provider);
208
+ this.log("INFO", "Init", `Registered inline provider: ${providerName}`);
209
+ } else {
210
+ if (!_Lixa.DEFAULT_PROVIDERS.has(name) && !_Lixa.CONFIGURED_PROVIDERS.has(name)) {
211
+ this.log("ERROR", "Init", `Provider '${providerName}' not available`);
212
+ throw new Error(
213
+ `Provider '${providerName}' is not available. Either import it from '@vunexa/lixa-providers' and include it in the configuration, or provide a custom implementation using the 'provider' field: { provider: new CustomProvider(), clientId: '...', ... }`
214
+ );
215
+ }
216
+ this.log("INFO", "Init", `Using registered provider: ${providerName}`);
217
+ }
218
+ }
219
+ this.log("INFO", "Init", "Lixa instance initialized successfully");
220
+ }
221
+ /**
222
+ * Validates that a provider configuration has all required credentials.
223
+ *
224
+ * @param name - The provider name
225
+ * @param config - The provider configuration
226
+ * @throws Error when required fields are missing or invalid
227
+ */
228
+ validateProviderConfig(name, config) {
229
+ const requiredFields = ["clientId", "clientSecret", "redirectUri", "scopes"];
230
+ const missingFields = requiredFields.filter((field) => {
231
+ const value = config[field];
232
+ return value === void 0 || value === null || typeof value === "string" && value.trim() === "";
233
+ });
234
+ if (missingFields.length > 0) {
235
+ throw new Error(
236
+ `Provider '${name}' configuration is missing required fields: ${missingFields.join(", ")}`
237
+ );
238
+ }
239
+ if (!Array.isArray(config.scopes)) {
240
+ throw new Error(
241
+ `Provider '${name}' configuration error: 'scopes' must be an array of strings`
242
+ );
243
+ }
244
+ if (config.scopes.length === 0) {
245
+ throw new Error(
246
+ `Provider '${name}' configuration error: 'scopes' array cannot be empty`
247
+ );
248
+ }
249
+ }
250
+ /**
251
+ * Validates that a provider implementation has all required properties.
252
+ *
253
+ * @param name - The provider name
254
+ * @param provider - The provider implementation
255
+ * @throws Error when required properties are missing
256
+ */
257
+ validateProviderImplementation(name, provider) {
258
+ const requiredProps = ["authorizationEndpoint", "tokenEndpoint", "userInfoEndpoint"];
259
+ const missingProps = requiredProps.filter((prop) => {
260
+ const value = provider[prop];
261
+ return !value || typeof value !== "string" || value.trim() === "";
262
+ });
263
+ if (missingProps.length > 0) {
264
+ throw new Error(
265
+ `Provider '${name}' implementation is missing required properties: ${missingProps.join(", ")}. All IProvider implementations must define: authorizationEndpoint, tokenEndpoint, and userInfoEndpoint.`
266
+ );
267
+ }
268
+ }
269
+ /**
270
+ * Structured debug logging with standardized format.
271
+ *
272
+ * @param level - Log level (INFO, WARN, ERROR)
273
+ * @param context - Context of the log (Init, Auth, Token, Session, State)
274
+ * @param message - Log message
275
+ * @param data - Optional data to log
276
+ *
277
+ * @remarks
278
+ * Format: [Lixa] [timestamp] [level] [context] message
279
+ * Only logs when debug mode is enabled.
280
+ */
281
+ log(level, context, message, data) {
282
+ if (!this.debug) return;
283
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
284
+ const prefix = `[Lixa] [${timestamp}] [${level}] [${context}]`;
285
+ if (data !== void 0) {
286
+ console.log(`${prefix} ${message}`, data);
287
+ } else {
288
+ console.log(`${prefix} ${message}`);
289
+ }
290
+ }
291
+ /**
292
+ * Checks if a provider is configured for this instance.
293
+ * This is a type guard that narrows the provider type for use with getAuthUrl.
294
+ *
295
+ * @param provider - The provider name to check (case-insensitive)
296
+ * @returns True if the provider is configured, false otherwise
297
+ *
298
+ * @example
299
+ * ```typescript
300
+ * if (lixa.isProviderConfigured(provider)) {
301
+ * // TypeScript now knows provider is a valid ConfiguredProviderKey
302
+ * const authUrl = lixa.getAuthUrl(provider, state);
303
+ * }
304
+ * ```
305
+ */
306
+ isProviderConfigured(provider) {
307
+ const providerType = provider.toLowerCase();
308
+ return this.config.providers.hasOwnProperty(providerType);
309
+ }
310
+ /**
311
+ * Gets a provider implementation by name.
312
+ * Resolution priority: inline custom provider \> default providers \> legacy registry
313
+ *
314
+ * @param name - The provider name (case-insensitive)
315
+ * @param config - The provider configuration
316
+ * @returns The provider implementation
317
+ * @throws Error when provider is not found
318
+ */
319
+ getProvider(name, config) {
320
+ if (config.provider) {
321
+ return config.provider;
322
+ }
323
+ const lowerName = name.toLowerCase();
324
+ const defaultProvider = _Lixa.DEFAULT_PROVIDERS.get(lowerName);
325
+ if (defaultProvider) {
326
+ return defaultProvider;
327
+ }
328
+ const legacyProvider = _Lixa.CONFIGURED_PROVIDERS.get(lowerName);
329
+ if (legacyProvider) {
330
+ return legacyProvider;
331
+ }
332
+ throw new Error(
333
+ `Provider '${name}' not found. Ensure the provider is included in the configuration with a 'provider' field, or registered using Lixa.registerProvider().`
334
+ );
335
+ }
336
+ /**
337
+ * Registers custom OAuth providers for use with Lixa.
338
+ *
339
+ * @deprecated This method is maintained for backward compatibility.
340
+ * The recommended approach is to pass providers inline in the configuration:
341
+ * ```typescript
342
+ * const lixa = new Lixa({
343
+ * providers: {
344
+ * custom: {
345
+ * provider: new CustomProvider(),
346
+ * clientId: '...',
347
+ * // ...
348
+ * }
349
+ * }
350
+ * });
351
+ * ```
352
+ *
353
+ * @param providerMap - A map of provider names to IProvider implementations
354
+ *
355
+ * @example
356
+ * Legacy usage (still supported):
357
+ * ```typescript
358
+ * class CustomProvider implements IProvider {
359
+ * authorizationEndpoint = 'https://custom.com/oauth/authorize';
360
+ * tokenEndpoint = 'https://custom.com/oauth/token';
361
+ * userInfoEndpoint = 'https://custom.com/api/user';
362
+ * }
363
+ *
364
+ * Lixa.registerProvider({ custom: new CustomProvider() });
365
+ * ```
366
+ */
367
+ static registerProvider(providerMap) {
368
+ Object.entries(providerMap).forEach(([key, providerImpl]) => {
369
+ _Lixa.CONFIGURED_PROVIDERS.set(key.toLowerCase(), providerImpl);
370
+ });
371
+ }
372
+ /**
373
+ * Gets the list of registered provider names.
374
+ *
375
+ * @returns Array of registered provider names
376
+ */
377
+ static getRegisteredProviders() {
378
+ return Array.from(_Lixa.CONFIGURED_PROVIDERS.keys());
379
+ }
380
+ /**
381
+ * Creates a type-safe configuration.
382
+ *
383
+ * @deprecated This method is maintained for backward compatibility.
384
+ * You can now pass configuration directly to the Lixa constructor without this helper.
385
+ *
386
+ * @param config - Configuration object with provider settings
387
+ * @returns The same configuration object with type safety
388
+ *
389
+ * @example
390
+ * New approach (recommended):
391
+ * ```typescript
392
+ * const lixa = new Lixa({
393
+ * providers: {
394
+ * google: {
395
+ * provider: new GoogleProvider(),
396
+ * clientId: '...',
397
+ * // ...
398
+ * }
399
+ * }
400
+ * });
401
+ * ```
402
+ */
403
+ static createConfig(config) {
404
+ return config;
405
+ }
406
+ /**
407
+ * Generates a cryptographically secure random state parameter for OAuth flows.
408
+ *
409
+ * @returns A 32-character hexadecimal string
410
+ *
411
+ * @remarks
412
+ * The state parameter is used to prevent CSRF attacks in OAuth flows.
413
+ */
414
+ static generateRandomState() {
415
+ return randomBytes2(16).toString("hex");
416
+ }
417
+ /**
418
+ * Generates a cryptographically secure code verifier for PKCE flows.
419
+ *
420
+ * @returns A 64-character hexadecimal string (32 random bytes encoded as hex)
421
+ *
422
+ * @remarks
423
+ * This method implements the code verifier generation as specified in RFC 7636 (PKCE).
424
+ *
425
+ * **PKCE (Proof Key for Code Exchange)** is a security extension to OAuth 2.0 that
426
+ * prevents authorization code interception attacks. It's especially important for
427
+ * public clients (mobile apps, SPAs) but is recommended for all OAuth flows.
428
+ *
429
+ * **Generation methodology:**
430
+ * 1. Generate 32 cryptographically random bytes using Node.js crypto.randomBytes()
431
+ * 2. Encode the bytes as a hexadecimal string (64 characters)
432
+ * 3. The verifier is stored securely and used later in the token exchange
433
+ *
434
+ * **RFC 7636 Requirements:**
435
+ * - Minimum length: 43 characters
436
+ * - Maximum length: 128 characters
437
+ * - Character set: [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"
438
+ * - This implementation produces 64 hex characters, meeting the requirements
439
+ *
440
+ * The code verifier is:
441
+ * - Generated when creating the authorization URL
442
+ * - Stored in state cache with the state parameter
443
+ * - Retrieved during callback handling
444
+ * - Sent to the token endpoint to prove the client's identity
445
+ *
446
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7636 | RFC 7636 - PKCE}
447
+ * @see buildCodeChallenge for the corresponding challenge generation
448
+ *
449
+ * @internal
450
+ */
451
+ static generateCodeVerifier() {
452
+ return randomBytes2(32).toString("hex");
453
+ }
454
+ /**
455
+ * Generates a code challenge from a code verifier for PKCE flows.
456
+ *
457
+ * @param codeVerifier - The code verifier string (64 hex characters)
458
+ * @returns A base64url-encoded SHA-256 hash of the code verifier
459
+ *
460
+ * @remarks
461
+ * This method implements the code challenge generation as specified in RFC 7636 (PKCE)
462
+ * using the S256 (SHA-256) transformation method.
463
+ *
464
+ * **Challenge generation methodology:**
465
+ * 1. Hash the code verifier using SHA-256
466
+ * 2. Encode the hash as base64
467
+ * 3. Convert to base64url format (RFC 4648):
468
+ * - Replace '+' with '-'
469
+ * - Replace '/' with '_'
470
+ * - Remove trailing '=' padding
471
+ *
472
+ * **PKCE Flow:**
473
+ * 1. Client generates code_verifier (random string)
474
+ * 2. Client creates code_challenge = BASE64URL(SHA256(code_verifier))
475
+ * 3. Client sends code_challenge to authorization endpoint
476
+ * 4. Authorization server stores the code_challenge
477
+ * 5. Client sends code_verifier to token endpoint
478
+ * 6. Authorization server verifies: SHA256(code_verifier) == code_challenge
479
+ *
480
+ * **Security Benefits:**
481
+ * - Prevents authorization code interception attacks
482
+ * - Even if an attacker intercepts the authorization code, they cannot
483
+ * exchange it for tokens without the original code_verifier
484
+ * - The challenge is sent in the authorization request (public)
485
+ * - The verifier is sent in the token request (should be kept secret)
486
+ *
487
+ * **RFC 7636 Transformation Methods:**
488
+ * - plain: code_challenge = code_verifier (not recommended)
489
+ * - S256: code_challenge = BASE64URL(SHA256(code_verifier)) (recommended, used here)
490
+ *
491
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7636 | RFC 7636 - PKCE}
492
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc4648#section-5 | RFC 4648 - Base64url Encoding}
493
+ * @see generateCodeVerifier for the verifier generation
494
+ *
495
+ * @internal
496
+ */
497
+ static buildCodeChallenge(codeVerifier) {
498
+ const hash = crypto.createHash("sha256").update(codeVerifier).digest("base64");
499
+ return hash.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
500
+ }
501
+ /**
502
+ * Generates the authorization URL for the specified provider.
503
+ *
504
+ * @param provider - The provider name (must be a configured provider key)
505
+ * @param state - The state parameter for CSRF protection
506
+ * @returns The complete authorization URL to redirect users to
507
+ *
508
+ * @throws Error when the provider is not configured
509
+ *
510
+ * @example
511
+ * ```typescript
512
+ * const state = Lixa.generateRandomState();
513
+ * const authUrl = lixa.getAuthUrl('google', state);
514
+ * res.redirect(authUrl);
515
+ * ```
516
+ */
517
+ async getAuthUrl(provider, state) {
518
+ const providerType = String(provider).toLowerCase();
519
+ this.log("INFO", "Auth", `Generating authorization URL for provider: ${providerType}`);
520
+ const providerConfig = this.findProviderByType(providerType);
521
+ if (!providerConfig) {
522
+ this.log("ERROR", "Auth", `Provider '${String(provider)}' is not configured`);
523
+ throw new Error(`Provider '${String(provider)}' is not configured in this Lixa instance`);
524
+ }
525
+ const providerImpl = this.getProvider(providerType, providerConfig);
526
+ let stateValue;
527
+ let codeVerifier;
528
+ if (this.stateHandler.generateState) {
529
+ this.log("INFO", "State", "Calling custom GenerateState");
530
+ const generated = await this.stateHandler.generateState(providerType);
531
+ stateValue = state || generated.state;
532
+ codeVerifier = generated.data.codeVerifier;
533
+ const storage = this.stateHandler.stateStorage || _Lixa.LOCAL_STATE_HANDLER.stateStorage;
534
+ await storage.saveState(stateValue, generated.data, 300);
535
+ } else {
536
+ this.log("INFO", "State", "Using default state generation");
537
+ stateValue = state || randomBytes2(16).toString("hex");
538
+ codeVerifier = randomBytes2(32).toString("hex");
539
+ const storage = this.stateHandler.stateStorage || _Lixa.LOCAL_STATE_HANDLER.stateStorage;
540
+ await storage.saveState(
541
+ stateValue,
542
+ {
543
+ createdAt: Date.now(),
544
+ provider: providerType,
545
+ codeVerifier
546
+ },
547
+ 300
548
+ // 5 minutes in seconds
549
+ );
550
+ }
551
+ const codeChallenge = _Lixa.buildCodeChallenge(codeVerifier);
552
+ this.log("INFO", "State", `Saved state for provider: ${providerType}`, { state: stateValue });
553
+ const authNScopes = this.resolveAuthNScopes(providerType, providerConfig.scopes, providerImpl);
554
+ const params = new URLSearchParams({
555
+ client_id: providerConfig.clientId,
556
+ redirect_uri: providerConfig.redirectUri,
557
+ scope: authNScopes.join(" "),
558
+ state: stateValue,
559
+ response_type: "code",
560
+ code_challenge: codeChallenge,
561
+ code_challenge_method: "S256",
562
+ ...providerConfig.extraConfig
563
+ });
564
+ const authUrl = `${providerImpl.authorizationEndpoint}?${params.toString()}`;
565
+ this.log("INFO", "Auth", `Authorization URL generated successfully`, {
566
+ provider: providerType,
567
+ endpoint: providerImpl.authorizationEndpoint
568
+ });
569
+ return authUrl;
570
+ }
571
+ /**
572
+ * Restricts primary authentication scopes strictly to AuthN identity scopes.
573
+ */
574
+ resolveAuthNScopes(providerType, configuredScopes, providerImpl) {
575
+ const defaultAuthScopes = {
576
+ google: ["openid", "email", "profile"],
577
+ github: ["read:user", "user:email"],
578
+ microsoft: ["openid", "email", "profile"]
579
+ };
580
+ const standardAuthNScopes = [
581
+ "openid",
582
+ "email",
583
+ "profile",
584
+ "read:user",
585
+ "user:email",
586
+ "read:email",
587
+ "user:profile",
588
+ "user"
589
+ ];
590
+ const allowedAuthNScopes = /* @__PURE__ */ new Set([
591
+ ...standardAuthNScopes,
592
+ ...providerImpl.authScopes || [],
593
+ ...defaultAuthScopes[providerType] || []
594
+ ]);
595
+ const validAuthNScopes = (configuredScopes || []).filter((scope) => allowedAuthNScopes.has(scope));
596
+ const nonAuthNScopes = (configuredScopes || []).filter((scope) => !allowedAuthNScopes.has(scope));
597
+ if (nonAuthNScopes.length > 0) {
598
+ this.log(
599
+ "WARN",
600
+ "Auth",
601
+ `Primary authentication is strictly limited to AuthN scopes. Excluded non-AuthN resource scopes: [${nonAuthNScopes.join(
602
+ ", "
603
+ )}]. Use lixa.getResourceAuthUrl() post-login to connect resource providers.`
604
+ );
605
+ }
606
+ if (validAuthNScopes.length > 0) {
607
+ return validAuthNScopes;
608
+ }
609
+ return providerImpl.authScopes || defaultAuthScopes[providerType] || ["openid", "email", "profile"];
610
+ }
611
+ /**
612
+ * Handles the OAuth callback and creates a user session.
613
+ *
614
+ * @param provider - The provider name (must be a configured provider key)
615
+ * @param code - The authorization code from the provider
616
+ * @param state - The state parameter for validation
617
+ * @returns A Promise that resolves to the session ID
618
+ *
619
+ * @throws Error when code or state is missing/invalid, or provider is not configured
620
+ *
621
+ * @example
622
+ * ```typescript
623
+ * const sessionId = await lixa.handleCallback({
624
+ * provider: 'google',
625
+ * code: req.query.code,
626
+ * state: req.query.state
627
+ * });
628
+ * ```
629
+ */
630
+ async handleCallback({
631
+ provider,
632
+ code,
633
+ state
634
+ }) {
635
+ const providerType = String(provider).toLowerCase();
636
+ this.log("INFO", "Auth", `Handling OAuth callback for provider: ${providerType}`);
637
+ if (!code || code.trim() === "") {
638
+ this.log("ERROR", "Auth", "Invalid or missing authorization code in callback");
639
+ throw new Error("Invalid or missing code in callback");
640
+ }
641
+ if (!state || state.trim() === "") {
642
+ this.log("ERROR", "Auth", "Invalid or missing state in callback");
643
+ throw new Error("Invalid or missing state in callback");
644
+ }
645
+ this.log("INFO", "State", "Validating state parameter", { state });
646
+ const stateStorage = this.stateHandler.stateStorage || _Lixa.LOCAL_STATE_HANDLER.stateStorage;
647
+ const cachedState = await stateStorage.getState(state);
648
+ if (!cachedState) {
649
+ this.log("ERROR", "State", "State validation failed: state not found or expired", { state });
650
+ throw new Error("Invalid or expired state");
651
+ }
652
+ this.log("INFO", "State", "State validated successfully, removing from cache");
653
+ await stateStorage.deleteState(state);
654
+ const codeVerifier = cachedState.codeVerifier;
655
+ const providerConfig = this.findProviderByType(providerType);
656
+ if (!providerConfig) {
657
+ this.log("ERROR", "Auth", `Provider '${String(provider)}' is not configured`);
658
+ throw new Error(`Provider '${String(provider)}' is not configured in this Lixa instance`);
659
+ }
660
+ const providerImpl = this.getProvider(providerType, providerConfig);
661
+ this.log("INFO", "Token", `Exchanging authorization code for tokens`, { provider: providerType });
662
+ const tokens = await this.exchangeCodeForToken(
663
+ code,
664
+ providerConfig,
665
+ providerImpl,
666
+ codeVerifier
667
+ );
668
+ this.log("INFO", "Token", "Token exchange successful");
669
+ this.log("INFO", "Session", "Generating user session");
670
+ const providerMetadata = {
671
+ name: providerType,
672
+ endpoints: {
673
+ authorization: providerImpl.authorizationEndpoint,
674
+ token: providerImpl.tokenEndpoint,
675
+ userInfo: providerImpl.userInfoEndpoint
676
+ }
677
+ };
678
+ let extractedUserInfo;
679
+ try {
680
+ const { userInfo } = await extractUserInfo(tokens, providerMetadata);
681
+ extractedUserInfo = userInfo;
682
+ } catch {
683
+ }
684
+ const generateSession = this.sessionHandler.generateSession || _Lixa.LOCAL_SESSION_HANDLER.GenerateSession.bind(_Lixa.LOCAL_SESSION_HANDLER);
685
+ if (this.sessionHandler.generateSession) {
686
+ this.log("INFO", "Session", "Calling custom GenerateSession");
687
+ } else {
688
+ this.log("INFO", "Session", "Using default session generation");
689
+ }
690
+ const session = await generateSession(tokens, providerMetadata);
691
+ session.provider = session.provider || providerType;
692
+ if (extractedUserInfo?.email && !session.email) {
693
+ session.email = extractedUserInfo.email;
694
+ }
695
+ const sessionStorage = this.sessionHandler.sessionStorage || _Lixa.LOCAL_SESSION_HANDLER.sessionStorage;
696
+ const linkingConfig = this.config.accountLinking;
697
+ const mode = String(linkingConfig?.mode || "");
698
+ const isLinkByEmail = mode === "AUTO_LINK_BY_VERIFIED_EMAIL" /* AUTO_LINK_BY_VERIFIED_EMAIL */ || mode === "AUTO_LINK_BY_VERIFIED_EMAIL" || mode === "linkByEmail";
699
+ const email = extractedUserInfo?.email;
700
+ const isVerified = extractedUserInfo?.email_verified !== false;
701
+ const requireVerified = linkingConfig?.requireVerifiedEmail ?? true;
702
+ const canLink = isLinkByEmail && email && (!requireVerified || isVerified);
703
+ if (canLink && sessionStorage.getSessionByEmail) {
704
+ const existingRecord = await sessionStorage.getSessionByEmail(email);
705
+ if (existingRecord) {
706
+ this.log("INFO", "AccountLinking", `Linking provider '${providerType}' to existing session for email '${email}'`);
707
+ const { sessionId: existingSessionId, session: existingSession } = existingRecord;
708
+ existingSession.accounts = existingSession.accounts || {};
709
+ existingSession.accounts[providerType] = {
710
+ provider: providerType,
711
+ providerUserId: extractedUserInfo?.sub || extractedUserInfo?.id,
712
+ email,
713
+ accessToken: tokens.access_token,
714
+ raw: tokens,
715
+ linkedAt: Date.now()
716
+ };
717
+ existingSession.provider = providerType;
718
+ existingSession.token = tokens.access_token;
719
+ existingSession.raw = tokens;
720
+ await sessionStorage.saveSession(existingSessionId, existingSession, 86400);
721
+ return existingSessionId;
722
+ }
723
+ }
724
+ session.accounts = session.accounts || {};
725
+ session.accounts[providerType] = {
726
+ provider: providerType,
727
+ providerUserId: extractedUserInfo?.sub || extractedUserInfo?.id,
728
+ email: extractedUserInfo?.email,
729
+ accessToken: tokens.access_token,
730
+ raw: tokens,
731
+ linkedAt: Date.now()
732
+ };
733
+ const sessionId = randomBytes2(32).toString("hex");
734
+ session.id = sessionId;
735
+ this.log("INFO", "Session", "Storing session", { sessionId });
736
+ await sessionStorage.saveSession(sessionId, session, 86400);
737
+ this.log("INFO", "Session", "Session created successfully", { sessionId });
738
+ return sessionId;
739
+ }
740
+ /**
741
+ * Explicitly link a new OAuth provider account to an active session.
742
+ *
743
+ * @param params - Object containing sessionId, provider, code, and optional state
744
+ * @returns The active session ID with the newly linked provider
745
+ */
746
+ async linkAccount(params) {
747
+ const { sessionId, provider, code, state } = params;
748
+ const sessionStorage = this.sessionHandler.sessionStorage || _Lixa.LOCAL_SESSION_HANDLER.sessionStorage;
749
+ const existingSession = await sessionStorage.getSession(sessionId);
750
+ if (!existingSession) {
751
+ throw new Error("Invalid session ID. User must be authenticated to link an account.");
752
+ }
753
+ const providerType = String(provider).toLowerCase();
754
+ const providerConfig = this.findProviderByType(providerType);
755
+ if (!providerConfig) {
756
+ throw new Error(`Provider '${String(provider)}' is not configured`);
757
+ }
758
+ const providerImpl = this.getProvider(providerType, providerConfig);
759
+ let codeVerifier = randomBytes2(32).toString("hex");
760
+ if (state) {
761
+ const stateStorage = this.stateHandler.stateStorage || _Lixa.LOCAL_STATE_HANDLER.stateStorage;
762
+ const cachedState = await stateStorage.getState(state);
763
+ if (cachedState) {
764
+ codeVerifier = cachedState.codeVerifier;
765
+ await stateStorage.deleteState(state);
766
+ }
767
+ }
768
+ const tokens = await this.exchangeCodeForToken(providerType, providerConfig, providerImpl, codeVerifier);
769
+ const providerMetadata = {
770
+ name: providerType,
771
+ endpoints: {
772
+ authorization: providerImpl.authorizationEndpoint,
773
+ token: providerImpl.tokenEndpoint,
774
+ userInfo: providerImpl.userInfoEndpoint
775
+ }
776
+ };
777
+ let extractedUserInfo;
778
+ try {
779
+ const { userInfo } = await extractUserInfo(tokens, providerMetadata);
780
+ extractedUserInfo = userInfo;
781
+ } catch {
782
+ }
783
+ existingSession.accounts = existingSession.accounts || {};
784
+ existingSession.accounts[providerType] = {
785
+ provider: providerType,
786
+ providerUserId: extractedUserInfo?.sub || extractedUserInfo?.id,
787
+ email: extractedUserInfo?.email,
788
+ accessToken: tokens.access_token,
789
+ raw: tokens,
790
+ linkedAt: Date.now()
791
+ };
792
+ if (extractedUserInfo?.email && !existingSession.email) {
793
+ existingSession.email = extractedUserInfo.email;
794
+ }
795
+ await sessionStorage.saveSession(sessionId, existingSession, 86400);
796
+ return sessionId;
797
+ }
798
+ /**
799
+ * Unlinks an OAuth provider account from an active session.
800
+ *
801
+ * @param sessionId - Active session ID
802
+ * @param providerToUnlink - Provider name to unlink (e.g. 'github')
803
+ * @returns Promise resolving to true on successful unlink
804
+ */
805
+ async unlinkAccount(sessionId, providerToUnlink) {
806
+ const sessionStorage = this.sessionHandler.sessionStorage || _Lixa.LOCAL_SESSION_HANDLER.sessionStorage;
807
+ const session = await sessionStorage.getSession(sessionId);
808
+ if (!session || !session.accounts) {
809
+ throw new Error("Session not found or has no linked accounts.");
810
+ }
811
+ const linkedProviders = Object.keys(session.accounts);
812
+ if (linkedProviders.length <= 1) {
813
+ throw new Error("Cannot unlink the only authentication provider for this account.");
814
+ }
815
+ delete session.accounts[providerToUnlink.toLowerCase()];
816
+ await sessionStorage.saveSession(sessionId, session, 86400);
817
+ return true;
818
+ }
819
+ /**
820
+ * Generates an authorization URL for connecting a resource provider (AuthZ) post-login.
821
+ *
822
+ * @remarks
823
+ * Resource authorization is kept strictly separate from primary authentication (AuthN).
824
+ * Call this method after a user is authenticated to request permissions for external API access
825
+ * (e.g. GitHub repositories, Google Drive, Slack, etc.).
826
+ *
827
+ * @param params - Object containing sessionId, provider, requested resource scopes, and optional state
828
+ * @returns The authorization URL for resource consent
829
+ */
830
+ async getResourceAuthUrl(params) {
831
+ const { sessionId, provider, scopes, state } = params;
832
+ const sessionStorage = this.sessionHandler.sessionStorage || _Lixa.LOCAL_SESSION_HANDLER.sessionStorage;
833
+ const activeSession = await sessionStorage.getSession(sessionId);
834
+ if (!activeSession) {
835
+ throw new Error("Authentication required. Active session must exist to connect resource providers.");
836
+ }
837
+ const providerType = String(provider).toLowerCase();
838
+ const providerConfig = this.findProviderByType(providerType);
839
+ if (!providerConfig) {
840
+ throw new Error(`Provider '${String(provider)}' is not configured`);
841
+ }
842
+ const providerImpl = this.getProvider(providerType, providerConfig);
843
+ const stateValue = state || randomBytes2(16).toString("hex");
844
+ const codeVerifier = randomBytes2(32).toString("hex");
845
+ const storage = this.stateHandler.stateStorage || _Lixa.LOCAL_STATE_HANDLER.stateStorage;
846
+ await storage.saveState(
847
+ stateValue,
848
+ {
849
+ createdAt: Date.now(),
850
+ provider: providerType,
851
+ codeVerifier
852
+ },
853
+ 300
854
+ );
855
+ const codeChallenge = _Lixa.buildCodeChallenge(codeVerifier);
856
+ const searchParams = new URLSearchParams({
857
+ client_id: providerConfig.clientId,
858
+ redirect_uri: providerConfig.redirectUri,
859
+ scope: scopes.join(" "),
860
+ state: stateValue,
861
+ response_type: "code",
862
+ code_challenge: codeChallenge,
863
+ code_challenge_method: "S256",
864
+ ...providerConfig.extraConfig
865
+ });
866
+ return `${providerImpl.authorizationEndpoint}?${searchParams.toString()}`;
867
+ }
868
+ /**
869
+ * Handles the OAuth callback for a connected resource provider and stores resource tokens on the session.
870
+ *
871
+ * @param params - Object containing sessionId, provider, code, state, and requested scopes
872
+ * @returns Updated Session containing stored resource tokens under session.resources[provider]
873
+ */
874
+ async handleResourceCallback(params) {
875
+ const { sessionId, provider, code, state, scopes } = params;
876
+ const sessionStorage = this.sessionHandler.sessionStorage || _Lixa.LOCAL_SESSION_HANDLER.sessionStorage;
877
+ const activeSession = await sessionStorage.getSession(sessionId);
878
+ if (!activeSession) {
879
+ throw new Error("Authentication required. Active session not found for resource connection.");
880
+ }
881
+ const providerType = String(provider).toLowerCase();
882
+ const providerConfig = this.findProviderByType(providerType);
883
+ if (!providerConfig) {
884
+ throw new Error(`Provider '${String(provider)}' is not configured`);
885
+ }
886
+ const providerImpl = this.getProvider(providerType, providerConfig);
887
+ let codeVerifier = randomBytes2(32).toString("hex");
888
+ if (state) {
889
+ const stateStorage = this.stateHandler.stateStorage || _Lixa.LOCAL_STATE_HANDLER.stateStorage;
890
+ const cachedState = await stateStorage.getState(state);
891
+ if (cachedState) {
892
+ codeVerifier = cachedState.codeVerifier;
893
+ await stateStorage.deleteState(state);
894
+ }
895
+ }
896
+ const tokens = await this.exchangeCodeForToken(providerType, providerConfig, providerImpl, codeVerifier);
897
+ activeSession.resources = activeSession.resources || {};
898
+ activeSession.resources[providerType] = {
899
+ provider: providerType,
900
+ accessToken: tokens.access_token,
901
+ refreshToken: tokens.refresh_token,
902
+ scopes: scopes || (tokens.scope ? tokens.scope.split(" ") : []),
903
+ raw: tokens,
904
+ connectedAt: Date.now()
905
+ };
906
+ await sessionStorage.saveSession(sessionId, activeSession, 86400);
907
+ return activeSession;
908
+ }
909
+ /**
910
+ * Retrieves a connected resource provider token for an active session.
911
+ *
912
+ * @param sessionId - Active session ID
913
+ * @param provider - Provider identifier (e.g. 'github')
914
+ */
915
+ async getConnectedResource(sessionId, provider) {
916
+ const sessionStorage = this.sessionHandler.sessionStorage || _Lixa.LOCAL_SESSION_HANDLER.sessionStorage;
917
+ const activeSession = await sessionStorage.getSession(sessionId);
918
+ if (!activeSession || !activeSession.resources) return null;
919
+ return activeSession.resources[provider.toLowerCase()] || null;
920
+ }
921
+ /**
922
+ * Disconnects a resource provider from an active session.
923
+ *
924
+ * @param sessionId - Active session ID
925
+ * @param provider - Provider identifier to disconnect
926
+ */
927
+ async disconnectResource(sessionId, provider) {
928
+ const sessionStorage = this.sessionHandler.sessionStorage || _Lixa.LOCAL_SESSION_HANDLER.sessionStorage;
929
+ const activeSession = await sessionStorage.getSession(sessionId);
930
+ if (!activeSession || !activeSession.resources) return false;
931
+ delete activeSession.resources[provider.toLowerCase()];
932
+ await sessionStorage.saveSession(sessionId, activeSession, 86400);
933
+ return true;
934
+ }
935
+ async fetchSessionInfo(sessionId) {
936
+ const sessionStorage = this.sessionHandler.sessionStorage || _Lixa.LOCAL_SESSION_HANDLER.sessionStorage;
937
+ return await sessionStorage.getSession(sessionId);
938
+ }
939
+ async exchangeCodeForToken(code, providerConfig, providerImpl, codeVerifier) {
940
+ const body = {
941
+ client_id: providerConfig.clientId,
942
+ client_secret: providerConfig.clientSecret,
943
+ code,
944
+ redirect_uri: providerConfig.redirectUri,
945
+ grant_type: "authorization_code"
946
+ };
947
+ if (codeVerifier) {
948
+ body.code_verifier = codeVerifier;
949
+ }
950
+ const params = new URLSearchParams(body);
951
+ this.log("INFO", "Token", "Sending token exchange request", {
952
+ endpoint: providerImpl.tokenEndpoint
953
+ });
954
+ const response = await fetch(providerImpl.tokenEndpoint, {
955
+ method: "POST",
956
+ headers: {
957
+ "Content-Type": "application/x-www-form-urlencoded",
958
+ Accept: "application/json"
959
+ },
960
+ body: params.toString()
961
+ });
962
+ if (!response.ok) {
963
+ const errorBody = await response.text();
964
+ this.log("ERROR", "Token", "Token exchange failed", {
965
+ status: response.status,
966
+ statusText: response.statusText,
967
+ error: errorBody
968
+ });
969
+ throw new Error(
970
+ `Token exchange failed: ${response.status} ${response.statusText} - ${errorBody}`
971
+ );
972
+ }
973
+ this.log("INFO", "Token", "Token exchange response received successfully");
974
+ return response.json();
975
+ }
976
+ findProviderByType(providerType) {
977
+ for (const [key, value] of Object.entries(this.config.providers)) {
978
+ if (key.toLowerCase() === providerType.toLowerCase()) {
979
+ return value;
980
+ }
981
+ }
982
+ return void 0;
983
+ }
984
+ };
985
+ export {
986
+ AccountLinkingStrategy,
987
+ Lixa,
988
+ decodeIdToken,
989
+ determineProviderFromIssuer,
990
+ extractUserInfo,
991
+ fetchUserInfo
992
+ };
10
993
  //# sourceMappingURL=index.js.map