@leanmcp/auth 0.1.1 → 0.3.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.
package/dist/index.js CHANGED
@@ -32,11 +32,19 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
33
 
34
34
  // src/decorators.ts
35
- function Authenticated(authProvider) {
35
+ function getAuthUser() {
36
+ return authUserStorage.getStore();
37
+ }
38
+ function Authenticated(authProvider, options) {
39
+ const authOptions = {
40
+ getUser: true,
41
+ ...options
42
+ };
36
43
  return function(target, propertyKey, descriptor) {
37
44
  if (!propertyKey && !descriptor) {
38
45
  Reflect.defineMetadata("auth:provider", authProvider, target);
39
46
  Reflect.defineMetadata("auth:required", true, target);
47
+ Reflect.defineMetadata("auth:options", authOptions, target);
40
48
  const prototype = target.prototype;
41
49
  const methodNames = Object.getOwnPropertyNames(prototype).filter((name) => name !== "constructor" && typeof prototype[name] === "function");
42
50
  for (const methodName of methodNames) {
@@ -45,7 +53,8 @@ function Authenticated(authProvider) {
45
53
  const originalMethod = originalDescriptor.value;
46
54
  Reflect.defineMetadata("auth:provider", authProvider, originalMethod);
47
55
  Reflect.defineMetadata("auth:required", true, originalMethod);
48
- prototype[methodName] = createAuthenticatedMethod(originalMethod, authProvider);
56
+ Reflect.defineMetadata("auth:options", authOptions, originalMethod);
57
+ prototype[methodName] = createAuthenticatedMethod(originalMethod, authProvider, authOptions);
49
58
  copyMetadata(originalMethod, prototype[methodName]);
50
59
  }
51
60
  }
@@ -55,14 +64,15 @@ function Authenticated(authProvider) {
55
64
  const originalMethod = descriptor.value;
56
65
  Reflect.defineMetadata("auth:provider", authProvider, originalMethod);
57
66
  Reflect.defineMetadata("auth:required", true, originalMethod);
58
- descriptor.value = createAuthenticatedMethod(originalMethod, authProvider);
67
+ Reflect.defineMetadata("auth:options", authOptions, originalMethod);
68
+ descriptor.value = createAuthenticatedMethod(originalMethod, authProvider, authOptions);
59
69
  copyMetadata(originalMethod, descriptor.value);
60
70
  return descriptor;
61
71
  }
62
72
  throw new Error("@Authenticated can only be applied to classes or methods");
63
73
  };
64
74
  }
65
- function createAuthenticatedMethod(originalMethod, authProvider) {
75
+ function createAuthenticatedMethod(originalMethod, authProvider, options) {
66
76
  return async function(args, meta) {
67
77
  const token = meta?.authorization?.token;
68
78
  if (!token) {
@@ -79,9 +89,29 @@ function createAuthenticatedMethod(originalMethod, authProvider) {
79
89
  }
80
90
  throw new AuthenticationError(`Token verification failed: ${error instanceof Error ? error.message : String(error)}`, "VERIFICATION_FAILED");
81
91
  }
82
- return originalMethod.apply(this, [
83
- args
84
- ]);
92
+ if (options.getUser !== false) {
93
+ try {
94
+ const user = await authProvider.getUser(token);
95
+ return await authUserStorage.run(user, async () => {
96
+ return await originalMethod.apply(this, [
97
+ args
98
+ ]);
99
+ });
100
+ } catch (error) {
101
+ console.warn("Failed to fetch user information:", error);
102
+ return await authUserStorage.run(void 0, async () => {
103
+ return await originalMethod.apply(this, [
104
+ args
105
+ ]);
106
+ });
107
+ }
108
+ } else {
109
+ return await authUserStorage.run(void 0, async () => {
110
+ return await originalMethod.apply(this, [
111
+ args
112
+ ]);
113
+ });
114
+ }
85
115
  };
86
116
  }
87
117
  function copyMetadata(source, target) {
@@ -108,11 +138,23 @@ function isAuthenticationRequired(target) {
108
138
  function getAuthProvider(target) {
109
139
  return Reflect.getMetadata("auth:provider", target);
110
140
  }
111
- var import_reflect_metadata, AuthenticationError;
141
+ var import_reflect_metadata, import_async_hooks, authUserStorage, AuthenticationError;
112
142
  var init_decorators = __esm({
113
143
  "src/decorators.ts"() {
114
144
  "use strict";
115
145
  import_reflect_metadata = require("reflect-metadata");
146
+ import_async_hooks = require("async_hooks");
147
+ authUserStorage = new import_async_hooks.AsyncLocalStorage();
148
+ __name(getAuthUser, "getAuthUser");
149
+ if (typeof globalThis !== "undefined" && !Object.getOwnPropertyDescriptor(globalThis, "authUser")) {
150
+ Object.defineProperty(globalThis, "authUser", {
151
+ get() {
152
+ return authUserStorage.getStore();
153
+ },
154
+ configurable: true,
155
+ enumerable: false
156
+ });
157
+ }
116
158
  AuthenticationError = class extends Error {
117
159
  static {
118
160
  __name(this, "AuthenticationError");
@@ -280,6 +322,231 @@ var init_cognito = __esm({
280
322
  }
281
323
  });
282
324
 
325
+ // src/providers/auth0.ts
326
+ var auth0_exports = {};
327
+ __export(auth0_exports, {
328
+ AuthAuth0: () => AuthAuth0
329
+ });
330
+ var import_axios2, import_jsonwebtoken2, import_jwk_to_pem2, AuthAuth0;
331
+ var init_auth0 = __esm({
332
+ "src/providers/auth0.ts"() {
333
+ "use strict";
334
+ import_axios2 = __toESM(require("axios"));
335
+ import_jsonwebtoken2 = __toESM(require("jsonwebtoken"));
336
+ import_jwk_to_pem2 = __toESM(require("jwk-to-pem"));
337
+ init_index();
338
+ AuthAuth0 = class extends AuthProviderBase {
339
+ static {
340
+ __name(this, "AuthAuth0");
341
+ }
342
+ domain = "";
343
+ clientId = "";
344
+ clientSecret = "";
345
+ audience = "";
346
+ scopes = "openid profile email offline_access";
347
+ jwksCache = null;
348
+ async init(config) {
349
+ this.domain = config?.domain || process.env.AUTH0_DOMAIN || "";
350
+ this.clientId = config?.clientId || process.env.AUTH0_CLIENT_ID || "";
351
+ this.clientSecret = config?.clientSecret || process.env.AUTH0_CLIENT_SECRET || "";
352
+ this.audience = config?.audience || process.env.AUTH0_AUDIENCE || "";
353
+ this.scopes = config?.scopes || this.scopes;
354
+ if (!this.domain || !this.clientId || !this.audience) {
355
+ throw new Error("Auth0 config missing: domain, clientId, and audience are required");
356
+ }
357
+ }
358
+ async refreshToken(refreshToken) {
359
+ const url = `https://${this.domain}/oauth/token`;
360
+ const payload = {
361
+ grant_type: "refresh_token",
362
+ client_id: this.clientId,
363
+ refresh_token: refreshToken,
364
+ audience: this.audience,
365
+ scope: this.scopes
366
+ };
367
+ if (this.clientSecret) {
368
+ payload.client_secret = this.clientSecret;
369
+ }
370
+ const { data } = await import_axios2.default.post(url, payload, {
371
+ headers: {
372
+ "Content-Type": "application/json"
373
+ }
374
+ });
375
+ return data;
376
+ }
377
+ async verifyToken(token) {
378
+ try {
379
+ await this.verifyJwt(token);
380
+ return true;
381
+ } catch (error) {
382
+ if (error instanceof Error) {
383
+ if (error.message.includes("jwt expired")) throw new Error("Token has expired");
384
+ if (error.message.includes("invalid signature")) throw new Error("Invalid token signature");
385
+ if (error.message.includes("jwt malformed")) throw new Error("Malformed token");
386
+ if (error.message.includes("invalid issuer")) throw new Error("Invalid token issuer");
387
+ throw error;
388
+ }
389
+ return false;
390
+ }
391
+ }
392
+ async getUser(idToken) {
393
+ const decoded = import_jsonwebtoken2.default.decode(idToken);
394
+ if (!decoded) throw new Error("Invalid ID token");
395
+ return {
396
+ sub: decoded.sub,
397
+ email: decoded.email,
398
+ email_verified: decoded.email_verified,
399
+ name: decoded.name,
400
+ attributes: decoded
401
+ };
402
+ }
403
+ async fetchJWKS() {
404
+ if (!this.jwksCache) {
405
+ const jwksUri = `https://${this.domain}/.well-known/jwks.json`;
406
+ const { data } = await import_axios2.default.get(jwksUri);
407
+ this.jwksCache = data.keys;
408
+ }
409
+ return this.jwksCache;
410
+ }
411
+ async verifyJwt(token) {
412
+ const decoded = import_jsonwebtoken2.default.decode(token, {
413
+ complete: true
414
+ });
415
+ if (!decoded) throw new Error("Invalid token");
416
+ const jwks = await this.fetchJWKS();
417
+ const key = jwks.find((k) => k.kid === decoded.header.kid);
418
+ if (!key) throw new Error("Signing key not found in JWKS");
419
+ const pem = (0, import_jwk_to_pem2.default)(key);
420
+ return import_jsonwebtoken2.default.verify(token, pem, {
421
+ algorithms: [
422
+ "RS256"
423
+ ],
424
+ issuer: `https://${this.domain}/`
425
+ });
426
+ }
427
+ };
428
+ }
429
+ });
430
+
431
+ // src/providers/clerk.ts
432
+ var clerk_exports = {};
433
+ __export(clerk_exports, {
434
+ AuthClerk: () => AuthClerk
435
+ });
436
+ var import_axios3, import_jsonwebtoken3, import_jwk_to_pem3, AuthClerk;
437
+ var init_clerk = __esm({
438
+ "src/providers/clerk.ts"() {
439
+ "use strict";
440
+ import_axios3 = __toESM(require("axios"));
441
+ import_jsonwebtoken3 = __toESM(require("jsonwebtoken"));
442
+ import_jwk_to_pem3 = __toESM(require("jwk-to-pem"));
443
+ init_index();
444
+ AuthClerk = class extends AuthProviderBase {
445
+ static {
446
+ __name(this, "AuthClerk");
447
+ }
448
+ clerkFrontendApi = "";
449
+ clerkSecretKey = "";
450
+ clerkJWKSUrl = "";
451
+ clerkIssuer = "";
452
+ jwksCache = null;
453
+ mode = "session";
454
+ oauthTokenUrl = "";
455
+ clientId;
456
+ clientSecret;
457
+ redirectUri;
458
+ /**
459
+ * Initialize Clerk Auth Provider
460
+ */
461
+ async init(config) {
462
+ this.clerkFrontendApi = config?.frontendApi || process.env.CLERK_FRONTEND_API || "";
463
+ this.clerkSecretKey = config?.secretKey || process.env.CLERK_SECRET_KEY || "";
464
+ if (!this.clerkFrontendApi || !this.clerkSecretKey) {
465
+ throw new Error("Missing Clerk configuration: frontendApi and secretKey are required");
466
+ }
467
+ this.clerkIssuer = `https://${this.clerkFrontendApi}`;
468
+ this.clerkJWKSUrl = `${this.clerkIssuer}/.well-known/jwks.json`;
469
+ if (config?.clientId && config?.clientSecret && config?.redirectUri) {
470
+ this.mode = "oauth";
471
+ this.clientId = config.clientId;
472
+ this.clientSecret = config.clientSecret;
473
+ this.redirectUri = config.redirectUri;
474
+ this.oauthTokenUrl = `${this.clerkIssuer}/oauth/token`;
475
+ }
476
+ }
477
+ /**
478
+ * Refresh tokens (OAuth mode only)
479
+ */
480
+ async refreshToken(refreshToken) {
481
+ if (this.mode !== "oauth") {
482
+ throw new Error("Clerk is in Session Mode: refresh tokens are not supported. Enable OAuth mode.");
483
+ }
484
+ const payload = {
485
+ grant_type: "refresh_token",
486
+ refresh_token: refreshToken,
487
+ client_id: this.clientId,
488
+ client_secret: this.clientSecret,
489
+ redirect_uri: this.redirectUri
490
+ };
491
+ const { data } = await import_axios3.default.post(this.oauthTokenUrl, payload, {
492
+ headers: {
493
+ "Content-Type": "application/json"
494
+ }
495
+ });
496
+ return data;
497
+ }
498
+ /**
499
+ * Verify JWT using JWKS
500
+ */
501
+ async verifyToken(token) {
502
+ await this.verifyJwt(token);
503
+ return true;
504
+ }
505
+ /**
506
+ * Extract user data from ID token
507
+ */
508
+ async getUser(idToken) {
509
+ const decoded = import_jsonwebtoken3.default.decode(idToken);
510
+ if (!decoded) throw new Error("Invalid ID token");
511
+ return {
512
+ sub: decoded.sub,
513
+ email: decoded.email,
514
+ email_verified: decoded.email_verified,
515
+ first_name: decoded.given_name,
516
+ last_name: decoded.family_name,
517
+ attributes: decoded
518
+ };
519
+ }
520
+ /**
521
+ * JWT verification using JWKS
522
+ */
523
+ async verifyJwt(token) {
524
+ const decoded = import_jsonwebtoken3.default.decode(token, {
525
+ complete: true
526
+ });
527
+ if (!decoded) throw new Error("Invalid token");
528
+ const jwks = await this.fetchJWKS();
529
+ const key = jwks.find((k) => k.kid === decoded.header.kid);
530
+ if (!key) throw new Error("Signing key not found in JWKS");
531
+ const pem = (0, import_jwk_to_pem3.default)(key);
532
+ return import_jsonwebtoken3.default.verify(token, pem, {
533
+ algorithms: [
534
+ "RS256"
535
+ ],
536
+ issuer: this.clerkIssuer
537
+ });
538
+ }
539
+ async fetchJWKS() {
540
+ if (!this.jwksCache) {
541
+ const { data } = await import_axios3.default.get(this.clerkJWKSUrl);
542
+ this.jwksCache = data.keys;
543
+ }
544
+ return this.jwksCache;
545
+ }
546
+ };
547
+ }
548
+ });
549
+
283
550
  // src/index.ts
284
551
  var index_exports = {};
285
552
  __export(index_exports, {
@@ -288,6 +555,7 @@ __export(index_exports, {
288
555
  Authenticated: () => Authenticated,
289
556
  AuthenticationError: () => AuthenticationError,
290
557
  getAuthProvider: () => getAuthProvider,
558
+ getAuthUser: () => getAuthUser,
291
559
  isAuthenticationRequired: () => isAuthenticationRequired
292
560
  });
293
561
  module.exports = __toCommonJS(index_exports);
@@ -325,13 +593,18 @@ var init_index = __esm({
325
593
  await this.providerInstance.init(finalConfig);
326
594
  break;
327
595
  }
328
- // Add more providers here in the future
329
- // case 'clerk': {
330
- // const { AuthClerk } = await import('./providers/clerk');
331
- // this.providerInstance = new AuthClerk();
332
- // await this.providerInstance.init(finalConfig);
333
- // break;
334
- // }
596
+ case "auth0": {
597
+ const { AuthAuth0: AuthAuth02 } = await Promise.resolve().then(() => (init_auth0(), auth0_exports));
598
+ this.providerInstance = new AuthAuth02();
599
+ await this.providerInstance.init(finalConfig);
600
+ break;
601
+ }
602
+ case "clerk": {
603
+ const { AuthClerk: AuthClerk2 } = await Promise.resolve().then(() => (init_clerk(), clerk_exports));
604
+ this.providerInstance = new AuthClerk2();
605
+ await this.providerInstance.init(finalConfig);
606
+ break;
607
+ }
335
608
  default:
336
609
  throw new Error(`Unsupported auth provider: ${this.providerType}. Supported providers: cognito`);
337
610
  }
@@ -380,5 +653,6 @@ init_index();
380
653
  Authenticated,
381
654
  AuthenticationError,
382
655
  getAuthProvider,
656
+ getAuthUser,
383
657
  isAuthenticationRequired
384
658
  });
package/dist/index.mjs CHANGED
@@ -4,13 +4,15 @@ import {
4
4
  Authenticated,
5
5
  AuthenticationError,
6
6
  getAuthProvider,
7
+ getAuthUser,
7
8
  isAuthenticationRequired
8
- } from "./chunk-NALGJYQB.mjs";
9
+ } from "./chunk-EVD2TRPR.mjs";
9
10
  export {
10
11
  AuthProvider,
11
12
  AuthProviderBase,
12
13
  Authenticated,
13
14
  AuthenticationError,
14
15
  getAuthProvider,
16
+ getAuthUser,
15
17
  isAuthenticationRequired
16
18
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leanmcp/auth",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Authentication and identity module supporting multiple providers",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -1,193 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
-
4
- // src/index.ts
5
- import "reflect-metadata";
6
-
7
- // src/decorators.ts
8
- import "reflect-metadata";
9
- var AuthenticationError = class extends Error {
10
- static {
11
- __name(this, "AuthenticationError");
12
- }
13
- code;
14
- constructor(message, code) {
15
- super(message), this.code = code;
16
- this.name = "AuthenticationError";
17
- }
18
- };
19
- function Authenticated(authProvider) {
20
- return function(target, propertyKey, descriptor) {
21
- if (!propertyKey && !descriptor) {
22
- Reflect.defineMetadata("auth:provider", authProvider, target);
23
- Reflect.defineMetadata("auth:required", true, target);
24
- const prototype = target.prototype;
25
- const methodNames = Object.getOwnPropertyNames(prototype).filter((name) => name !== "constructor" && typeof prototype[name] === "function");
26
- for (const methodName of methodNames) {
27
- const originalDescriptor = Object.getOwnPropertyDescriptor(prototype, methodName);
28
- if (originalDescriptor && typeof originalDescriptor.value === "function") {
29
- const originalMethod = originalDescriptor.value;
30
- Reflect.defineMetadata("auth:provider", authProvider, originalMethod);
31
- Reflect.defineMetadata("auth:required", true, originalMethod);
32
- prototype[methodName] = createAuthenticatedMethod(originalMethod, authProvider);
33
- copyMetadata(originalMethod, prototype[methodName]);
34
- }
35
- }
36
- return target;
37
- }
38
- if (descriptor && typeof descriptor.value === "function") {
39
- const originalMethod = descriptor.value;
40
- Reflect.defineMetadata("auth:provider", authProvider, originalMethod);
41
- Reflect.defineMetadata("auth:required", true, originalMethod);
42
- descriptor.value = createAuthenticatedMethod(originalMethod, authProvider);
43
- copyMetadata(originalMethod, descriptor.value);
44
- return descriptor;
45
- }
46
- throw new Error("@Authenticated can only be applied to classes or methods");
47
- };
48
- }
49
- __name(Authenticated, "Authenticated");
50
- function createAuthenticatedMethod(originalMethod, authProvider) {
51
- return async function(...args) {
52
- const firstArg = args[0];
53
- let token;
54
- let cleanedArgs = args;
55
- if (firstArg && typeof firstArg === "object") {
56
- token = firstArg.token;
57
- const { token: _, ...restArgs } = firstArg;
58
- cleanedArgs = [
59
- restArgs,
60
- ...args.slice(1)
61
- ];
62
- }
63
- if (!token) {
64
- throw new AuthenticationError("Authentication required. Please provide a valid token in the request.", "MISSING_TOKEN");
65
- }
66
- try {
67
- const isValid = await authProvider.verifyToken(token);
68
- if (!isValid) {
69
- throw new AuthenticationError("Invalid or expired token. Please authenticate again.", "INVALID_TOKEN");
70
- }
71
- } catch (error) {
72
- if (error instanceof AuthenticationError) {
73
- throw error;
74
- }
75
- throw new AuthenticationError(`Token verification failed: ${error instanceof Error ? error.message : String(error)}`, "VERIFICATION_FAILED");
76
- }
77
- return originalMethod.apply(this, cleanedArgs);
78
- };
79
- }
80
- __name(createAuthenticatedMethod, "createAuthenticatedMethod");
81
- function copyMetadata(source, target) {
82
- const metadataKeys = Reflect.getMetadataKeys(source);
83
- for (const key of metadataKeys) {
84
- const value = Reflect.getMetadata(key, source);
85
- Reflect.defineMetadata(key, value, target);
86
- }
87
- const designKeys = [
88
- "design:type",
89
- "design:paramtypes",
90
- "design:returntype"
91
- ];
92
- for (const key of designKeys) {
93
- const value = Reflect.getMetadata(key, source);
94
- if (value !== void 0) {
95
- Reflect.defineMetadata(key, value, target);
96
- }
97
- }
98
- }
99
- __name(copyMetadata, "copyMetadata");
100
- function isAuthenticationRequired(target) {
101
- return Reflect.getMetadata("auth:required", target) === true;
102
- }
103
- __name(isAuthenticationRequired, "isAuthenticationRequired");
104
- function getAuthProvider(target) {
105
- return Reflect.getMetadata("auth:provider", target);
106
- }
107
- __name(getAuthProvider, "getAuthProvider");
108
-
109
- // src/index.ts
110
- var AuthProviderBase = class {
111
- static {
112
- __name(this, "AuthProviderBase");
113
- }
114
- };
115
- var AuthProvider = class extends AuthProviderBase {
116
- static {
117
- __name(this, "AuthProvider");
118
- }
119
- providerInstance = null;
120
- providerType;
121
- config;
122
- constructor(provider, config) {
123
- super();
124
- this.providerType = provider.toLowerCase();
125
- this.config = config;
126
- }
127
- /**
128
- * Initialize the selected auth provider
129
- */
130
- async init(config) {
131
- const finalConfig = config || this.config;
132
- switch (this.providerType) {
133
- case "cognito": {
134
- const { AuthCognito } = await import("./cognito-GBSAAMZI.mjs");
135
- this.providerInstance = new AuthCognito();
136
- await this.providerInstance.init(finalConfig);
137
- break;
138
- }
139
- // Add more providers here in the future
140
- // case 'clerk': {
141
- // const { AuthClerk } = await import('./providers/clerk');
142
- // this.providerInstance = new AuthClerk();
143
- // await this.providerInstance.init(finalConfig);
144
- // break;
145
- // }
146
- default:
147
- throw new Error(`Unsupported auth provider: ${this.providerType}. Supported providers: cognito`);
148
- }
149
- }
150
- /**
151
- * Refresh an authentication token
152
- */
153
- async refreshToken(refreshToken, username) {
154
- if (!this.providerInstance) {
155
- throw new Error("AuthProvider not initialized. Call init() first.");
156
- }
157
- return this.providerInstance.refreshToken(refreshToken, username);
158
- }
159
- /**
160
- * Verify if a token is valid
161
- */
162
- async verifyToken(token) {
163
- if (!this.providerInstance) {
164
- throw new Error("AuthProvider not initialized. Call init() first.");
165
- }
166
- return this.providerInstance.verifyToken(token);
167
- }
168
- /**
169
- * Get user information from a token
170
- */
171
- async getUser(token) {
172
- if (!this.providerInstance) {
173
- throw new Error("AuthProvider not initialized. Call init() first.");
174
- }
175
- return this.providerInstance.getUser(token);
176
- }
177
- /**
178
- * Get the provider type
179
- */
180
- getProviderType() {
181
- return this.providerType;
182
- }
183
- };
184
-
185
- export {
186
- __name,
187
- AuthenticationError,
188
- Authenticated,
189
- isAuthenticationRequired,
190
- getAuthProvider,
191
- AuthProviderBase,
192
- AuthProvider
193
- };