win-sso 1.4.0 → 2.0.0-beta.2

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
@@ -109,6 +109,10 @@ This method throws if the response could not be created. One such scenario is if
109
109
 
110
110
  Releases all allocated resources for the authorization context. Resources are also released when the instance is destroyed, but it is still recommended to call this method when the context is no longer required, such as when an error ocurred or when the socket was closed.
111
111
 
112
- ### Credits
112
+ ## Developer notes
113
+
114
+ Due to security improvements in npm the install step has been removed. The package uses prebuildify which means that the required Node addon is incldued automatically in the npm package for downstream use. However, when working with this package directly the Node addon is no longer built automatically on `npm install` - now an additional call to `npm run native_build` is required.
115
+
116
+ ## Credits
113
117
 
114
118
  The idea of implementation is based on the work of @snowytoxa, who presented the concept of retrieving NTLM tokens for the current user without any admin privileges in 2014. The source for his project [selfhash](https://github.com/snowytoxa/selfhash/) shortened the development time significantly.
package/dist/index.js CHANGED
@@ -1,7 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.osSupported = exports.WinSso = void 0;
4
- const win_sso_1 = require("./win-sso");
5
- Object.defineProperty(exports, "WinSso", { enumerable: true, get: function () { return win_sso_1.WinSso; } });
6
- const os_supported_1 = require("./os-supported");
7
- Object.defineProperty(exports, "osSupported", { enumerable: true, get: function () { return os_supported_1.osSupported; } });
1
+ import { WinSso } from "./win-sso.js";
2
+ import { osSupported } from "./os-supported.js";
3
+ export { WinSso, osSupported };
@@ -1,15 +1,9 @@
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.osSupported = osSupported;
7
- const os_1 = __importDefault(require("os"));
1
+ import os from "node:os";
8
2
  /**
9
3
  * Returns true if the current platform is supported by the win-sso module. Only Windows OSs are supported.
10
4
  * If false, all other methods in the module will throw.
11
- * @returns Is the os supported
5
+ * @returns {boolean} Is the os supported
12
6
  */
13
- function osSupported() {
14
- return os_1.default.platform() === "win32";
7
+ export function osSupported() {
8
+ return os.platform() === "win32";
15
9
  }
@@ -1,5 +1,2 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.debug = void 0;
4
- const debug_1 = require("debug");
5
- exports.debug = (0, debug_1.debug)('win-sso');
1
+ import debugInit from 'debug';
2
+ export const debug = debugInit('win-sso');
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
package/dist/win-sso.js CHANGED
@@ -1,34 +1,31 @@
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.WinSso = void 0;
7
- const debug_logger_1 = require("./utils/debug.logger");
8
- const path_1 = __importDefault(require("path"));
1
+ import { debug } from "./utils/debug.logger.js";
2
+ import path from "node:path";
9
3
  let winSsoAddon;
10
4
  try {
11
- const currentDir = __dirname; // eslint-disable-line
12
- // eslint-disable-next-line @typescript-eslint/no-require-imports
13
- winSsoAddon = require("node-gyp-build")(path_1.default.join(currentDir, "..", "native"));
14
- (0, debug_logger_1.debug)("Loaded win-sso native module");
5
+ const { default: load } = await import("node-gyp-build");
6
+ const currentDir = import.meta.dirname; // eslint-disable-line
7
+ winSsoAddon = load(path.join(currentDir, "..", "native"));
8
+ debug("Loaded win-sso native module");
15
9
  }
16
- catch (_a) {
17
- (0, debug_logger_1.debug)("Could not load win-sso native module");
10
+ catch (err) {
11
+ debug("Could not load win-sso native module", { cause: err });
18
12
  }
19
13
  /**
20
14
  * Creates authentication tokens for NTLM or Negotiate handshake using the executing users credentials.
21
15
  */
22
- class WinSso {
16
+ export class WinSso {
17
+ static NEGOTIATE_NTLM2_KEY = 1 << 19;
18
+ authContextId;
19
+ securityPackage;
23
20
  /**
24
21
  * Creates an authentication context for SSO.
25
22
  * This allocates memory buffers, the freeAuthContext method should be called
26
23
  * to free them (on error or after authentication is no longer needed)
27
- * @param securityPackage The name of the security package (NTLM or Negotiate)
28
- * @param targetHost The FQDN hostname of the target (optional for NTLM, required for Kerberos)
29
- * @param peerCert The certificate of the target server
24
+ * @param {string} securityPackage The name of the security package (NTLM or Negotiate)
25
+ * @param {string|undefined} targetHost The FQDN hostname of the target (optional for NTLM, required for Kerberos)
26
+ * @param {PeerCertificate|undefined} peerCert The certificate of the target server
30
27
  * (optional, for HTTPS channel binding)
31
- * @param flags Flags to set in the authentication context
28
+ * @param {number|undefined} flags Flags to set in the authentication context
32
29
  * If not set, NTML defaults to no flags, while Negotiate defaults to ISC_REQ_MUTUAL_AUTH | ISC_REQ_SEQUENCE_DETECT
33
30
  * (optional, allows customizing security features)
34
31
  */
@@ -48,15 +45,15 @@ class WinSso {
48
45
  }
49
46
  /**
50
47
  * Retrieves the username of the logged in user
51
- * @returns user name including domain
48
+ * @returns {string} user name including domain
52
49
  */
53
50
  static getLogonUserName() {
54
51
  return winSsoAddon.getLogonUserName();
55
52
  }
56
53
  /**
57
54
  * Transforms target TLS certificate into a channel binding application data buffer
58
- * @param peerCert Target TLS certificate
59
- * @returns Application data buffer
55
+ * @param {PeerCertificate} peerCert Target TLS certificate
56
+ * @returns {Buffer} Application data buffer
60
57
  */
61
58
  getChannelBindingsApplicationData(peerCert) {
62
59
  const hash = peerCert.fingerprint256.replace(/:/g, "");
@@ -77,16 +74,16 @@ class WinSso {
77
74
  }
78
75
  /**
79
76
  * Creates an authentication request token
80
- * @returns Raw token buffer
77
+ * @returns {Buffer} Raw token buffer
81
78
  */
82
79
  createAuthRequest() {
83
80
  const token = winSsoAddon.createAuthRequest(this.authContextId);
84
- (0, debug_logger_1.debug)("Created " + this.securityPackage + " authentication request token", token.toString("base64"));
81
+ debug("Created " + this.securityPackage + " authentication request token", token.toString("base64"));
85
82
  return token;
86
83
  }
87
84
  /**
88
85
  * Creates an authentication request header
89
- * @returns The www-authenticate header
86
+ * @returns {string} The www-authenticate header
90
87
  */
91
88
  createAuthRequestHeader() {
92
89
  const header = this.securityPackage + " " + this.createAuthRequest().toString("base64");
@@ -94,12 +91,12 @@ class WinSso {
94
91
  }
95
92
  /**
96
93
  * Creates an authentication response token
97
- * @param inTokenHeader The www-authentication header received from the target
94
+ * @param {string} inTokenHeader The www-authentication header received from the target
98
95
  * in response to the authentication request
99
- * @returns Raw token buffer. May be empty if Negotiate handshake is complete.
96
+ * @returns {Buffer} Raw token buffer. May be empty if Negotiate handshake is complete.
100
97
  */
101
98
  createAuthResponse(inTokenHeader) {
102
- (0, debug_logger_1.debug)("Received www-authentication response", inTokenHeader);
99
+ debug("Received www-authentication response", inTokenHeader);
103
100
  const packageMatch = new RegExp("^" + this.securityPackage + "\\s([^,\\s]+)").exec(inTokenHeader);
104
101
  if (!packageMatch) {
105
102
  throw new Error("Invalid input token, missing " +
@@ -111,10 +108,10 @@ class WinSso {
111
108
  try {
112
109
  const token = winSsoAddon.createAuthResponse(this.authContextId, inToken);
113
110
  if (token.length > 0) {
114
- (0, debug_logger_1.debug)("Created " + this.securityPackage + " authentication response token", token.toString("base64"));
111
+ debug("Created " + this.securityPackage + " authentication response token", token.toString("base64"));
115
112
  }
116
113
  else {
117
- (0, debug_logger_1.debug)("No response token, authentication complete");
114
+ debug("No response token, authentication complete");
118
115
  }
119
116
  return token;
120
117
  }
@@ -126,7 +123,7 @@ class WinSso {
126
123
  if (this.securityPackage === "NTLM" && this.isNtlmV1(inToken)) {
127
124
  throw new Error("Could not create NTLM type 3 message. Incoming type 2 message uses NTLMv1, " +
128
125
  "it is likely that the client is prevented from sending such messages. " +
129
- "Update target host to use NTLMv2 (recommended) or adjust LMCompatibilityLevel on the client (insecure)");
126
+ "Update target host to use NTLMv2 (recommended) or adjust LMCompatibilityLevel on the client (insecure)", { cause: err });
130
127
  }
131
128
  }
132
129
  throw err;
@@ -143,9 +140,9 @@ class WinSso {
143
140
  }
144
141
  /**
145
142
  * Creates an authentication response header
146
- * @param inTokenHeader The www-authentication header received from the target
143
+ * @param {string} inTokenHeader The www-authentication header received from the target
147
144
  * in response to the authentication request
148
- * @returns The www-authenticate header. May be an empty string if Negotiate handshake is complete.
145
+ * @returns {string} The www-authenticate header. May be an empty string if Negotiate handshake is complete.
149
146
  */
150
147
  createAuthResponseHeader(inTokenHeader) {
151
148
  const tokenBuffer = this.createAuthResponse(inTokenHeader);
@@ -156,5 +153,3 @@ class WinSso {
156
153
  return header;
157
154
  }
158
155
  }
159
- exports.WinSso = WinSso;
160
- WinSso.NEGOTIATE_NTLM2_KEY = 1 << 19;
package/package.json CHANGED
@@ -1,15 +1,18 @@
1
1
  {
2
2
  "name": "win-sso",
3
- "version": "1.4.0",
3
+ "version": "2.0.0-beta.2",
4
4
  "description": "NTLM single-sign-on for Node.js. Only Windows OS supported.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
7
7
  "build": "shx rm -rf dist && tsc",
8
8
  "lint": "eslint src",
9
- "test": "mocha --require ./test/ts.hooks.js test/**/*.spec.ts",
10
- "prebuildify": "node native/prebuildify_env.js",
11
- "native_prebuildify": "prebuildify --napi --strip --target 22.22.2 --cwd native"
9
+ "test": "mocha test/**/*.spec.ts",
10
+ "typecheck": "tsc --noEmit",
11
+ "prebuildify": "node native/prebuildify_env.ts",
12
+ "native_prebuildify": "prebuildify --napi --strip --target 22.22.2 --cwd native",
13
+ "prepare": "tsc -p tsconfig.publish.json"
12
14
  },
15
+ "type": "module",
13
16
  "engines": {
14
17
  "node": ">=22.22.2 || >=24.15.0 || >=26.0.0"
15
18
  },
@@ -34,26 +37,26 @@
34
37
  },
35
38
  "homepage": "https://github.com/bjowes/node-win-sso#readme",
36
39
  "dependencies": {
37
- "debug": "^4.4.0",
40
+ "debug": "^4.4.3",
38
41
  "node-gyp-build": "^4.8.4"
39
42
  },
40
43
  "devDependencies": {
41
- "@types/debug": "^4.1.12",
44
+ "@eslint/js": "^10.0.1",
45
+ "@types/cross-spawn": "^6.0.6",
46
+ "@types/debug": "^4.1.13",
42
47
  "@types/mocha": "^10.0.10",
43
- "@types/node": "^22.20.5",
44
- "asn1-parser": "^1.1.8",
48
+ "@types/node": "^26.6.6",
45
49
  "bindings": "^1.5.0",
46
50
  "cross-spawn": "^7.0.6",
47
- "eslint": "^9.26.0",
48
- "eslint-plugin-jsdoc": "^50.6.11",
49
- "eslint-plugin-node": "^11.1.0",
50
- "mocha": "^11.2.2",
51
- "node-addon-api": "^8.3.1",
51
+ "eslint": "^10.15.0",
52
+ "eslint-plugin-jsdoc": "^65.4.7",
53
+ "eslint-plugin-n": "^18.5.0",
54
+ "mocha": "^12.0.3",
55
+ "node-addon-api": "^8.9.2",
52
56
  "node-gyp": "^13.1.0",
53
57
  "prebuildify": "^6.0.1",
54
58
  "shx": "^0.4.0",
55
- "ts-node": "^10.9.2",
56
- "typescript": "^5.8.3",
57
- "typescript-eslint": "^8.32.0"
59
+ "typescript": "^6.0.3",
60
+ "typescript-eslint": "^8.72.2"
58
61
  }
59
62
  }
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { WinSso } from "./win-sso";
2
- import { osSupported } from "./os-supported";
1
+ import { WinSso } from "./win-sso.ts";
2
+ import { osSupported } from "./os-supported.ts";
3
3
 
4
4
  export { WinSso, osSupported };
@@ -0,0 +1,5 @@
1
+ declare module "node-gyp-build" {
2
+ function load<T = unknown>(directory: string): T;
3
+
4
+ export default load;
5
+ }
@@ -1,9 +1,9 @@
1
- import os from "os";
1
+ import os from "node:os";
2
2
 
3
3
  /**
4
4
  * Returns true if the current platform is supported by the win-sso module. Only Windows OSs are supported.
5
5
  * If false, all other methods in the module will throw.
6
- * @returns Is the os supported
6
+ * @returns {boolean} Is the os supported
7
7
  */
8
8
  export function osSupported(): boolean {
9
9
  return os.platform() === "win32";
@@ -1,4 +1,4 @@
1
- import { debug as debugInit } from 'debug';
1
+ import debugInit from 'debug';
2
2
 
3
3
  export const debug = debugInit('win-sso');
4
4
 
@@ -1,4 +1,4 @@
1
- export interface IWinSsoAddon {
1
+ interface IWinSsoAddon {
2
2
  createAuthContext(
3
3
  securityPackage: string,
4
4
  targetHost: string | undefined,
@@ -12,4 +12,6 @@ export interface IWinSsoAddon {
12
12
 
13
13
  createAuthRequest(authContextId: number): Buffer,
14
14
  createAuthResponse(authContextId: number, inToken: Buffer): Buffer,
15
- }
15
+ }
16
+
17
+ export type { IWinSsoAddon };
package/src/win-sso.ts CHANGED
@@ -1,16 +1,17 @@
1
- import { debug } from "./utils/debug.logger";
2
- import { PeerCertificate } from "tls";
3
- import path from "path";
4
- import { IWinSsoAddon } from "./utils/i.win-sso-addon";
1
+ import { debug } from "./utils/debug.logger.ts";
2
+ import type { PeerCertificate } from "node:tls";
3
+ import path from "node:path";
4
+ import type { IWinSsoAddon } from "./utils/i.win-sso-addon.ts";
5
5
 
6
6
  let winSsoAddon: IWinSsoAddon;
7
7
  try {
8
- const currentDir = __dirname; // eslint-disable-line
9
- // eslint-disable-next-line @typescript-eslint/no-require-imports
10
- winSsoAddon = require("node-gyp-build")(path.join(currentDir, "..", "native"));
8
+ const { default: load } = await import("node-gyp-build");
9
+
10
+ const currentDir = import.meta.dirname; // eslint-disable-line
11
+ winSsoAddon = load<IWinSsoAddon>(path.join(currentDir, "..", "native"));
11
12
  debug("Loaded win-sso native module");
12
- } catch {
13
- debug("Could not load win-sso native module");
13
+ } catch (err) {
14
+ debug("Could not load win-sso native module", { cause: err });
14
15
  }
15
16
 
16
17
  /**
@@ -26,11 +27,11 @@ export class WinSso {
26
27
  * Creates an authentication context for SSO.
27
28
  * This allocates memory buffers, the freeAuthContext method should be called
28
29
  * to free them (on error or after authentication is no longer needed)
29
- * @param securityPackage The name of the security package (NTLM or Negotiate)
30
- * @param targetHost The FQDN hostname of the target (optional for NTLM, required for Kerberos)
31
- * @param peerCert The certificate of the target server
30
+ * @param {string} securityPackage The name of the security package (NTLM or Negotiate)
31
+ * @param {string|undefined} targetHost The FQDN hostname of the target (optional for NTLM, required for Kerberos)
32
+ * @param {PeerCertificate|undefined} peerCert The certificate of the target server
32
33
  * (optional, for HTTPS channel binding)
33
- * @param flags Flags to set in the authentication context
34
+ * @param {number|undefined} flags Flags to set in the authentication context
34
35
  * If not set, NTML defaults to no flags, while Negotiate defaults to ISC_REQ_MUTUAL_AUTH | ISC_REQ_SEQUENCE_DETECT
35
36
  * (optional, allows customizing security features)
36
37
  */
@@ -60,7 +61,7 @@ export class WinSso {
60
61
 
61
62
  /**
62
63
  * Retrieves the username of the logged in user
63
- * @returns user name including domain
64
+ * @returns {string} user name including domain
64
65
  */
65
66
  static getLogonUserName(): string {
66
67
  return winSsoAddon.getLogonUserName();
@@ -68,8 +69,8 @@ export class WinSso {
68
69
 
69
70
  /**
70
71
  * Transforms target TLS certificate into a channel binding application data buffer
71
- * @param peerCert Target TLS certificate
72
- * @returns Application data buffer
72
+ * @param {PeerCertificate} peerCert Target TLS certificate
73
+ * @returns {Buffer} Application data buffer
73
74
  */
74
75
  private getChannelBindingsApplicationData(peerCert: PeerCertificate): Buffer {
75
76
  const hash = peerCert.fingerprint256.replace(/:/g, "");
@@ -94,7 +95,7 @@ export class WinSso {
94
95
 
95
96
  /**
96
97
  * Creates an authentication request token
97
- * @returns Raw token buffer
98
+ * @returns {Buffer} Raw token buffer
98
99
  */
99
100
  createAuthRequest(): Buffer {
100
101
  const token = winSsoAddon.createAuthRequest(this.authContextId);
@@ -107,7 +108,7 @@ export class WinSso {
107
108
 
108
109
  /**
109
110
  * Creates an authentication request header
110
- * @returns The www-authenticate header
111
+ * @returns {string} The www-authenticate header
111
112
  */
112
113
  createAuthRequestHeader(): string {
113
114
  const header =
@@ -117,9 +118,9 @@ export class WinSso {
117
118
 
118
119
  /**
119
120
  * Creates an authentication response token
120
- * @param inTokenHeader The www-authentication header received from the target
121
+ * @param {string} inTokenHeader The www-authentication header received from the target
121
122
  * in response to the authentication request
122
- * @returns Raw token buffer. May be empty if Negotiate handshake is complete.
123
+ * @returns {Buffer} Raw token buffer. May be empty if Negotiate handshake is complete.
123
124
  */
124
125
  createAuthResponse(inTokenHeader: string): Buffer {
125
126
  debug("Received www-authentication response", inTokenHeader);
@@ -158,7 +159,8 @@ export class WinSso {
158
159
  throw new Error(
159
160
  "Could not create NTLM type 3 message. Incoming type 2 message uses NTLMv1, " +
160
161
  "it is likely that the client is prevented from sending such messages. " +
161
- "Update target host to use NTLMv2 (recommended) or adjust LMCompatibilityLevel on the client (insecure)"
162
+ "Update target host to use NTLMv2 (recommended) or adjust LMCompatibilityLevel on the client (insecure)",
163
+ { cause: err }
162
164
  );
163
165
  }
164
166
  }
@@ -178,9 +180,9 @@ export class WinSso {
178
180
 
179
181
  /**
180
182
  * Creates an authentication response header
181
- * @param inTokenHeader The www-authentication header received from the target
183
+ * @param {string} inTokenHeader The www-authentication header received from the target
182
184
  * in response to the authentication request
183
- * @returns The www-authenticate header. May be an empty string if Negotiate handshake is complete.
185
+ * @returns {string} The www-authenticate header. May be an empty string if Negotiate handshake is complete.
184
186
  */
185
187
  createAuthResponseHeader(inTokenHeader: string): string {
186
188
  const tokenBuffer = this.createAuthResponse(inTokenHeader);
package/dist/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- import { WinSso } from "./win-sso";
2
- import { osSupported } from "./os-supported";
3
- export { WinSso, osSupported };
@@ -1,6 +0,0 @@
1
- /**
2
- * Returns true if the current platform is supported by the win-sso module. Only Windows OSs are supported.
3
- * If false, all other methods in the module will throw.
4
- * @returns Is the os supported
5
- */
6
- export declare function osSupported(): boolean;
@@ -1 +0,0 @@
1
- export declare const debug: import("debug").Debugger;
@@ -1,7 +0,0 @@
1
- export interface IWinSsoAddon {
2
- createAuthContext(securityPackage: string, targetHost: string | undefined, applicationData: Buffer, flags: number | undefined): number;
3
- freeAuthContext(authContextId: number): void;
4
- getLogonUserName(): string;
5
- createAuthRequest(authContextId: number): Buffer;
6
- createAuthResponse(authContextId: number, inToken: Buffer): Buffer;
7
- }
package/dist/win-sso.d.ts DELETED
@@ -1,64 +0,0 @@
1
- import { PeerCertificate } from "tls";
2
- /**
3
- * Creates authentication tokens for NTLM or Negotiate handshake using the executing users credentials.
4
- */
5
- export declare class WinSso {
6
- private static NEGOTIATE_NTLM2_KEY;
7
- private authContextId;
8
- private securityPackage;
9
- /**
10
- * Creates an authentication context for SSO.
11
- * This allocates memory buffers, the freeAuthContext method should be called
12
- * to free them (on error or after authentication is no longer needed)
13
- * @param securityPackage The name of the security package (NTLM or Negotiate)
14
- * @param targetHost The FQDN hostname of the target (optional for NTLM, required for Kerberos)
15
- * @param peerCert The certificate of the target server
16
- * (optional, for HTTPS channel binding)
17
- * @param flags Flags to set in the authentication context
18
- * If not set, NTML defaults to no flags, while Negotiate defaults to ISC_REQ_MUTUAL_AUTH | ISC_REQ_SEQUENCE_DETECT
19
- * (optional, allows customizing security features)
20
- */
21
- constructor(securityPackage: string, targetHost: string | undefined, peerCert: PeerCertificate | undefined, flags: number | undefined);
22
- /**
23
- * Retrieves the username of the logged in user
24
- * @returns user name including domain
25
- */
26
- static getLogonUserName(): string;
27
- /**
28
- * Transforms target TLS certificate into a channel binding application data buffer
29
- * @param peerCert Target TLS certificate
30
- * @returns Application data buffer
31
- */
32
- private getChannelBindingsApplicationData;
33
- /**
34
- * Releases all allocated resources for the authorization context.
35
- * Should be called when the context is no longer required, such as when the
36
- * socket was closed.
37
- */
38
- freeAuthContext(): void;
39
- /**
40
- * Creates an authentication request token
41
- * @returns Raw token buffer
42
- */
43
- createAuthRequest(): Buffer;
44
- /**
45
- * Creates an authentication request header
46
- * @returns The www-authenticate header
47
- */
48
- createAuthRequestHeader(): string;
49
- /**
50
- * Creates an authentication response token
51
- * @param inTokenHeader The www-authentication header received from the target
52
- * in response to the authentication request
53
- * @returns Raw token buffer. May be empty if Negotiate handshake is complete.
54
- */
55
- createAuthResponse(inTokenHeader: string): Buffer;
56
- private isNtlmV1;
57
- /**
58
- * Creates an authentication response header
59
- * @param inTokenHeader The www-authentication header received from the target
60
- * in response to the authentication request
61
- * @returns The www-authenticate header. May be an empty string if Negotiate handshake is complete.
62
- */
63
- createAuthResponseHeader(inTokenHeader: string): string;
64
- }
@@ -1,162 +0,0 @@
1
- #include "auth-context.hh"
2
- #include "secur32-facade.hh"
3
- #include "exception-handler.hh"
4
-
5
- AuthContext::AuthContext() {
6
- credHandle = {};
7
- lifeTime = {};
8
- ctxHandle = {};
9
- flags = 0;
10
- maxTokenLength = 0;
11
- outToken = nullptr;
12
- outTokenLength = 0;
13
- credHandleAllocated = false;
14
- ctxHandleAllocated = false;
15
- channelBindings = {};
16
- channelBindingsLength = 0;
17
- targetHostnameSpn = nullptr;
18
- };
19
-
20
- AuthContext::~AuthContext() {
21
- // Napi::Env is not available in destructor, but we can still do cleanup without
22
- // reporting JS exceptions to Node
23
- Cleanup(0);
24
- }
25
-
26
- void AuthContext::Cleanup(Napi::Env* env) {
27
- if (credHandleAllocated) {
28
- Secur32Facade::FreeCredentialsHandle(&credHandle, env);
29
- credHandleAllocated = false;
30
- }
31
- if (ctxHandleAllocated) {
32
- Secur32Facade::FreeContextHandle(&ctxHandle, env);
33
- ctxHandleAllocated = false;
34
- }
35
- if (outToken) {
36
- delete outToken;
37
- outToken = nullptr;
38
- }
39
- if (targetHostnameSpn) {
40
- delete targetHostnameSpn;
41
- targetHostnameSpn = nullptr;;
42
- }
43
- }
44
-
45
- bool AuthContext::Init(std::string* securityPackageName, std::string* targetHost, Napi::Buffer<unsigned char>& applicationDataBuffer, unsigned long flags, Napi::Env* env) {
46
- this->flags = flags;
47
- auto packageNameLen = securityPackageName->copy(packageName, sizeof(packageName) - 1);
48
- packageName[packageNameLen] = '\0';
49
- targetHostname = *targetHost;
50
- if (targetHostname.length() > 0) {
51
- int len = targetHostname.length() + 5 + 1;
52
- targetHostnameSpn = new char[len];
53
- strncpy(targetHostnameSpn, ("HTTP/" + targetHostname).c_str(), len);
54
- }
55
- maxTokenLength = Secur32Facade::GetMaxTokenLength(packageName, env);
56
- SetupChannelBindings(applicationDataBuffer);
57
- Secur32Facade::AcquireCredentialsHandle(packageName, &credHandle, &lifeTime, env);
58
- if (env->IsExceptionPending()) {
59
- Cleanup(env);
60
- return false;
61
- }
62
- credHandleAllocated = true;
63
- return true;
64
- }
65
-
66
- void AuthContext::SetupChannelBindings(Napi::Buffer<unsigned char>& applicationDataBuffer) {
67
- if (applicationDataBuffer.Length() > 0) {
68
- channelBindings.secChannelBindings.dwInitiatorAddrType = 0;
69
- channelBindings.secChannelBindings.cbInitiatorLength = 0;
70
- channelBindings.secChannelBindings.dwInitiatorOffset = 0;
71
- channelBindings.secChannelBindings.dwAcceptorAddrType = 0;
72
- channelBindings.secChannelBindings.cbAcceptorLength = 0;
73
- channelBindings.secChannelBindings.dwAcceptorOffset = 0;
74
- channelBindings.secChannelBindings.cbApplicationDataLength = applicationDataBuffer.Length();
75
- channelBindings.secChannelBindings.dwApplicationDataOffset = 32;
76
- memcpy(channelBindings.applicationData, applicationDataBuffer.Data(), applicationDataBuffer.Length());
77
- channelBindingsLength = (32 + applicationDataBuffer.Length());
78
- }
79
- }
80
-
81
- bool AuthContext::InitContext(Napi::Env* env) {
82
- SecBufferDesc outSecBufferDesc;
83
- SecBuffer outSecBuff;
84
- outToken = new unsigned char[maxTokenLength];
85
-
86
- outSecBufferDesc.ulVersion = 0;
87
- outSecBufferDesc.cBuffers = 1;
88
- outSecBufferDesc.pBuffers = &outSecBuff;
89
-
90
- outSecBuff.cbBuffer = maxTokenLength;
91
- outSecBuff.BufferType = SECBUFFER_TOKEN;
92
- outSecBuff.pvBuffer = outToken;
93
-
94
- int result = Secur32Facade::InitializeSecurityContext(
95
- NULL, &outSecBufferDesc, targetHostnameSpn, &credHandle, &ctxHandle, flags, &lifeTime, env);
96
- if (env->IsExceptionPending()) {
97
- Cleanup(env);
98
- return false;
99
- }
100
- if (result != SEC_I_CONTINUE_NEEDED && result != SEC_E_OK) {
101
- ExceptionHandler::CreateAndThrow(*env, "Init security context did not return SEC_I_CONTINUE_NEEDED or SEC_E_OK. Result: ", result);
102
- Cleanup(env);
103
- return false;
104
- }
105
- ctxHandleAllocated = true;
106
- outTokenLength = outSecBuff.cbBuffer;
107
- return true;
108
- }
109
-
110
- bool AuthContext::HandleResponse(
111
- Napi::Buffer<unsigned char>& inTokenBuffer,
112
- Napi::Env* env) {
113
- SecBufferDesc outSecBufferDesc;
114
- SecBuffer outSecBuff;
115
- SecBufferDesc inSecBufferDesc;
116
- SecBuffer inSecBuffers[2];
117
-
118
- outSecBufferDesc.ulVersion = 0;
119
- outSecBufferDesc.cBuffers = 1;
120
- outSecBufferDesc.pBuffers = &outSecBuff;
121
-
122
- outSecBuff.cbBuffer = maxTokenLength;
123
- outSecBuff.BufferType = SECBUFFER_TOKEN;
124
- outSecBuff.pvBuffer = outToken;
125
-
126
- inSecBufferDesc.ulVersion = 0;
127
- inSecBufferDesc.cBuffers = 1;
128
- inSecBufferDesc.pBuffers = inSecBuffers;
129
-
130
- inSecBuffers[0].cbBuffer = inTokenBuffer.Length();
131
- inSecBuffers[0].BufferType = SECBUFFER_TOKEN;
132
- inSecBuffers[0].pvBuffer = inTokenBuffer.Data();
133
-
134
- if (channelBindingsLength > 0) {
135
- inSecBufferDesc.cBuffers++;
136
- inSecBuffers[1].cbBuffer = channelBindingsLength;
137
- inSecBuffers[1].BufferType = SECBUFFER_CHANNEL_BINDINGS;
138
- inSecBuffers[1].pvBuffer = &channelBindings;
139
- }
140
-
141
- auto result = Secur32Facade::InitializeSecurityContext(&inSecBufferDesc, &outSecBufferDesc, targetHostnameSpn, &credHandle, &ctxHandle, flags, &lifeTime, env);
142
- if (env->IsExceptionPending()) {
143
- Cleanup(env);
144
- return false;
145
- }
146
- if (result != SEC_I_CONTINUE_NEEDED && result != SEC_E_OK) {
147
- ExceptionHandler::CreateAndThrow(*env, "Init security context did not return SEC_I_CONTINUE_NEEDED or SEC_E_OK. Result: ", result);
148
- Cleanup(env);
149
- return false;
150
- }
151
-
152
- outTokenLength = outSecBuff.cbBuffer;
153
- return true;
154
- }
155
-
156
- Napi::Buffer<unsigned char> AuthContext::OutToken(Napi::Env* env) {
157
- if (outToken) {
158
- return Napi::Buffer<unsigned char>::Copy(*env, outToken, outTokenLength);
159
- } else {
160
- return Napi::Buffer<unsigned char>::Buffer();
161
- }
162
- }
@@ -1,52 +0,0 @@
1
- #ifndef AUTH_CONTEXT_HH
2
- #define AUTH_CONTEXT_HH
3
-
4
- #define SECURITY_WIN32
5
-
6
- #include <napi.h>
7
-
8
- #include <windows.h>
9
- #include <sspi.h>
10
- #include <Secext.h>
11
- #include <Security.h>
12
-
13
- class AuthContext {
14
- public:
15
- char packageName[128];
16
- std::string targetHostname;
17
- char* targetHostnameSpn;
18
- CredHandle credHandle;
19
- SECURITY_INTEGER lifeTime;
20
- struct _SecHandle ctxHandle;
21
- unsigned long flags;
22
- unsigned long maxTokenLength;
23
- unsigned char* outToken;
24
- unsigned long outTokenLength;
25
-
26
- private:
27
- struct SecChannelBindingsCombined {
28
- struct _SEC_CHANNEL_BINDINGS secChannelBindings;
29
- unsigned char applicationData[128];
30
- };
31
- struct SecChannelBindingsCombined channelBindings;
32
- unsigned long channelBindingsLength;
33
-
34
- bool credHandleAllocated;
35
- bool ctxHandleAllocated;
36
-
37
- public:
38
- AuthContext();
39
- virtual ~AuthContext();
40
- void Cleanup(Napi::Env* env);
41
-
42
- bool Init(std::string* packageName, std::string* targetHost, Napi::Buffer<unsigned char>& applicationDataBuffer, unsigned long flags, Napi::Env* env);
43
- bool InitContext(Napi::Env* env);
44
- bool HandleResponse(Napi::Buffer<unsigned char>& inTokenBuffer, Napi::Env* env);
45
-
46
- Napi::Buffer<unsigned char> OutToken(Napi::Env* env);
47
-
48
- private:
49
- void SetupChannelBindings(Napi::Buffer<unsigned char>& applicationDataBuffer);
50
- };
51
-
52
- #endif
@@ -1,25 +0,0 @@
1
- #include "exception-handler.hh"
2
-
3
- void ExceptionHandler::CreateAndThrow(Napi::Env& env, std::string& message) {
4
- if (env.IsExceptionPending()) {
5
- // Merge exceptions if an exception has already been thrown
6
- auto error = env.GetAndClearPendingException();
7
- message = error.Message() + "\n" + message;
8
- }
9
- Napi::Error::New(env, message).ThrowAsJavaScriptException();
10
- }
11
-
12
- void ExceptionHandler::CreateAndThrow(Napi::Env& env, const char* message) {
13
- std::string exMessage = message;
14
- CreateAndThrow(env, exMessage);
15
- }
16
-
17
- void ExceptionHandler::CreateAndThrow(Napi::Env& env, const char* message, int resultCode) {
18
- std::string exMessage = message;
19
- CreateAndThrow(env, exMessage, resultCode);
20
- }
21
-
22
- void ExceptionHandler::CreateAndThrow(Napi::Env& env, std::string& message, int resultCode) {
23
- message = message + std::to_string(resultCode);
24
- CreateAndThrow(env, message);
25
- }
@@ -1,15 +0,0 @@
1
- #ifndef EXCEPTION_HANDLER_HH
2
- #define EXCEPTION_HANDLER_HH
3
-
4
- #include <string.h>
5
- #include <napi.h>
6
-
7
- class ExceptionHandler {
8
- public:
9
- static void CreateAndThrow(Napi::Env& env, const char* message);
10
- static void CreateAndThrow(Napi::Env& env, std::string& message);
11
- static void CreateAndThrow(Napi::Env& env, const char* message, int resultCode);
12
- static void CreateAndThrow(Napi::Env& env, std::string& message, int resultCode);
13
- };
14
-
15
- #endif
@@ -1,243 +0,0 @@
1
- #include "secur32-facade.hh"
2
- #include "exception-handler.hh"
3
- #include "auth-context.hh"
4
-
5
- #include <Secext.h>
6
- #include <Security.h>
7
- #include <string.h>
8
-
9
- std::map<unsigned long, std::shared_ptr<AuthContext>> Secur32Facade::acMap = std::map<unsigned long, std::shared_ptr<AuthContext>>();
10
- unsigned long Secur32Facade::acKey = 0;
11
-
12
- Napi::String Secur32Facade::GetLogonUserName(const Napi::CallbackInfo& info) {
13
- static char _userName[256] = "";
14
- Napi::Env env = info.Env();
15
- if (_userName[0]) {
16
- return Napi::String::New(env, _userName);
17
- }
18
-
19
- unsigned long userNameLength = 256;
20
- int result = ::GetUserNameExA(NameSamCompatible, _userName, &userNameLength);
21
- if (result < 0) {
22
- ExceptionHandler::CreateAndThrow(env, "Could not get user name of logged in user. Result: ", result);
23
- return Napi::String::New(env, "");
24
- }
25
- _userName[userNameLength] = '\0';
26
- auto name = Napi::String::New(env, _userName);
27
-
28
- return name;
29
- }
30
-
31
- unsigned int Secur32Facade::GetMaxTokenLength(char* packageName, Napi::Env* env) {
32
- static unsigned int _maxTokenLength = 0;
33
-
34
- if (_maxTokenLength != 0) {
35
- return _maxTokenLength;
36
- }
37
-
38
- PSecPkgInfoA pkgInfo;
39
- int result = ::QuerySecurityPackageInfoA(packageName, &pkgInfo);
40
- if (result != 0) {
41
- ExceptionHandler::CreateAndThrow(*env, "Could not get SecurityPackageInfo. Result: ", result);
42
- return 0;
43
- }
44
- _maxTokenLength = pkgInfo->cbMaxToken;
45
- result = ::FreeContextBuffer(pkgInfo);
46
- if (result != 0) {
47
- ExceptionHandler::CreateAndThrow(*env, "Could not free context buffer. Result: ", result);
48
- return 0;
49
- }
50
- return _maxTokenLength;
51
- }
52
-
53
- void Secur32Facade::AcquireCredentialsHandle(char* packageName, CredHandle* credHandle, SECURITY_INTEGER* lifeTime, Napi::Env* env) {
54
- int result = ::AcquireCredentialsHandleA(NULL, packageName, SECPKG_CRED_OUTBOUND, NULL, NULL, NULL, NULL, credHandle, lifeTime);
55
- if (result < 0) {
56
- ExceptionHandler::CreateAndThrow(*env, "Could not acquire credentials handle. Result: ", result);
57
- }
58
- }
59
-
60
- void Secur32Facade::FreeCredentialsHandle(CredHandle* credHandle, Napi::Env* env) {
61
- int result = ::FreeCredentialsHandle(credHandle);
62
- if (result != 0 && env != 0) {
63
- ExceptionHandler::CreateAndThrow(*env, "Could not free credentials handle. Result: ", result);
64
- }
65
- }
66
-
67
- int Secur32Facade::InitializeSecurityContext(
68
- SecBufferDesc* inSecBufferDesc,
69
- SecBufferDesc* outSecBufferDesc,
70
- char* targetHostSpn,
71
- CredHandle* credHandle,
72
- struct _SecHandle* ctxHandle,
73
- unsigned long flags,
74
- SECURITY_INTEGER* lifeTime,
75
- Napi::Env* env)
76
- {
77
- int result = 0;
78
- unsigned long ignored;
79
-
80
- if (inSecBufferDesc == NULL) {
81
- result = ::InitializeSecurityContextA(
82
- credHandle,
83
- NULL,
84
- targetHostSpn,
85
- flags,
86
- 0,
87
- SECURITY_NATIVE_DREP,
88
- NULL,
89
- 0,
90
- ctxHandle,
91
- outSecBufferDesc,
92
- &ignored,
93
- lifeTime
94
- );
95
- } else {
96
- result = ::InitializeSecurityContextA(
97
- credHandle,
98
- ctxHandle,
99
- targetHostSpn,
100
- flags,
101
- 0,
102
- SECURITY_NATIVE_DREP,
103
- inSecBufferDesc,
104
- 0,
105
- ctxHandle,
106
- outSecBufferDesc,
107
- &ignored,
108
- lifeTime
109
- );
110
- }
111
- if (result < 0) {
112
- ExceptionHandler::CreateAndThrow(*env, "Could not init security context. Result: ", result);
113
- }
114
- return result;
115
- }
116
-
117
- void Secur32Facade::FreeContextHandle(struct _SecHandle* ctxHandle, Napi::Env* env) {
118
- int result = ::DeleteSecurityContext(ctxHandle);
119
- if (result != 0 && env != 0) {
120
- ExceptionHandler::CreateAndThrow(*env, "Could not delete security context. Result: ", result);
121
- }
122
- }
123
-
124
- unsigned long Secur32Facade::GetDefaultFlags(std::string securityPackageName) {
125
- if (securityPackageName == "Negotiate" || securityPackageName == "Kerberos") {
126
- return ISC_REQ_MUTUAL_AUTH | ISC_REQ_SEQUENCE_DETECT;
127
- }
128
- return 0;
129
- }
130
-
131
- Napi::Number Secur32Facade::CreateAuthContext(const Napi::CallbackInfo& info) {
132
- Napi::Env env = info.Env();
133
- if (info.Length() < 4) {
134
- ExceptionHandler::CreateAndThrow(env, "Wrong number of arguments");
135
- return Napi::Number::New(env, 0);
136
- }
137
-
138
- if (!info[0].IsString() || !info[1].IsString() || !info[2].IsBuffer() || !(info[3].IsUndefined() || info[3].IsNumber())) {
139
- ExceptionHandler::CreateAndThrow(env, "Wrong argument types");
140
- return Napi::Number::New(env, 0);
141
- }
142
- auto securityPackageName = info[0].ToString();
143
- auto targetHost = info[1].ToString();
144
- auto applicationDataBuffer = info[2].As<Napi::Buffer<unsigned char>>();
145
- auto flags = info[3].IsNumber() ? (unsigned long)(info[3].ToNumber().Uint32Value()) : GetDefaultFlags(securityPackageName);
146
-
147
- auto ac = std::make_shared<AuthContext>();
148
- ac->Init(&(securityPackageName.Utf8Value()), &(targetHost.Utf8Value()), applicationDataBuffer, flags, &env);
149
- acKey++;
150
- acMap[acKey] = ac;
151
- return Napi::Number::New(env, acKey);
152
- }
153
-
154
- Napi::Number Secur32Facade::FreeAuthContext(const Napi::CallbackInfo& info) {
155
- Napi::Env env = info.Env();
156
- if (info.Length() < 1) {
157
- ExceptionHandler::CreateAndThrow(env, "Wrong number of arguments");
158
- return Napi::Number::New(env, 0);
159
- }
160
-
161
- if (!info[0].IsNumber()) {
162
- ExceptionHandler::CreateAndThrow(env, "Wrong argument types");
163
- return Napi::Number::New(env, 0);
164
- }
165
-
166
- auto acKey = info[0].ToNumber().Uint32Value();
167
- size_t erased = 0;
168
- if (acMap.find(acKey) != acMap.end()) {
169
- acMap[acKey]->Cleanup(&env);
170
- erased = acMap.erase(acKey);
171
- }
172
- return Napi::Number::New(env, erased);
173
- }
174
-
175
- /**
176
- * Creates a NTLM type 1 authentication token
177
- */
178
- Napi::Buffer<unsigned char> Secur32Facade::CreateAuthRequest(const Napi::CallbackInfo& info) {
179
- Napi::Env env = info.Env();
180
- if (info.Length() < 1) {
181
- ExceptionHandler::CreateAndThrow(env, "Wrong number of arguments");
182
- return Napi::Buffer<unsigned char>::Buffer();
183
- }
184
-
185
- if (!info[0].IsNumber()) {
186
- ExceptionHandler::CreateAndThrow(env, "Wrong argument types");
187
- return Napi::Buffer<unsigned char>::Buffer();
188
- }
189
-
190
- auto acKey = info[0].ToNumber().Uint32Value();
191
-
192
- if (acMap.find(acKey) == acMap.end()) {
193
- ExceptionHandler::CreateAndThrow(env, "AuthContext not found");
194
- return Napi::Buffer<unsigned char>::Buffer();
195
- }
196
-
197
- auto ac = acMap[acKey];
198
- ac->InitContext(&env);
199
- return ac->OutToken(&env);
200
- }
201
-
202
- /**
203
- * Creates a NTLM type 3 authentication token
204
- */
205
- Napi::Buffer<unsigned char> Secur32Facade::CreateAuthResponse(const Napi::CallbackInfo& info) {
206
- Napi::Env env = info.Env();
207
- if (info.Length() < 2) {
208
- ExceptionHandler::CreateAndThrow(env, "Wrong number of arguments");
209
- return Napi::Buffer<unsigned char>::Buffer();
210
- }
211
-
212
- if (!info[0].IsNumber() && !info[1].IsBuffer()) {
213
- ExceptionHandler::CreateAndThrow(env, "Wrong argument types");
214
- return Napi::Buffer<unsigned char>::Buffer();
215
- }
216
-
217
- auto acKey = info[0].ToNumber().Uint32Value();
218
- if (acMap.find(acKey) == acMap.end()) {
219
- ExceptionHandler::CreateAndThrow(env, "AuthContext not found");
220
- return Napi::Buffer<unsigned char>::Buffer();
221
- }
222
-
223
- auto inTokenBuffer = info[1].As<Napi::Buffer<unsigned char>>();
224
- auto ac = acMap[acKey];
225
- ac->HandleResponse(inTokenBuffer, &env);
226
- return ac->OutToken(&env);
227
- }
228
-
229
- Napi::Object Init(Napi::Env env, Napi::Object exports) {
230
- exports.Set(Napi::String::New(env, "getLogonUserName"),
231
- Napi::Function::New(env, Secur32Facade::GetLogonUserName));
232
- exports.Set(Napi::String::New(env, "createAuthContext"),
233
- Napi::Function::New(env, Secur32Facade::CreateAuthContext));
234
- exports.Set(Napi::String::New(env, "freeAuthContext"),
235
- Napi::Function::New(env, Secur32Facade::FreeAuthContext));
236
- exports.Set(Napi::String::New(env, "createAuthRequest"),
237
- Napi::Function::New(env, Secur32Facade::CreateAuthRequest));
238
- exports.Set(Napi::String::New(env, "createAuthResponse"),
239
- Napi::Function::New(env, Secur32Facade::CreateAuthResponse));
240
- return exports;
241
- }
242
-
243
- NODE_API_MODULE(WinSso, Init)
@@ -1,56 +0,0 @@
1
- #ifndef SECUR32_FACADE_HH
2
- #define SECUR32_FACADE_HH
3
-
4
- #define SECURITY_WIN32
5
-
6
- #include <napi.h>
7
-
8
- #include <windows.h>
9
- #include <sspi.h>
10
- #include <map>
11
-
12
- class AuthContext;
13
-
14
- class Secur32Facade {
15
- private:
16
- static std::map<unsigned long, std::shared_ptr<AuthContext>> acMap;
17
- static unsigned long acKey;
18
-
19
- public:
20
- /**
21
- * Returns the full username (domain\username) of the user running the process
22
- */
23
- static Napi::String GetLogonUserName(const Napi::CallbackInfo& info);
24
-
25
- static Napi::Number Secur32Facade::CreateAuthContext(const Napi::CallbackInfo& info);
26
- static Napi::Number Secur32Facade::FreeAuthContext(const Napi::CallbackInfo& info);
27
- /**
28
- * Creates a NTLM type 1 authentication token
29
- */
30
- static Napi::Buffer<unsigned char> CreateAuthRequest(const Napi::CallbackInfo& info);
31
-
32
- /**
33
- * Creates a NTLM type 3 authentication token
34
- */
35
- static Napi::Buffer<unsigned char> CreateAuthResponse(const Napi::CallbackInfo& info);
36
-
37
- static unsigned int GetMaxTokenLength(char* packageName, Napi::Env* env);
38
- static void AcquireCredentialsHandle(char* packageName, CredHandle* credHandle, SECURITY_INTEGER* lifeTime, Napi::Env* env);
39
- static void FreeCredentialsHandle(CredHandle* credHandle, Napi::Env* env);
40
- static int InitializeSecurityContext(
41
- SecBufferDesc* inSecBufferDesc,
42
- SecBufferDesc* outSecBufferDesc,
43
- char* targetHost,
44
- CredHandle* credHandle,
45
- struct _SecHandle* ctxHandle,
46
- unsigned long flags,
47
- SECURITY_INTEGER* lifeTime,
48
- Napi::Env* env);
49
- static void FreeContextHandle(struct _SecHandle* ctxHandle, Napi::Env* env);
50
- static Napi::Object Init(Napi::Env env, Napi::Object exports);
51
-
52
- private:
53
- static unsigned long GetDefaultFlags(std::string securityPackageName);
54
- };
55
-
56
- #endif