passport-descope 2.0.0 → 3.0.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/README.md CHANGED
@@ -10,7 +10,7 @@ This strategy is designed to help manage authentication and sessions in your exp
10
10
 
11
11
  ### Requirements
12
12
 
13
- - [Node 20.0.0+](https://nodejs.org/en)
13
+ - [Node 20.19.0+ or 22.12.0+](https://nodejs.org/en)
14
14
 
15
15
  ### Installation
16
16
 
@@ -58,6 +58,8 @@ If you would like to learn more about Passport JS Strategies, please visit their
58
58
 
59
59
  We appreciate feedback and contribution to this repository!
60
60
 
61
+ This repository uses [Bun](https://bun.sh): `bun install`, `bun test`, `bun run lint` ([Biome](https://biomejs.dev)) and `bun run build`.
62
+
61
63
  ### Raise an issue
62
64
 
63
65
  To provide feedback or report a bug, please [raise an issue on our issue tracker](https://github.com/descope/passport-descope/issues).
package/dist/index.cjs ADDED
@@ -0,0 +1,180 @@
1
+ var __create = Object.create;
2
+ var __getProtoOf = Object.getPrototypeOf;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ if (mod && typeof mod === "object" || typeof mod === "function") {
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
29
+ }
30
+ if (canCache)
31
+ cache.set(mod, to);
32
+ return to;
33
+ };
34
+ var __toCommonJS = (from) => {
35
+ var entry = (__moduleCache ??= new WeakMap).get(from), desc;
36
+ if (entry)
37
+ return entry;
38
+ entry = __defProp({}, "__esModule", { value: true });
39
+ if (from && typeof from === "object" || typeof from === "function") {
40
+ for (var key of __getOwnPropNames(from))
41
+ if (!__hasOwnProp.call(entry, key))
42
+ __defProp(entry, key, {
43
+ get: __accessProp.bind(from, key),
44
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
45
+ });
46
+ }
47
+ __moduleCache.set(from, entry);
48
+ return entry;
49
+ };
50
+ var __moduleCache;
51
+ var __returnValue = (v) => v;
52
+ function __exportSetter(name, newValue) {
53
+ this[name] = __returnValue.bind(null, newValue);
54
+ }
55
+ var __export = (target, all) => {
56
+ for (var name in all)
57
+ __defProp(target, name, {
58
+ get: all[name],
59
+ enumerable: true,
60
+ configurable: true,
61
+ set: __exportSetter.bind(all, name)
62
+ });
63
+ };
64
+
65
+ // src/index.ts
66
+ var exports_src = {};
67
+ __export(exports_src, {
68
+ default: () => src_default
69
+ });
70
+ module.exports = __toCommonJS(exports_src);
71
+ var import_node_sdk2 = __toESM(require("@descope/node-sdk"), 1);
72
+
73
+ // src/token.ts
74
+ var import_node_sdk = __toESM(require("@descope/node-sdk"), 1);
75
+ var tokenFromCookie = (request) => {
76
+ const list = new Map;
77
+ const cookieHeader = request.headers?.cookie;
78
+ if (!cookieHeader)
79
+ return null;
80
+ cookieHeader.split(`;`).forEach((cookie) => {
81
+ let [name, ...rest] = cookie.split(`=`);
82
+ name = name?.trim();
83
+ if (!name)
84
+ return;
85
+ const value = rest.join(`=`).trim();
86
+ if (!value)
87
+ return;
88
+ try {
89
+ list.set(name, decodeURIComponent(value));
90
+ } catch {
91
+ return;
92
+ }
93
+ });
94
+ return list.get(import_node_sdk.default.SessionTokenCookieName);
95
+ };
96
+ var tokenFromHeader = (request) => {
97
+ const authHeader = request.headers?.authorization;
98
+ if (!authHeader)
99
+ return null;
100
+ const parts = authHeader.split(" ");
101
+ if (parts.length === 2) {
102
+ const [scheme, credentials] = parts;
103
+ if (/^Bearer$/i.test(scheme)) {
104
+ return credentials;
105
+ }
106
+ }
107
+ return null;
108
+ };
109
+
110
+ // src/index.ts
111
+ class DescopeStrategy {
112
+ _options;
113
+ name = "descope";
114
+ _descopeClient;
115
+ _realm;
116
+ _scope;
117
+ constructor(_options) {
118
+ this._options = _options;
119
+ this._descopeClient = import_node_sdk2.default({
120
+ projectId: _options.projectId,
121
+ managementKey: _options.managementKey
122
+ });
123
+ this._realm = _options.realm || "Users";
124
+ if (_options.scope) {
125
+ this._scope = Array.isArray(_options.scope) ? _options.scope : [_options.scope];
126
+ }
127
+ }
128
+ async authenticate(req, _authOptions) {
129
+ const token = tokenFromHeader(req) || tokenFromCookie(req);
130
+ let authInfo = null;
131
+ try {
132
+ authInfo = await this._descopeClient.validateJwt(token);
133
+ } catch (error) {
134
+ const defaultMessage = "No valid token provided";
135
+ const message = error instanceof Error ? error.message : defaultMessage;
136
+ return this.fail(this._challenge(401, message));
137
+ }
138
+ const verifyCallback = (err, user, info) => {
139
+ if (err) {
140
+ return this.error(err);
141
+ }
142
+ if (!user) {
143
+ if (typeof info === "string") {
144
+ info = { message: info };
145
+ }
146
+ info = info || {};
147
+ return this.fail(this._challenge(401, "invalid_token", info.message));
148
+ }
149
+ if (info?.userDetails) {
150
+ return this._descopeClient.management.user.loadByUserId(authInfo.token.sub).then((res) => {
151
+ if (!res.ok || !res.data) {
152
+ return this.fail(this._challenge(401, "invalid_token"));
153
+ }
154
+ return this.success(res.data, info);
155
+ }).catch((error) => this.error(error));
156
+ }
157
+ return this.success(user, info);
158
+ };
159
+ this._options.verify(authInfo, verifyCallback, req);
160
+ }
161
+ _challenge(code, desc, uri) {
162
+ let challenge = `Bearer realm="${this._realm}"`;
163
+ if (this._scope) {
164
+ challenge += `, scope="${this._scope.join(" ")}"`;
165
+ }
166
+ if (code) {
167
+ challenge += `, error="${code}"`;
168
+ }
169
+ if (desc) {
170
+ challenge += `, error_description="${desc}"`;
171
+ }
172
+ if (uri) {
173
+ challenge += `, error_uri="${uri}"`;
174
+ }
175
+ return challenge;
176
+ }
177
+ }
178
+ var src_default = DescopeStrategy;
179
+
180
+ module.exports = module.exports.default;
package/dist/index.d.ts CHANGED
@@ -1,8 +1,7 @@
1
- import { Request } from 'express';
2
- import { StrategyCreatedStatic } from 'passport';
3
1
  import DescopeClient from '@descope/node-sdk';
4
-
5
- type VerifyCallback = (payload: any, verifyCallback: (err?: Error | null, user?: Object, info?: any) => void, req: Request) => void;
2
+ import type { Request } from 'express';
3
+ import type { StrategyCreatedStatic } from 'passport';
4
+ type VerifyCallback = (payload: any, verifyCallback: (err?: Error | null, user?: unknown, info?: any) => void, req: Request) => void;
6
5
  interface Options {
7
6
  /** Descope project id to use */
8
7
  projectId: string;
@@ -27,7 +26,7 @@ declare class DescopeStrategy {
27
26
  _realm: string;
28
27
  _scope: [string];
29
28
  constructor(_options: Options);
30
- authenticate(this: StrategyCreatedStatic & DescopeStrategy, req: Request, options?: any): Promise<void>;
29
+ authenticate(this: StrategyCreatedStatic & DescopeStrategy, req: Request, _authOptions?: any): Promise<void>;
31
30
  /**
32
31
  * Generate a challenge response in case of failure
33
32
  * @param this the Descope strategy
@@ -38,5 +37,4 @@ declare class DescopeStrategy {
38
37
  */
39
38
  _challenge(this: StrategyCreatedStatic & DescopeStrategy, code?: number, desc?: string, uri?: string): string;
40
39
  }
41
-
42
- export { DescopeStrategy as default };
40
+ export default DescopeStrategy;
package/dist/index.js ADDED
@@ -0,0 +1,112 @@
1
+ // src/index.ts
2
+ import DescopeClient2 from "@descope/node-sdk";
3
+
4
+ // src/token.ts
5
+ import DescopeClient from "@descope/node-sdk";
6
+ var tokenFromCookie = (request) => {
7
+ const list = new Map;
8
+ const cookieHeader = request.headers?.cookie;
9
+ if (!cookieHeader)
10
+ return null;
11
+ cookieHeader.split(`;`).forEach((cookie) => {
12
+ let [name, ...rest] = cookie.split(`=`);
13
+ name = name?.trim();
14
+ if (!name)
15
+ return;
16
+ const value = rest.join(`=`).trim();
17
+ if (!value)
18
+ return;
19
+ try {
20
+ list.set(name, decodeURIComponent(value));
21
+ } catch {
22
+ return;
23
+ }
24
+ });
25
+ return list.get(DescopeClient.SessionTokenCookieName);
26
+ };
27
+ var tokenFromHeader = (request) => {
28
+ const authHeader = request.headers?.authorization;
29
+ if (!authHeader)
30
+ return null;
31
+ const parts = authHeader.split(" ");
32
+ if (parts.length === 2) {
33
+ const [scheme, credentials] = parts;
34
+ if (/^Bearer$/i.test(scheme)) {
35
+ return credentials;
36
+ }
37
+ }
38
+ return null;
39
+ };
40
+
41
+ // src/index.ts
42
+ class DescopeStrategy {
43
+ _options;
44
+ name = "descope";
45
+ _descopeClient;
46
+ _realm;
47
+ _scope;
48
+ constructor(_options) {
49
+ this._options = _options;
50
+ this._descopeClient = DescopeClient2({
51
+ projectId: _options.projectId,
52
+ managementKey: _options.managementKey
53
+ });
54
+ this._realm = _options.realm || "Users";
55
+ if (_options.scope) {
56
+ this._scope = Array.isArray(_options.scope) ? _options.scope : [_options.scope];
57
+ }
58
+ }
59
+ async authenticate(req, _authOptions) {
60
+ const token = tokenFromHeader(req) || tokenFromCookie(req);
61
+ let authInfo = null;
62
+ try {
63
+ authInfo = await this._descopeClient.validateJwt(token);
64
+ } catch (error) {
65
+ const defaultMessage = "No valid token provided";
66
+ const message = error instanceof Error ? error.message : defaultMessage;
67
+ return this.fail(this._challenge(401, message));
68
+ }
69
+ const verifyCallback = (err, user, info) => {
70
+ if (err) {
71
+ return this.error(err);
72
+ }
73
+ if (!user) {
74
+ if (typeof info === "string") {
75
+ info = { message: info };
76
+ }
77
+ info = info || {};
78
+ return this.fail(this._challenge(401, "invalid_token", info.message));
79
+ }
80
+ if (info?.userDetails) {
81
+ return this._descopeClient.management.user.loadByUserId(authInfo.token.sub).then((res) => {
82
+ if (!res.ok || !res.data) {
83
+ return this.fail(this._challenge(401, "invalid_token"));
84
+ }
85
+ return this.success(res.data, info);
86
+ }).catch((error) => this.error(error));
87
+ }
88
+ return this.success(user, info);
89
+ };
90
+ this._options.verify(authInfo, verifyCallback, req);
91
+ }
92
+ _challenge(code, desc, uri) {
93
+ let challenge = `Bearer realm="${this._realm}"`;
94
+ if (this._scope) {
95
+ challenge += `, scope="${this._scope.join(" ")}"`;
96
+ }
97
+ if (code) {
98
+ challenge += `, error="${code}"`;
99
+ }
100
+ if (desc) {
101
+ challenge += `, error_description="${desc}"`;
102
+ }
103
+ if (uri) {
104
+ challenge += `, error_uri="${uri}"`;
105
+ }
106
+ return challenge;
107
+ }
108
+ }
109
+ var src_default = DescopeStrategy;
110
+ export {
111
+ src_default as default
112
+ };
@@ -0,0 +1,3 @@
1
+ import type { Request } from 'express';
2
+ export declare const tokenFromCookie: (request: Request) => string;
3
+ export declare const tokenFromHeader: (request: Request) => string;
package/package.json CHANGED
@@ -1,39 +1,38 @@
1
1
  {
2
2
  "name": "passport-descope",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "Passport strategy for Descope authentication service",
5
- "typings": "dist/index.d.ts",
6
- "main": "dist/cjs/index.cjs.js",
7
- "module": "./dist/index.esm.js",
8
- "types": "dist/index.d.ts",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
9
  "exports": {
10
- "require": "./dist/cjs/index.cjs.js",
10
+ "require": "./dist/index.cjs",
11
11
  "import": {
12
12
  "types": "./dist/index.d.ts",
13
- "default": "./dist/index.esm.js"
13
+ "default": "./dist/index.js"
14
14
  }
15
15
  },
16
- "type": "module",
17
16
  "files": [
18
- "dist/**/*"
17
+ "dist"
19
18
  ],
20
19
  "repository": {
21
20
  "type": "git",
22
21
  "url": "git+https://github.com/descope/passport-descope.git"
23
22
  },
24
23
  "engines": {
25
- "node": ">= 20.0.0"
24
+ "node": "^20.19.0 || >=22.12.0"
26
25
  },
27
26
  "scripts": {
28
- "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && rollup -c --bundleConfigAsCjs",
29
- "test": "jest",
30
- "lint": "eslint src/**/*.ts --fix",
31
- "format": "prettier . --write --ignore-path .gitignore",
32
- "leaks": "bash gitleaks/gitleaks.sh"
27
+ "build": "bun run build.ts",
28
+ "test": "bun test",
29
+ "typecheck": "tsc",
30
+ "lint": "biome check --write",
31
+ "format": "biome format --write"
33
32
  },
34
33
  "author": "Descope",
35
34
  "bugs": {
36
- "url": "git://github.com/descope/passport-descope/issues"
35
+ "url": "https://github.com/descope/passport-descope/issues"
37
36
  },
38
37
  "license": "MIT",
39
38
  "keywords": [
@@ -43,45 +42,15 @@
43
42
  "node"
44
43
  ],
45
44
  "devDependencies": {
46
- "@rollup/plugin-commonjs": "29.0.3",
47
- "@rollup/plugin-node-resolve": "16.0.3",
48
- "@rollup/plugin-typescript": "12.3.1",
45
+ "@biomejs/biome": "2.6.9",
46
+ "@types/bun": "1.4.5",
49
47
  "@types/express": "5.0.6",
50
- "@types/jest": "30.0.0",
51
- "@types/jsonwebtoken": "9.0.10",
52
- "@types/passport": "1.0.17",
53
48
  "@types/node": "22.20.5",
54
- "@types/node-fetch": "2.6.13",
55
- "@typescript-eslint/eslint-plugin": "8.72.2",
56
- "@typescript-eslint/parser": "8.72.2",
57
- "@typescript/native": "npm:typescript@7.0.2",
58
- "eslint": "10.14.0",
59
- "eslint-config-airbnb-base": "15.0.0",
60
- "eslint-config-airbnb-typescript": "18.0.0",
61
- "eslint-config-prettier": "10.1.8",
62
- "eslint-import-resolver-typescript": "4.4.5",
63
- "eslint-plugin-import": "2.32.0",
64
- "eslint-plugin-jest": "29.17.0",
65
- "eslint-plugin-jest-dom": "5.10.1",
66
- "eslint-plugin-jest-formatting": "4.0.0",
67
- "eslint-plugin-no-only-tests": "3.4.0",
68
- "eslint-plugin-prefer-arrow": "1.2.3",
69
- "eslint-plugin-prettier": "5.5.7",
70
- "jest": "30.5.2",
71
- "prettier": "3.9.10",
72
- "rollup": "4.68.2",
73
- "rollup-plugin-dts": "6.4.1",
74
- "@rollup/plugin-terser": "1.0.2",
75
- "ts-jest": "29.4.15",
76
- "ts-node": "10.9.2",
77
- "tslib": "2.9.1",
78
- "typescript": "npm:@typescript/typescript6@6.0.2"
49
+ "@types/passport": "1.0.17",
50
+ "typescript": "7.0.2"
79
51
  },
80
52
  "dependencies": {
81
- "@descope/node-sdk": "1.10.0"
82
- },
83
- "peerDependencies": {
84
- "tslib": ">=1.14.1"
53
+ "@descope/node-sdk": "3.1.0"
85
54
  },
86
- "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
55
+ "packageManager": "bun@1.4.5"
87
56
  }
@@ -1,2 +0,0 @@
1
- "use strict";var e=require("@descope/node-sdk");module.exports=class{constructor(t){this._options=t,this.name="descope",this._descopeClient=e({projectId:t.projectId,managementKey:t.managementKey}),this._realm=t.realm||"Users",t.scope&&(this._scope=Array.isArray(t.scope)?t.scope:[t.scope])}async authenticate(t,r){const s=this,o=(e=>{var t;const r=null===(t=e.headers)||void 0===t?void 0:t.authorization;if(!r)return null;const s=r.split(" ");if(2==s.length){const e=s[0],t=s[1];if(/^Bearer$/i.test(e))return t}return null})(t)||(t=>{var r;const s=new Map,o=null===(r=t.headers)||void 0===r?void 0:r.cookie;return o?(o.split(";").forEach(e=>{let[t,...r]=e.split("=");if(t=null==t?void 0:t.trim(),!t)return;const o=r.join("=").trim();if(o)try{s.set(t,decodeURIComponent(o))}catch(e){return}}),s.get(e.SessionTokenCookieName)):null})(t);let n=null;try{n=await s._descopeClient.validateJwt(o)}catch(e){const t="No valid token provided",r=e instanceof Error?e.message:t;return s.fail(s._challenge(401,r))}s._options.verify(n,(e,t,r)=>e?s.error(e):t?(null==r?void 0:r.userDetails)?s._descopeClient.management.user.loadByUserId(n.token.sub).then(e=>e.ok&&e.data?s.success(e.data,r):s.fail(s._challenge(401,"invalid_token"))).catch(e=>s.error(e)):s.success(t,r):("string"==typeof r&&(r={message:r}),r=r||{},s.fail(s._challenge(401,"invalid_token",r.message))),t)}_challenge(e,t,r){let s='Bearer realm="'+this._realm+'"';return this._scope&&(s+=', scope="'+this._scope.join(" ")+'"'),e&&(s+=', error="'+e+'"'),t&&(s+=', error_description="'+t+'"'),r&&(s+=', error_uri="'+r+'"'),s}};
2
- //# sourceMappingURL=index.cjs.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../../src/index.ts","../../src/token.ts"],"sourcesContent":["/* eslint-disable no-console */\n/* eslint-disable no-underscore-dangle */\nimport { Request, Response } from 'express';\nimport { StrategyCreatedStatic } from 'passport';\nimport { tokenFromHeader, tokenFromCookie } from './token';\nimport DescopeClient from '@descope/node-sdk';\n\ntype VerifyCallback = (\n payload: any,\n verifyCallback: (err?: Error | null, user?: Object, info?: any) => void,\n req: Request,\n) => void;\n\ninterface Options {\n /** Descope project id to use */\n projectId: string;\n /** Descope optional management key to retrieve extra user details */\n managementKey?: string;\n /** The callback to load the user details if stored outside of Descope */\n verify: VerifyCallback;\n /** The realm for the challenge */\n realm?: string;\n /** The scopes for the challenge */\n scope?: [string] | string;\n}\n\ntype DescopeSdk = ReturnType<typeof DescopeClient>;\ntype ValidateSessionRes = ReturnType<DescopeSdk[\"validateJwt\"]>;\ntype AuthenticationInfo = Awaited<ValidateSessionRes>;\n\n/**\n * DescopeStrategy for PassportJS verifies that the given JWT token in either Authorization Bearer or DS cookie is valid.\n * It requires the Descope project ID and a verify function is there to allow the app to manipulate user details.\n */\nclass DescopeStrategy {\n name: string = 'descope';\n _descopeClient: DescopeSdk;\n _realm: string;\n _scope: [string];\n\n constructor(private _options: Options) {\n this._descopeClient = DescopeClient({ projectId: _options.projectId, managementKey: _options.managementKey });\n this._realm = _options.realm || 'Users';\n if (_options.scope) {\n this._scope = (Array.isArray(_options.scope)) ? _options.scope : [ _options.scope ];\n }\n }\n\n async authenticate(this: StrategyCreatedStatic & DescopeStrategy, req: Request, options?: any): Promise<void> {\n const self = this;\n const token = tokenFromHeader(req) || tokenFromCookie(req);\n let authInfo: AuthenticationInfo = null;\n try {\n authInfo = await self._descopeClient.validateJwt(token);\n } catch (error) {\n const defaultMessage = 'No valid token provided';\n const message = error instanceof Error ? error.message : defaultMessage;\n return self.fail(self._challenge(401, message));\n }\n\n const verifyCallback = (err?: Error | null, user?: Object, info?: any) => {\n if (err) {\n return self.error(err);\n }\n if (!user) {\n if (typeof info == 'string') {\n info = { message: info }\n }\n info = info || {};\n return self.fail(self._challenge(401, 'invalid_token', info.message)); \n }\n if (info?.userDetails) {\n return self._descopeClient.management.user.loadByUserId(authInfo.token.sub)\n .then((res) => {\n if (!res.ok || !res.data) {\n return self.fail(self._challenge(401, 'invalid_token'));\n }\n return self.success(res.data, info);\n })\n .catch((error) => self.error(error));\n }\n return self.success(user, info);\n };\n\n self._options.verify(authInfo, verifyCallback, req);\n }\n\n /**\n * Generate a challenge response in case of failure\n * @param this the Descope strategy\n * @param code error code\n * @param desc error description\n * @param uri relevant uri for the error\n * @returns the challenge string\n */\n _challenge(this: StrategyCreatedStatic & DescopeStrategy, code?: number, desc?: string, uri?: string) {\n let challenge = 'Bearer realm=\"' + this._realm + '\"';\n if (this._scope) {\n challenge += ', scope=\"' + this._scope.join(' ') + '\"';\n }\n if (code) {\n challenge += ', error=\"' + code + '\"';\n }\n if (desc) {\n challenge += ', error_description=\"' + desc + '\"';\n }\n if (uri) {\n challenge += ', error_uri=\"' + uri + '\"';\n }\n return challenge;\n }\n}\n\nexport default DescopeStrategy;\n","/* eslint-disable no-console */\nimport { Request } from 'express';\nimport DescopeClient from '@descope/node-sdk';\n\nexport const tokenFromCookie = (request: Request) => {\n const list = new Map<string, string>();\n const cookieHeader = request.headers?.cookie;\n if (!cookieHeader) return null;\n\n cookieHeader.split(`;`).forEach((cookie: string) => {\n let [name, ...rest] = cookie.split(`=`);\n name = name?.trim();\n if (!name) return;\n const value = rest.join(`=`).trim();\n if (!value) return;\n try {\n list.set(name, decodeURIComponent(value));\n } catch {\n return;\n }\n });\n\n return list.get(DescopeClient.SessionTokenCookieName);\n};\n\nexport const tokenFromHeader = (request: Request) => {\n const authHeader = request.headers?.authorization;\n if (!authHeader) return null;\n\n const parts = authHeader.split(' ');\n if (parts.length == 2) {\n const scheme = parts[0], credentials = parts[1];\n if (/^Bearer$/i.test(scheme)) {\n return credentials;\n }\n }\n return null\n};"],"names":["constructor","_options","this","name","_descopeClient","DescopeClient","projectId","managementKey","_realm","realm","scope","_scope","Array","isArray","authenticate","req","options","self","token","request","authHeader","_a","headers","authorization","parts","split","length","scheme","credentials","test","tokenFromHeader","list","Map","cookieHeader","cookie","forEach","rest","trim","value","join","set","decodeURIComponent","get","SessionTokenCookieName","tokenFromCookie","authInfo","validateJwt","error","defaultMessage","message","Error","fail","_challenge","verify","err","user","info","userDetails","management","loadByUserId","sub","then","res","ok","data","success","catch","code","desc","uri","challenge"],"mappings":"+DAkCA,MAME,WAAAA,CAAoBC,GAAAC,KAAAD,SAAAA,EALpBC,KAAAC,KAAe,UAMbD,KAAKE,eAAiBC,EAAc,CAAEC,UAAWL,EAASK,UAAWC,cAAeN,EAASM,gBAC7FL,KAAKM,OAASP,EAASQ,OAAS,QAC5BR,EAASS,QACXR,KAAKS,OAAUC,MAAMC,QAAQZ,EAASS,OAAUT,EAASS,MAAQ,CAAET,EAASS,OAEhF,CAEA,kBAAMI,CAA4DC,EAAcC,GAC9E,MAAMC,EAAOf,KACPgB,ECzBqB,CAACC,UAC9B,MAAMC,EAA4B,QAAfC,EAAAF,EAAQG,eAAO,IAAAD,SAAAA,EAAEE,cACpC,IAAKH,EAAY,OAAO,KAExB,MAAMI,EAAQ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,QAASO,IAEpBA,EAAOA,GAAQ,CAAA,EACRvC,EAAKkC,KAAKlC,EAAKmC,WAAW,IAAK,gBAAiBI,EAAKP,WAejBlC,EACjD,CAUA,UAAAqC,CAA0De,EAAeC,EAAeC,GACtF,IAAIC,EAAY,iBAAmBpE,KAAKM,OAAS,IAajD,OAZIN,KAAKS,SACP2D,GAAa,YAAcpE,KAAKS,OAAO4B,KAAK,KAAO,KAEjD4B,IACFG,GAAa,YAAcH,EAAO,KAEhCC,IACFE,GAAa,wBAA0BF,EAAO,KAE5CC,IACFC,GAAa,gBAAkBD,EAAM,KAEhCC,CACT"}
@@ -1 +0,0 @@
1
- {"type":"commonjs"}
package/dist/index.esm.js DELETED
@@ -1,2 +0,0 @@
1
- import e from"@descope/node-sdk";class t{constructor(t){this._options=t,this.name="descope",this._descopeClient=e({projectId:t.projectId,managementKey:t.managementKey}),this._realm=t.realm||"Users",t.scope&&(this._scope=Array.isArray(t.scope)?t.scope:[t.scope])}async authenticate(t,r){const o=this,s=(e=>{var t;const r=null===(t=e.headers)||void 0===t?void 0:t.authorization;if(!r)return null;const o=r.split(" ");if(2==o.length){const e=o[0],t=o[1];if(/^Bearer$/i.test(e))return t}return null})(t)||(t=>{var r;const o=new Map,s=null===(r=t.headers)||void 0===r?void 0:r.cookie;return s?(s.split(";").forEach(e=>{let[t,...r]=e.split("=");if(t=null==t?void 0:t.trim(),!t)return;const s=r.join("=").trim();if(s)try{o.set(t,decodeURIComponent(s))}catch(e){return}}),o.get(e.SessionTokenCookieName)):null})(t);let n=null;try{n=await o._descopeClient.validateJwt(s)}catch(e){const t="No valid token provided",r=e instanceof Error?e.message:t;return o.fail(o._challenge(401,r))}o._options.verify(n,(e,t,r)=>e?o.error(e):t?(null==r?void 0:r.userDetails)?o._descopeClient.management.user.loadByUserId(n.token.sub).then(e=>e.ok&&e.data?o.success(e.data,r):o.fail(o._challenge(401,"invalid_token"))).catch(e=>o.error(e)):o.success(t,r):("string"==typeof r&&(r={message:r}),r=r||{},o.fail(o._challenge(401,"invalid_token",r.message))),t)}_challenge(e,t,r){let o='Bearer realm="'+this._realm+'"';return this._scope&&(o+=', scope="'+this._scope.join(" ")+'"'),e&&(o+=', error="'+e+'"'),t&&(o+=', error_description="'+t+'"'),r&&(o+=', error_uri="'+r+'"'),o}}export{t as default};
2
- //# sourceMappingURL=index.esm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/index.ts","../src/token.ts"],"sourcesContent":["/* eslint-disable no-console */\n/* eslint-disable no-underscore-dangle */\nimport { Request, Response } from 'express';\nimport { StrategyCreatedStatic } from 'passport';\nimport { tokenFromHeader, tokenFromCookie } from './token';\nimport DescopeClient from '@descope/node-sdk';\n\ntype VerifyCallback = (\n payload: any,\n verifyCallback: (err?: Error | null, user?: Object, info?: any) => void,\n req: Request,\n) => void;\n\ninterface Options {\n /** Descope project id to use */\n projectId: string;\n /** Descope optional management key to retrieve extra user details */\n managementKey?: string;\n /** The callback to load the user details if stored outside of Descope */\n verify: VerifyCallback;\n /** The realm for the challenge */\n realm?: string;\n /** The scopes for the challenge */\n scope?: [string] | string;\n}\n\ntype DescopeSdk = ReturnType<typeof DescopeClient>;\ntype ValidateSessionRes = ReturnType<DescopeSdk[\"validateJwt\"]>;\ntype AuthenticationInfo = Awaited<ValidateSessionRes>;\n\n/**\n * DescopeStrategy for PassportJS verifies that the given JWT token in either Authorization Bearer or DS cookie is valid.\n * It requires the Descope project ID and a verify function is there to allow the app to manipulate user details.\n */\nclass DescopeStrategy {\n name: string = 'descope';\n _descopeClient: DescopeSdk;\n _realm: string;\n _scope: [string];\n\n constructor(private _options: Options) {\n this._descopeClient = DescopeClient({ projectId: _options.projectId, managementKey: _options.managementKey });\n this._realm = _options.realm || 'Users';\n if (_options.scope) {\n this._scope = (Array.isArray(_options.scope)) ? _options.scope : [ _options.scope ];\n }\n }\n\n async authenticate(this: StrategyCreatedStatic & DescopeStrategy, req: Request, options?: any): Promise<void> {\n const self = this;\n const token = tokenFromHeader(req) || tokenFromCookie(req);\n let authInfo: AuthenticationInfo = null;\n try {\n authInfo = await self._descopeClient.validateJwt(token);\n } catch (error) {\n const defaultMessage = 'No valid token provided';\n const message = error instanceof Error ? error.message : defaultMessage;\n return self.fail(self._challenge(401, message));\n }\n\n const verifyCallback = (err?: Error | null, user?: Object, info?: any) => {\n if (err) {\n return self.error(err);\n }\n if (!user) {\n if (typeof info == 'string') {\n info = { message: info }\n }\n info = info || {};\n return self.fail(self._challenge(401, 'invalid_token', info.message)); \n }\n if (info?.userDetails) {\n return self._descopeClient.management.user.loadByUserId(authInfo.token.sub)\n .then((res) => {\n if (!res.ok || !res.data) {\n return self.fail(self._challenge(401, 'invalid_token'));\n }\n return self.success(res.data, info);\n })\n .catch((error) => self.error(error));\n }\n return self.success(user, info);\n };\n\n self._options.verify(authInfo, verifyCallback, req);\n }\n\n /**\n * Generate a challenge response in case of failure\n * @param this the Descope strategy\n * @param code error code\n * @param desc error description\n * @param uri relevant uri for the error\n * @returns the challenge string\n */\n _challenge(this: StrategyCreatedStatic & DescopeStrategy, code?: number, desc?: string, uri?: string) {\n let challenge = 'Bearer realm=\"' + this._realm + '\"';\n if (this._scope) {\n challenge += ', scope=\"' + this._scope.join(' ') + '\"';\n }\n if (code) {\n challenge += ', error=\"' + code + '\"';\n }\n if (desc) {\n challenge += ', error_description=\"' + desc + '\"';\n }\n if (uri) {\n challenge += ', error_uri=\"' + uri + '\"';\n }\n return challenge;\n }\n}\n\nexport default DescopeStrategy;\n","/* eslint-disable no-console */\nimport { Request } from 'express';\nimport DescopeClient from '@descope/node-sdk';\n\nexport const tokenFromCookie = (request: Request) => {\n const list = new Map<string, string>();\n const cookieHeader = request.headers?.cookie;\n if (!cookieHeader) return null;\n\n cookieHeader.split(`;`).forEach((cookie: string) => {\n let [name, ...rest] = cookie.split(`=`);\n name = name?.trim();\n if (!name) return;\n const value = rest.join(`=`).trim();\n if (!value) return;\n try {\n list.set(name, decodeURIComponent(value));\n } catch {\n return;\n }\n });\n\n return list.get(DescopeClient.SessionTokenCookieName);\n};\n\nexport const tokenFromHeader = (request: Request) => {\n const authHeader = request.headers?.authorization;\n if (!authHeader) return null;\n\n const parts = authHeader.split(' ');\n if (parts.length == 2) {\n const scheme = parts[0], credentials = parts[1];\n if (/^Bearer$/i.test(scheme)) {\n return credentials;\n }\n }\n return null\n};"],"names":["DescopeStrategy","constructor","_options","this","name","_descopeClient","DescopeClient","projectId","managementKey","_realm","realm","scope","_scope","Array","isArray","authenticate","req","options","self","token","request","authHeader","_a","headers","authorization","parts","split","length","scheme","credentials","test","tokenFromHeader","list","Map","cookieHeader","cookie","forEach","rest","trim","value","join","set","decodeURIComponent","get","SessionTokenCookieName","tokenFromCookie","authInfo","validateJwt","error","defaultMessage","message","Error","fail","_challenge","verify","err","user","info","userDetails","management","loadByUserId","sub","then","res","ok","data","success","catch","code","desc","uri","challenge"],"mappings":"iCAkCA,MAAMA,EAMJ,WAAAC,CAAoBC,GAAAC,KAAAD,SAAAA,EALpBC,KAAAC,KAAe,UAMbD,KAAKE,eAAiBC,EAAc,CAAEC,UAAWL,EAASK,UAAWC,cAAeN,EAASM,gBAC7FL,KAAKM,OAASP,EAASQ,OAAS,QAC5BR,EAASS,QACXR,KAAKS,OAAUC,MAAMC,QAAQZ,EAASS,OAAUT,EAASS,MAAQ,CAAET,EAASS,OAEhF,CAEA,kBAAMI,CAA4DC,EAAcC,GAC9E,MAAMC,EAAOf,KACPgB,ECzBqB,CAACC,UAC9B,MAAMC,EAA4B,QAAfC,EAAAF,EAAQG,eAAO,IAAAD,SAAAA,EAAEE,cACpC,IAAKH,EAAY,OAAO,KAExB,MAAMI,EAAQJ,EAAWK,MAAM,KAC/B,GAAoB,GAAhBD,EAAME,OAAa,CACrB,MAAMC,EAASH,EAAM,GAAII,EAAcJ,EAAM,GAC7C,GAAI,YAAYK,KAAKF,GACnB,OAAOC,CAEX,CACA,OAAO,MDcSE,CAAgBf,IC9CH,CAACI,UAC9B,MAA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