@vunexa/lixa 0.0.1-alpha.13 → 0.0.1-alpha.14
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.
- package/README.md +31 -28
- package/dist/dao/session-cache.cjs +24 -0
- package/dist/dao/state-cache.cjs +24 -0
- package/dist/dao/types.cjs +3 -0
- package/dist/index.cjs +16 -0
- package/dist/lixa.cjs +295 -0
- package/dist/models/session.cjs +34 -0
- package/dist/providers/IProvider.cjs +3 -0
- package/dist/providers/github.cjs +15 -0
- package/dist/providers/google.cjs +15 -0
- package/dist/providers/index.cjs +8 -0
- package/dist/providers-entry.cjs +27 -0
- package/dist/types.cjs +3 -0
- package/dist/utils/constants.cjs +8 -0
- package/package.json +9 -5
package/README.md
CHANGED
|
@@ -36,25 +36,25 @@ yarn add @vunexa/lixa
|
|
|
36
36
|
### 1. Configure lixa with multiple providers
|
|
37
37
|
|
|
38
38
|
```typescript
|
|
39
|
-
import { Lixa } from
|
|
39
|
+
import { Lixa } from "@vunexa/lixa";
|
|
40
40
|
|
|
41
41
|
const lixa = new Lixa({
|
|
42
42
|
providers: {
|
|
43
43
|
google: {
|
|
44
44
|
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
45
45
|
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
46
|
-
redirectUri:
|
|
47
|
-
scopes: [
|
|
46
|
+
redirectUri: "https://yourapp.com/auth/google/callback",
|
|
47
|
+
scopes: ["openid", "email", "profile"],
|
|
48
48
|
extraConfig: {
|
|
49
|
-
prompt:
|
|
50
|
-
access_type:
|
|
49
|
+
prompt: "consent",
|
|
50
|
+
access_type: "offline",
|
|
51
51
|
},
|
|
52
52
|
},
|
|
53
53
|
github: {
|
|
54
54
|
clientId: process.env.GITHUB_CLIENT_ID!,
|
|
55
55
|
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
|
|
56
|
-
redirectUri:
|
|
57
|
-
scopes: [
|
|
56
|
+
redirectUri: "https://yourapp.com/auth/github/callback",
|
|
57
|
+
scopes: ["read:user", "user:email"],
|
|
58
58
|
extraConfig: {},
|
|
59
59
|
},
|
|
60
60
|
},
|
|
@@ -64,10 +64,10 @@ const lixa = new Lixa({
|
|
|
64
64
|
createSession: async (tokenData) => {
|
|
65
65
|
// Custom session creation logic
|
|
66
66
|
return {
|
|
67
|
-
token:
|
|
68
|
-
raw: tokenData
|
|
67
|
+
token: "custom-session-token",
|
|
68
|
+
raw: tokenData,
|
|
69
69
|
};
|
|
70
|
-
}
|
|
70
|
+
},
|
|
71
71
|
},
|
|
72
72
|
});
|
|
73
73
|
```
|
|
@@ -78,10 +78,10 @@ const lixa = new Lixa({
|
|
|
78
78
|
app.get("/login", (req, res) => {
|
|
79
79
|
const provider = req.query.provider as string; // 'google' or 'github'
|
|
80
80
|
const state = lixa.generateRandomState();
|
|
81
|
-
|
|
81
|
+
|
|
82
82
|
// Store state in session for validation
|
|
83
83
|
req.session.oauthState = state;
|
|
84
|
-
|
|
84
|
+
|
|
85
85
|
const authUrl = lixa.getAuthUrl(provider.toUpperCase(), state);
|
|
86
86
|
res.redirect(authUrl);
|
|
87
87
|
});
|
|
@@ -97,7 +97,7 @@ app.get("/auth/:provider/callback", async (req, res) => {
|
|
|
97
97
|
try {
|
|
98
98
|
// Validate state parameter
|
|
99
99
|
if (state !== req.session.oauthState) {
|
|
100
|
-
throw new Error(
|
|
100
|
+
throw new Error("Invalid state parameter");
|
|
101
101
|
}
|
|
102
102
|
|
|
103
103
|
const session = await lixa.handleCallback({
|
|
@@ -110,9 +110,9 @@ app.get("/auth/:provider/callback", async (req, res) => {
|
|
|
110
110
|
res.cookie("session_token", session.token, {
|
|
111
111
|
httpOnly: true,
|
|
112
112
|
secure: true,
|
|
113
|
-
sameSite:
|
|
113
|
+
sameSite: "strict",
|
|
114
114
|
});
|
|
115
|
-
|
|
115
|
+
|
|
116
116
|
res.redirect("/dashboard");
|
|
117
117
|
} catch (error) {
|
|
118
118
|
console.error("Authentication error:", error);
|
|
@@ -128,29 +128,29 @@ app.get("/auth/:provider/callback", async (req, res) => {
|
|
|
128
128
|
You can register custom OAuth providers by implementing the `IProvider` interface:
|
|
129
129
|
|
|
130
130
|
```typescript
|
|
131
|
-
import { Lixa, IProvider } from
|
|
131
|
+
import { Lixa, IProvider } from "@vunexa/lixa";
|
|
132
132
|
|
|
133
133
|
class CustomProvider implements IProvider {
|
|
134
|
-
authorizationEndpoint =
|
|
135
|
-
tokenEndpoint =
|
|
136
|
-
userInfoEndpoint =
|
|
134
|
+
authorizationEndpoint = "https://custom-provider.com/oauth/authorize";
|
|
135
|
+
tokenEndpoint = "https://custom-provider.com/oauth/token";
|
|
136
|
+
userInfoEndpoint = "https://custom-provider.com/api/user";
|
|
137
137
|
}
|
|
138
138
|
|
|
139
139
|
// Register the custom provider
|
|
140
140
|
Lixa.registerProvider({
|
|
141
|
-
custom: new CustomProvider()
|
|
141
|
+
custom: new CustomProvider(),
|
|
142
142
|
});
|
|
143
143
|
|
|
144
144
|
// Use it in your configuration
|
|
145
145
|
const lixa = new Lixa({
|
|
146
146
|
providers: {
|
|
147
147
|
custom: {
|
|
148
|
-
clientId:
|
|
149
|
-
clientSecret:
|
|
150
|
-
redirectUri:
|
|
151
|
-
scopes: [
|
|
152
|
-
}
|
|
153
|
-
}
|
|
148
|
+
clientId: "your-client-id",
|
|
149
|
+
clientSecret: "your-client-secret",
|
|
150
|
+
redirectUri: "https://yourapp.com/auth/custom/callback",
|
|
151
|
+
scopes: ["read:user"],
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
154
|
});
|
|
155
155
|
```
|
|
156
156
|
|
|
@@ -158,8 +158,8 @@ const lixa = new Lixa({
|
|
|
158
158
|
|
|
159
159
|
```typescript
|
|
160
160
|
// Check if a provider is registered
|
|
161
|
-
if (Lixa.isProviderRegistered(
|
|
162
|
-
console.log(
|
|
161
|
+
if (Lixa.isProviderRegistered("google")) {
|
|
162
|
+
console.log("Google provider is available");
|
|
163
163
|
}
|
|
164
164
|
```
|
|
165
165
|
|
|
@@ -168,13 +168,16 @@ if (Lixa.isProviderRegistered('google')) {
|
|
|
168
168
|
### `Lixa` Class
|
|
169
169
|
|
|
170
170
|
#### Constructor
|
|
171
|
+
|
|
171
172
|
- `new Lixa(config: LixaConfig)` - Creates a new Lixa instance
|
|
172
173
|
|
|
173
174
|
#### Static Methods
|
|
175
|
+
|
|
174
176
|
- `Lixa.registerProvider(providerMap: { [key: string]: IProvider })` - Register custom providers
|
|
175
177
|
- `Lixa.isProviderRegistered(provider: string): boolean` - Check if a provider is registered
|
|
176
178
|
|
|
177
179
|
#### Instance Methods
|
|
180
|
+
|
|
178
181
|
- `generateRandomState(): string` - Generate a random state parameter for OAuth flow
|
|
179
182
|
- `getAuthUrl(provider: string, state: string): string` - Get authorization URL for a provider
|
|
180
183
|
- `handleCallback({ provider, code, state }): Promise<Session>` - Handle OAuth callback and create session
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.LocalSessionCache = void 0;
|
|
7
|
+
const node_cache_1 = __importDefault(require("node-cache"));
|
|
8
|
+
class LocalSessionCache {
|
|
9
|
+
cache;
|
|
10
|
+
constructor(defaultTtlSeconds = 600) {
|
|
11
|
+
this.cache = new node_cache_1.default({ stdTTL: defaultTtlSeconds });
|
|
12
|
+
}
|
|
13
|
+
async saveSession(state, data, expiresInSeconds) {
|
|
14
|
+
this.cache.set(state, data, expiresInSeconds);
|
|
15
|
+
}
|
|
16
|
+
async getSession(state) {
|
|
17
|
+
return this.cache.get(state) || null;
|
|
18
|
+
}
|
|
19
|
+
async deleteSession(state) {
|
|
20
|
+
this.cache.del(state);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.LocalSessionCache = LocalSessionCache;
|
|
24
|
+
//# sourceMappingURL=session-cache.js.map
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.LocalStateCache = void 0;
|
|
7
|
+
const node_cache_1 = __importDefault(require("node-cache"));
|
|
8
|
+
class LocalStateCache {
|
|
9
|
+
cache;
|
|
10
|
+
constructor(defaultTtlSeconds = 600) {
|
|
11
|
+
this.cache = new node_cache_1.default({ stdTTL: defaultTtlSeconds });
|
|
12
|
+
}
|
|
13
|
+
async saveState(state, data, expiresInSeconds) {
|
|
14
|
+
this.cache.set(state, data, expiresInSeconds);
|
|
15
|
+
}
|
|
16
|
+
async getState(state) {
|
|
17
|
+
return this.cache.get(state) || null;
|
|
18
|
+
}
|
|
19
|
+
async deleteState(state) {
|
|
20
|
+
this.cache.del(state);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.LocalStateCache = LocalStateCache;
|
|
24
|
+
//# sourceMappingURL=state-cache.js.map
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* A flexible, provider-agnostic OAuth 2.0 and OpenID Connect (OIDC) client library for backend applications.
|
|
4
|
+
*
|
|
5
|
+
* @remarks
|
|
6
|
+
* This package simplifies multi-provider authentication flows (e.g., Google, GitHub), supports extensible session management, and enables custom provider registration.
|
|
7
|
+
*
|
|
8
|
+
* @packageDocumentation
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.DefaultSessionStrategy = exports.Lixa = void 0;
|
|
12
|
+
var lixa_1 = require("./lixa");
|
|
13
|
+
Object.defineProperty(exports, "Lixa", { enumerable: true, get: function () { return lixa_1.Lixa; } });
|
|
14
|
+
var session_1 = require("./models/session");
|
|
15
|
+
Object.defineProperty(exports, "DefaultSessionStrategy", { enumerable: true, get: function () { return session_1.DefaultSessionStrategy; } });
|
|
16
|
+
//# sourceMappingURL=index.js.map
|
package/dist/lixa.cjs
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.Lixa = void 0;
|
|
7
|
+
const crypto_1 = require("crypto");
|
|
8
|
+
const state_cache_1 = require("./dao/state-cache");
|
|
9
|
+
const crypto_2 = __importDefault(require("crypto"));
|
|
10
|
+
const session_cache_1 = require("./dao/session-cache");
|
|
11
|
+
const session_1 = require("./models/session");
|
|
12
|
+
/**
|
|
13
|
+
* A flexible, provider-agnostic OAuth 2.0 and OpenID Connect (OIDC) client library.
|
|
14
|
+
*
|
|
15
|
+
* @remarks
|
|
16
|
+
* Lixa simplifies multi-provider authentication flows and supports extensible session management.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```typescript
|
|
20
|
+
* import { Lixa } from '@vunexa/lixa';
|
|
21
|
+
* import { GoogleProvider } from '@vunexa/lixa/providers';
|
|
22
|
+
*
|
|
23
|
+
* // Register providers before using them
|
|
24
|
+
* Lixa.registerProvider({ google: new GoogleProvider() });
|
|
25
|
+
*
|
|
26
|
+
* const config = Lixa.createConfig({
|
|
27
|
+
* providers: {
|
|
28
|
+
* google: {
|
|
29
|
+
* clientId: 'your-client-id',
|
|
30
|
+
* clientSecret: 'your-client-secret',
|
|
31
|
+
* redirectUri: 'https://yourapp.com/auth/google/callback',
|
|
32
|
+
* scopes: ['openid', 'email', 'profile']
|
|
33
|
+
* }
|
|
34
|
+
* }
|
|
35
|
+
* });
|
|
36
|
+
*
|
|
37
|
+
* const lixa = new Lixa(config);
|
|
38
|
+
* ```
|
|
39
|
+
*
|
|
40
|
+
* @public
|
|
41
|
+
*/
|
|
42
|
+
class Lixa {
|
|
43
|
+
static CONFIGURED_PROVIDERS = new Map();
|
|
44
|
+
static LOCAL_STATE_CACHE = new state_cache_1.LocalStateCache();
|
|
45
|
+
static LOCAL_SESSION_CACHE = new session_cache_1.LocalSessionCache();
|
|
46
|
+
static DEFAULT_SESSION_STRATEGY = new session_1.DefaultSessionStrategy();
|
|
47
|
+
config;
|
|
48
|
+
stateDao;
|
|
49
|
+
sesionDao;
|
|
50
|
+
sessionStrategy;
|
|
51
|
+
/**
|
|
52
|
+
* Creates a new Lixa instance with the provided configuration.
|
|
53
|
+
*
|
|
54
|
+
* @param config - The configuration object containing provider settings and optional session strategy
|
|
55
|
+
*/
|
|
56
|
+
constructor(config) {
|
|
57
|
+
// Validate that all providers in config are registered
|
|
58
|
+
const configuredProviders = Object.keys(config.providers);
|
|
59
|
+
const registeredProviders = Lixa.getRegisteredProviders();
|
|
60
|
+
for (const provider of configuredProviders) {
|
|
61
|
+
if (!registeredProviders.includes(provider.toLowerCase())) {
|
|
62
|
+
throw new Error(`Provider '${provider}' is not registered. Please register it first using Lixa.registerProvider()`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
this.config = config;
|
|
66
|
+
this.stateDao = config.stateDao || Lixa.LOCAL_STATE_CACHE;
|
|
67
|
+
this.sesionDao = config.sessionDao || Lixa.LOCAL_SESSION_CACHE;
|
|
68
|
+
this.sessionStrategy = config.sessionStrategy || Lixa.DEFAULT_SESSION_STRATEGY;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Checks if a provider is both registered and configured for this instance.
|
|
72
|
+
* This is a type guard that narrows the provider type for use with getAuthUrl.
|
|
73
|
+
*
|
|
74
|
+
* @param provider - The provider name to check (case-insensitive)
|
|
75
|
+
* @returns True if the provider is registered and configured, false otherwise
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* ```typescript
|
|
79
|
+
* if (lixa.isProviderConfigured(provider)) {
|
|
80
|
+
* // TypeScript now knows provider is a valid ConfiguredProviderKey
|
|
81
|
+
* const authUrl = lixa.getAuthUrl(provider, state);
|
|
82
|
+
* }
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
isProviderConfigured(provider) {
|
|
86
|
+
const providerType = provider.toLowerCase();
|
|
87
|
+
return Lixa.CONFIGURED_PROVIDERS.has(providerType) &&
|
|
88
|
+
this.config.providers.hasOwnProperty(providerType);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Registers custom OAuth providers for use with Lixa.
|
|
92
|
+
*
|
|
93
|
+
* @param providerMap - A map of provider names to IProvider implementations
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```typescript
|
|
97
|
+
* class CustomProvider implements IProvider {
|
|
98
|
+
* authorizationEndpoint = 'https://custom.com/oauth/authorize';
|
|
99
|
+
* tokenEndpoint = 'https://custom.com/oauth/token';
|
|
100
|
+
* userInfoEndpoint = 'https://custom.com/api/user';
|
|
101
|
+
* }
|
|
102
|
+
*
|
|
103
|
+
* Lixa.registerProvider({ custom: new CustomProvider() });
|
|
104
|
+
* ```
|
|
105
|
+
*/
|
|
106
|
+
static registerProvider(providerMap) {
|
|
107
|
+
Object.entries(providerMap).forEach(([key, providerImpl]) => {
|
|
108
|
+
Lixa.CONFIGURED_PROVIDERS.set(key.toLowerCase(), providerImpl);
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Gets the list of registered provider names.
|
|
113
|
+
*
|
|
114
|
+
* @returns Array of registered provider names
|
|
115
|
+
*/
|
|
116
|
+
static getRegisteredProviders() {
|
|
117
|
+
return Array.from(Lixa.CONFIGURED_PROVIDERS.keys());
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Creates a type-safe configuration that only allows registered providers.
|
|
121
|
+
*
|
|
122
|
+
* @param config - Configuration object with providers that must be registered
|
|
123
|
+
* @returns The same configuration object, but with type safety for registered providers
|
|
124
|
+
*/
|
|
125
|
+
static createConfig(config) {
|
|
126
|
+
// Validate that all providers in config are registered
|
|
127
|
+
const configuredProviders = Object.keys(config.providers);
|
|
128
|
+
const registeredProviders = Lixa.getRegisteredProviders();
|
|
129
|
+
for (const provider of configuredProviders) {
|
|
130
|
+
if (!registeredProviders.includes(provider.toLowerCase())) {
|
|
131
|
+
throw new Error(`Provider '${provider}' is not registered. Please register it first using Lixa.registerProvider()`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return config;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Generates a cryptographically secure random state parameter for OAuth flows.
|
|
138
|
+
*
|
|
139
|
+
* @returns A 32-character hexadecimal string
|
|
140
|
+
*
|
|
141
|
+
* @remarks
|
|
142
|
+
* The state parameter is used to prevent CSRF attacks in OAuth flows.
|
|
143
|
+
*/
|
|
144
|
+
static generateRandomState() {
|
|
145
|
+
return (0, crypto_1.randomBytes)(16).toString("hex");
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Generates a cryptographically secure code verifier for PKCE flows.
|
|
149
|
+
*
|
|
150
|
+
* @returns A 64-character hexadecimal string
|
|
151
|
+
*
|
|
152
|
+
* @remarks
|
|
153
|
+
* The code verifier is used in PKCE (Proof Key for Code Exchange) to enhance security.
|
|
154
|
+
*/
|
|
155
|
+
static generateCodeVerifier() {
|
|
156
|
+
return (0, crypto_1.randomBytes)(32).toString("hex");
|
|
157
|
+
}
|
|
158
|
+
static buildCodeChallenge(codeVerifier) {
|
|
159
|
+
const hash = crypto_2.default
|
|
160
|
+
.createHash("sha256")
|
|
161
|
+
.update(codeVerifier)
|
|
162
|
+
.digest("base64");
|
|
163
|
+
// Convert to base64url
|
|
164
|
+
return hash.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Generates the authorization URL for the specified provider.
|
|
168
|
+
*
|
|
169
|
+
* @param provider - The provider name (must be a configured provider key)
|
|
170
|
+
* @param state - The state parameter for CSRF protection
|
|
171
|
+
* @returns The complete authorization URL to redirect users to
|
|
172
|
+
*
|
|
173
|
+
* @throws Error when the provider is not configured
|
|
174
|
+
*
|
|
175
|
+
* @example
|
|
176
|
+
* ```typescript
|
|
177
|
+
* const state = Lixa.generateRandomState();
|
|
178
|
+
* const authUrl = lixa.getAuthUrl('google', state);
|
|
179
|
+
* res.redirect(authUrl);
|
|
180
|
+
* ```
|
|
181
|
+
*/
|
|
182
|
+
getAuthUrl(provider, state) {
|
|
183
|
+
const providerType = String(provider).toLowerCase();
|
|
184
|
+
const providerConfig = this.findProviderByType(providerType);
|
|
185
|
+
const providerImpl = Lixa.CONFIGURED_PROVIDERS.get(providerType);
|
|
186
|
+
if (!providerConfig || !providerImpl) {
|
|
187
|
+
throw new Error(`Provider ${providerType} not configured`);
|
|
188
|
+
}
|
|
189
|
+
const codeVerifier = Lixa.generateCodeVerifier();
|
|
190
|
+
const codeChallenge = Lixa.buildCodeChallenge(codeVerifier);
|
|
191
|
+
// Cache the state paramaeter with TTL of 5 minutes (300 seconds)
|
|
192
|
+
// We dont care about value. we are onl interested in key existence
|
|
193
|
+
this.stateDao.saveState(state, {
|
|
194
|
+
createdAt: Date.now(),
|
|
195
|
+
provider: providerType,
|
|
196
|
+
codeVerifier,
|
|
197
|
+
}, 300 // 5 minutes in seconds
|
|
198
|
+
);
|
|
199
|
+
const params = new URLSearchParams({
|
|
200
|
+
client_id: providerConfig.clientId,
|
|
201
|
+
redirect_uri: providerConfig.redirectUri,
|
|
202
|
+
scope: providerConfig.scopes.join(" "),
|
|
203
|
+
state,
|
|
204
|
+
response_type: "code",
|
|
205
|
+
code_challenge: codeChallenge,
|
|
206
|
+
code_challenge_method: "S256",
|
|
207
|
+
...providerConfig.extraConfig,
|
|
208
|
+
});
|
|
209
|
+
return `${providerImpl.authorizationEndpoint}?${params.toString()}`;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Handles the OAuth callback and creates a user session.
|
|
213
|
+
*
|
|
214
|
+
* @param provider - The provider name (must be a configured provider key)
|
|
215
|
+
* @param code - The authorization code from the provider
|
|
216
|
+
* @param state - The state parameter for validation
|
|
217
|
+
* @returns A Promise that resolves to the session ID
|
|
218
|
+
*
|
|
219
|
+
* @throws Error when code or state is missing/invalid, or provider is not configured
|
|
220
|
+
*
|
|
221
|
+
* @example
|
|
222
|
+
* ```typescript
|
|
223
|
+
* const sessionId = await lixa.handleCallback({
|
|
224
|
+
* provider: 'google',
|
|
225
|
+
* code: req.query.code,
|
|
226
|
+
* state: req.query.state
|
|
227
|
+
* });
|
|
228
|
+
* ```
|
|
229
|
+
*/
|
|
230
|
+
async handleCallback({ provider, code, state, }) {
|
|
231
|
+
if (!code || code.trim() === "") {
|
|
232
|
+
throw new Error("Invalid or missing code in callback");
|
|
233
|
+
}
|
|
234
|
+
if (!state || state.trim() === "") {
|
|
235
|
+
throw new Error("Invalid or missing state in callback");
|
|
236
|
+
}
|
|
237
|
+
//Validate state here
|
|
238
|
+
const cachedState = await this.stateDao.getState(state);
|
|
239
|
+
if (!cachedState) {
|
|
240
|
+
throw new Error("Invalid or expired state");
|
|
241
|
+
}
|
|
242
|
+
// State is valid, remove it from cache to prevent reuse
|
|
243
|
+
await this.stateDao.deleteState(state);
|
|
244
|
+
//Get code verifier from cached state
|
|
245
|
+
const codeVerifier = cachedState.codeVerifier;
|
|
246
|
+
const providerType = String(provider).toLowerCase();
|
|
247
|
+
const providerConfig = this.findProviderByType(providerType);
|
|
248
|
+
const providerImpl = Lixa.CONFIGURED_PROVIDERS.get(providerType);
|
|
249
|
+
if (!providerConfig || !providerImpl) {
|
|
250
|
+
throw new Error(`Provider ${String(provider)} not configured`);
|
|
251
|
+
}
|
|
252
|
+
// Exchange code for tokens and fetch user info here.
|
|
253
|
+
const tokens = await this.exchangeCodeForToken(code, providerConfig, providerImpl, codeVerifier);
|
|
254
|
+
const session = await this.sessionStrategy.createSession(tokens);
|
|
255
|
+
// Generate unique session ID
|
|
256
|
+
const sessionId = (0, crypto_1.randomBytes)(32).toString("hex");
|
|
257
|
+
// Store session with 24 hour TTL (86400 seconds)
|
|
258
|
+
await this.sesionDao.saveSession(sessionId, session, 86400);
|
|
259
|
+
return sessionId;
|
|
260
|
+
}
|
|
261
|
+
fetchSessionInfo(sessionId) {
|
|
262
|
+
return this.sesionDao.getSession(sessionId);
|
|
263
|
+
}
|
|
264
|
+
async exchangeCodeForToken(code, providerConfig, providerImpl, codeVerifier) {
|
|
265
|
+
// Build the request body
|
|
266
|
+
const body = {
|
|
267
|
+
client_id: providerConfig.clientId,
|
|
268
|
+
client_secret: providerConfig.clientSecret,
|
|
269
|
+
code,
|
|
270
|
+
redirect_uri: providerConfig.redirectUri,
|
|
271
|
+
grant_type: "authorization_code",
|
|
272
|
+
};
|
|
273
|
+
if (codeVerifier) {
|
|
274
|
+
body.code_verifier = codeVerifier;
|
|
275
|
+
}
|
|
276
|
+
const params = new URLSearchParams(body);
|
|
277
|
+
const response = await fetch(providerImpl.tokenEndpoint, {
|
|
278
|
+
method: "POST",
|
|
279
|
+
headers: {
|
|
280
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
281
|
+
Accept: "application/json",
|
|
282
|
+
},
|
|
283
|
+
body: params.toString(),
|
|
284
|
+
});
|
|
285
|
+
if (!response.ok) {
|
|
286
|
+
throw new Error(`Token exchange failed: ${response.status} ${response.statusText}`);
|
|
287
|
+
}
|
|
288
|
+
return response.json();
|
|
289
|
+
}
|
|
290
|
+
findProviderByType(providerType) {
|
|
291
|
+
return this.config.providers[providerType];
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
exports.Lixa = Lixa;
|
|
295
|
+
//# sourceMappingURL=lixa.js.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DefaultSessionStrategy = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Default session strategy that works with any OAuth provider.
|
|
6
|
+
* Extracts common token information and creates a standardized session.
|
|
7
|
+
*
|
|
8
|
+
* @public
|
|
9
|
+
*/
|
|
10
|
+
class DefaultSessionStrategy {
|
|
11
|
+
/**
|
|
12
|
+
* Creates a session from OAuth token data.
|
|
13
|
+
* Handles common OAuth token formats and extracts the access token.
|
|
14
|
+
*
|
|
15
|
+
* @param tokenData - The token data received from the OAuth provider
|
|
16
|
+
* @returns A Promise that resolves to a Session object
|
|
17
|
+
*/
|
|
18
|
+
async createSession(tokenData) {
|
|
19
|
+
// Extract access token from various possible formats
|
|
20
|
+
const accessToken = tokenData.access_token ||
|
|
21
|
+
tokenData.accessToken ||
|
|
22
|
+
tokenData.token ||
|
|
23
|
+
tokenData;
|
|
24
|
+
if (!accessToken || typeof accessToken !== 'string') {
|
|
25
|
+
throw new Error('No valid access token found in OAuth response');
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
token: accessToken,
|
|
29
|
+
raw: tokenData,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
exports.DefaultSessionStrategy = DefaultSessionStrategy;
|
|
34
|
+
//# sourceMappingURL=session.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GithubProvider = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* GitHub OAuth provider implementation
|
|
6
|
+
* @public
|
|
7
|
+
*/
|
|
8
|
+
class GithubProvider {
|
|
9
|
+
providerType = "GITHUB";
|
|
10
|
+
authorizationEndpoint = "https://github.com/login/oauth/authorize";
|
|
11
|
+
tokenEndpoint = "https://github.com/login/oauth/access_token";
|
|
12
|
+
userInfoEndpoint = "https://api.github.com/user";
|
|
13
|
+
}
|
|
14
|
+
exports.GithubProvider = GithubProvider;
|
|
15
|
+
//# sourceMappingURL=github.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GoogleProvider = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Google OAuth provider implementation
|
|
6
|
+
* @public
|
|
7
|
+
*/
|
|
8
|
+
class GoogleProvider {
|
|
9
|
+
providerType = "GOOGLE";
|
|
10
|
+
authorizationEndpoint = "https://accounts.google.com/o/oauth2/v2/auth";
|
|
11
|
+
tokenEndpoint = "https://oauth2.googleapis.com/token";
|
|
12
|
+
userInfoEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo";
|
|
13
|
+
}
|
|
14
|
+
exports.GoogleProvider = GoogleProvider;
|
|
15
|
+
//# sourceMappingURL=google.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GoogleProvider = exports.GithubProvider = void 0;
|
|
4
|
+
var github_1 = require("./github");
|
|
5
|
+
Object.defineProperty(exports, "GithubProvider", { enumerable: true, get: function () { return github_1.GithubProvider; } });
|
|
6
|
+
var google_1 = require("./google");
|
|
7
|
+
Object.defineProperty(exports, "GoogleProvider", { enumerable: true, get: function () { return google_1.GoogleProvider; } });
|
|
8
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Built-in OAuth providers for Lixa
|
|
4
|
+
*
|
|
5
|
+
* @remarks
|
|
6
|
+
* Import and register these providers before using them in your Lixa configuration.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import { Lixa } from '@vunexa/lixa';
|
|
11
|
+
* import { GoogleProvider, GithubProvider } from '@vunexa/lixa/providers';
|
|
12
|
+
*
|
|
13
|
+
* // Register the providers you want to use
|
|
14
|
+
* Lixa.registerProvider({
|
|
15
|
+
* google: new GoogleProvider(),
|
|
16
|
+
* github: new GithubProvider(),
|
|
17
|
+
* });
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* @packageDocumentation
|
|
21
|
+
*/
|
|
22
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
+
exports.GithubProvider = exports.GoogleProvider = void 0;
|
|
24
|
+
var providers_1 = require("./providers");
|
|
25
|
+
Object.defineProperty(exports, "GoogleProvider", { enumerable: true, get: function () { return providers_1.GoogleProvider; } });
|
|
26
|
+
Object.defineProperty(exports, "GithubProvider", { enumerable: true, get: function () { return providers_1.GithubProvider; } });
|
|
27
|
+
//# sourceMappingURL=providers-entry.js.map
|
package/dist/types.cjs
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GITHUB = exports.GOOGLE = void 0;
|
|
4
|
+
const GOOGLE = "google";
|
|
5
|
+
exports.GOOGLE = GOOGLE;
|
|
6
|
+
const GITHUB = "github";
|
|
7
|
+
exports.GITHUB = GITHUB;
|
|
8
|
+
//# sourceMappingURL=constants.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vunexa/lixa",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.14",
|
|
4
4
|
"description": "Lixa is a flexible, provider-agnostic OAuth and OpenID Connect (OIDC) client library that simplifies multi-provider authentication flows. It supports seamless integration with providers like Google and GitHub, offers extensible session management, and enables dynamic provider resolution based on callback URLs.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"oauth",
|
|
@@ -14,16 +14,20 @@
|
|
|
14
14
|
"exports": {
|
|
15
15
|
".": {
|
|
16
16
|
"types": "./dist/export-types/index.d.ts",
|
|
17
|
-
"import": "./dist/index.js"
|
|
17
|
+
"import": "./dist/index.js",
|
|
18
|
+
"require": "./dist/index.cjs"
|
|
18
19
|
},
|
|
19
20
|
"./providers": {
|
|
20
21
|
"types": "./dist/export-types/providers.d.ts",
|
|
21
|
-
"import": "./dist/providers-entry.js"
|
|
22
|
+
"import": "./dist/providers-entry.js",
|
|
23
|
+
"require": "./dist/providers-entry.cjs"
|
|
22
24
|
}
|
|
23
25
|
},
|
|
24
26
|
"scripts": {
|
|
25
|
-
"build": "
|
|
26
|
-
"
|
|
27
|
+
"build": "npm run build:esm && npm run build:cjs && npm run test && api-extractor run --local && api-extractor run --local --config api-extractor-providers.json",
|
|
28
|
+
"build:esm": "tsc",
|
|
29
|
+
"build:cjs": "tsc --module commonjs --outDir dist-cjs && node scripts/rename-cjs.cjs",
|
|
30
|
+
"clean": "rm -rf dist dist-cjs",
|
|
27
31
|
"prepublishOnly": "npm run clean && npm run build",
|
|
28
32
|
"lint": "eslint src/**/*.ts",
|
|
29
33
|
"lint:fix": "eslint src/**/*.ts --fix",
|