@b-jones-rfd/ntlm-handshake 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 B-Jones-RFD
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,244 @@
1
- # Temporary Holding Version
1
+ [![CI](https://github.com/B-Jones-RFD/ntlm-handshake/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/B-Jones-RFD/ntlm-handshake/actions/workflows/main.yml)
2
+ [![npm version](https://img.shields.io/npm/v/%40b-jones-rfd%2Fntlm-handshake?style=flat-square)](https://www.npmjs.com/package/@b-jones-rfd/ntlm-handshake)
3
+ [![npm unpacked size](https://img.shields.io/npm/unpacked-size/%40b-jones-rfd%2Fntlm-handshake?style=flat-square)](https://www.npmjs.com/package/@b-jones-rfd/ntlm-handshake)
4
+ [![node](https://img.shields.io/node/v/%40b-jones-rfd%2Fntlm-handshake?style=flat-square)](https://nodejs.org)
5
+ [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ # NTLM Handshake
8
+
9
+ NTLMv2-authenticated HTTP requests for Node.js, with no dependencies. A
10
+ connection is bound to one NTLM-protected host, typically an IIS site such as
11
+ SharePoint Server on-premises, and runs the NTLM handshake for each call on a
12
+ single socket with `node:http` and `node:https`. Every call returns a typed
13
+ `Result` instead of throwing.
14
+
15
+ ## Requirements
16
+
17
+ - **Node.js 22.12 or later.** The package is ESM only; from 22.12, CommonJS projects can `require()` it too.
18
+ - **TypeScript (optional):** any release from the last two years.
19
+ - **A server that offers `WWW-Authenticate: NTLM` and negotiates NTLMv2** over HTTP/1.1 or HTTPS. Not supported: NTLMv1 and LM, Kerberos, SPNEGO `Negotiate`, servers that require a message integrity code (MIC), Extended Protection (channel binding) set to Required, and proxy authentication.
20
+ - Nothing else. There are no runtime dependencies.
21
+
22
+ ## Installation
23
+
24
+ ```sh
25
+ npm i @b-jones-rfd/ntlm-handshake
26
+ # or
27
+ pnpm add @b-jones-rfd/ntlm-handshake
28
+ # or
29
+ yarn add @b-jones-rfd/ntlm-handshake
30
+ ```
31
+
32
+ ## Quick start
33
+
34
+ ```ts
35
+ import { createNtlmConnection } from '@b-jones-rfd/ntlm-handshake'
36
+
37
+ const connection = createNtlmConnection({
38
+ url: 'https://sharepoint.contoso.local/sites/finance/',
39
+ username: 'CONTOSO\\jsmith',
40
+ password: process.env.NTLM_PASSWORD!,
41
+ })
42
+
43
+ const ok = await connection.testConnection()
44
+ if (!ok.success) throw new Error(ok.error)
45
+
46
+ const res = await connection.request({
47
+ path: '_api/web?$select=Title',
48
+ headers: { Accept: 'application/json;odata=nometadata' },
49
+ })
50
+ if (res.success) console.log(JSON.parse(res.data.body))
51
+ else console.error(res.code, res.error)
52
+ ```
53
+
54
+ More examples: [`examples/basic.ts`](examples/basic.ts) checks the
55
+ credentials, [`examples/request.ts`](examples/request.ts) reads, writes and
56
+ streams a download, and [`examples/protocol.ts`](examples/protocol.ts) runs
57
+ the handshake by hand.
58
+
59
+ ## Usage
60
+
61
+ ### Connection
62
+
63
+ `createNtlmConnection(options)` binds every action to one host. It performs
64
+ no network I/O: credentials are captured and used on each call, and only
65
+ ever sent to the origin of `url`. It throws a `TypeError` naming the option
66
+ for malformed options, so a misconfiguration fails at startup.
67
+
68
+ | Option | Type | Required | Default | Description |
69
+ | -------------- | -------------------- | -------- | -------------------------- | ---------------------------------------------------------------------------------------------------- |
70
+ | `url` | `string` | Yes | | The `http:` or `https:` URL to connect to. Must not carry user info. |
71
+ | `username` | `string` | Yes | | Account name. `DOMAIN\user` and `user@domain` are split into user and domain. |
72
+ | `password` | `string` | Yes | | The account's password. Read it from the environment. |
73
+ | `domain` | `string` | No | From `username`, else `''` | NTLM (NetBIOS) domain. Wins over a domain in `username`. |
74
+ | `workstation` | `string` | No | `''` | Workstation name sent in the handshake. Empty sends none. |
75
+ | `timeout` | `number` | No | `30000` | Socket inactivity timeout for each leg, in milliseconds. |
76
+ | `agentOptions` | `https.AgentOptions` | No | | TLS and socket options for the per-call agent, such as `ca`. `keepAlive` and `maxSockets` are fixed. |
77
+ | `retry` | `RetryOptions` | No | Off | Retry transient failures on reads. See below. |
78
+
79
+ ### Standalone actions
80
+
81
+ Each action is also exported as a factory taking the same options, plus an
82
+ optional context from `createConnectionContext(options)`:
83
+
84
+ ```ts
85
+ import { request, testConnection } from '@b-jones-rfd/ntlm-handshake'
86
+
87
+ const check = testConnection(options)
88
+ const send = request(options)
89
+ const result = await check({ timeout: 5000 })
90
+ const lists = await send({ path: '_api/web/lists' })
91
+ ```
92
+
93
+ ### Results
94
+
95
+ Every action resolves to `Result<T>`: `{ success: true, data }` or a
96
+ `Failure` `{ success: false, error, code, status?, details?, retryAfterMs? }`.
97
+ Branch on `code`, never on the `error` text.
98
+
99
+ | `code` | Meaning |
100
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
101
+ | `HTTP` | The server answered with a non-2xx status other than 401/403. See `status`, and `details` for the body. |
102
+ | `AUTH` | 401 or 403 after the handshake: the server refused the credentials, or the account lacks access. |
103
+ | `PROTOCOL` | The server can't do NTLMv2: it offered no NTLM, sent a malformed challenge, offered only NTLMv1, or didn't ask for NTLM on a request with a body. |
104
+ | `INVALID_REQUEST` | The call was refused before anything was sent: its `path` is on another origin or carries user info, or a per-call option is malformed. |
105
+ | `TIMEOUT` | The socket was idle longer than `timeout`. |
106
+ | `ABORTED` | The call was cancelled through `signal`. |
107
+ | `NETWORK` | DNS, connection or TLS failure before a response arrived. |
108
+ | `PARSE` | The server answered 2xx, but the body was not in the expected shape. |
109
+ | `UNKNOWN` | Anything else. |
110
+
111
+ ### Retrying transient failures
112
+
113
+ Retry is off unless `retry` is set; `{}` turns on the defaults (`retries: 2`,
114
+ `baseDelayMs: 200`, `maxDelayMs: 5000`). Only reads are retried, with
115
+ exponential backoff and full jitter, honouring `Retry-After`. The default
116
+ predicate, `isTransientFailure`, retries `NETWORK`, `TIMEOUT` and HTTP 429,
117
+ 502, 503 and 504; pass `retryOn` to choose your own. A call whose body is a `Readable` is never
118
+ retried, since a stream can be sent only once.
119
+
120
+ ### Requests
121
+
122
+ `connection.request(options)` sends one request and runs the whole NTLM
123
+ handshake for it on one socket.
124
+
125
+ | Option | Type | Default | Description |
126
+ | -------------- | ---------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
127
+ | `path` | `string` | | Required. Resolved against `url` (see below). |
128
+ | `method` | `string` | `'GET'` | The HTTP method. |
129
+ | `headers` | `Record<string, string \| number>` | | Request headers. `Authorization`, `Connection` and `Host` are managed by the connection and dropped. |
130
+ | `body` | `string \| Uint8Array \| Readable` | | Sent only on the authenticated leg. A `Readable` goes out chunked unless you set `Content-Length`; if the call fails before it is sent, destroy it yourself. |
131
+ | `responseType` | `'text' \| 'buffer' \| 'stream'` | `'text'` | How a 2xx body is returned. |
132
+ | `probePath` | `string` | | Opens the handshake with a `GET` of this path instead. Resolved as `path` is. |
133
+ | `timeout` | `number` | `timeout` of the connection | Socket inactivity timeout for this call, in milliseconds. |
134
+ | `signal` | `AbortSignal` | | Cancels the call. |
135
+
136
+ **Where it goes.** `path` resolves against the connection's `url` by URL
137
+ rules. With `url` set to `https://sharepoint.contoso.local/sites/finance/`:
138
+
139
+ - `_api/web` gives `https://sharepoint.contoso.local/sites/finance/_api/web`;
140
+ - `/_api/web` gives `https://sharepoint.contoso.local/_api/web`;
141
+ - an absolute URL is used as is.
142
+
143
+ The result must be on `url`'s origin. Anything else, including a URL with
144
+ user info, is an `INVALID_REQUEST` failure, and nothing is sent.
145
+
146
+ **The response.** `data` is `{ status, headers, body }`, and `body` follows
147
+ `responseType`: a `string`, a `Uint8Array` (a `Buffer` at runtime), or a
148
+ `Readable`. A streamed body holds the socket until the stream closes, so
149
+ read it to the end or destroy it. The connection's `timeout` and the call's
150
+ `signal` still apply while it is read: a stall longer than `timeout`, or an
151
+ abort, destroys the stream with an error, so attach an `'error'` listener
152
+ (`pipeline` does). When the server answered without asking for NTLM, the body
153
+ was already read in full, and the stream replays it from memory. A non-2xx answer is always a failure:
154
+ `AUTH` for 401 and 403, `HTTP` otherwise, with the body as text in
155
+ `details`.
156
+
157
+ **The handshake.** The first leg sends the request's method and URL with no
158
+ body; the body goes only with the authenticated leg. If the server answers
159
+ that first leg without asking for NTLM:
160
+
161
+ - a request without a body takes that answer as its result (the server
162
+ allows anonymous access);
163
+ - a request with a body fails with `PROTOCOL`, and the body is never sent.
164
+
165
+ Use `probePath` when the request's own URL can't take a body-less first leg:
166
+ the handshake opens with a `GET` of `probePath`, and the request follows on
167
+ the same socket. If the probe isn't challenged, the request is sent without
168
+ authentication.
169
+
170
+ **Retry.** With the connection's `retry` set, `GET` and `HEAD` are retried on
171
+ transient failures. Other methods, and a call with a `Readable` body, are
172
+ sent once.
173
+
174
+ ### Protocol layer (`./protocol`)
175
+
176
+ `@b-jones-rfd/ntlm-handshake/protocol` exports the NTLMv2 messages on their
177
+ own, for a caller with its own HTTP transport. These are pure functions and,
178
+ unlike the connection, they throw `NtlmError` on malformed input. NTLM
179
+ authenticates the TCP connection, not the request, so all three legs must
180
+ use one keep-alive socket:
181
+
182
+ ```ts
183
+ import {
184
+ createAuthenticateMessage,
185
+ createNegotiateMessage,
186
+ extractNtlmChallenge,
187
+ parseChallengeMessage,
188
+ toAuthorizationHeader,
189
+ } from '@b-jones-rfd/ntlm-handshake/protocol'
190
+
191
+ const type1 = toAuthorizationHeader(createNegotiateMessage(credentials))
192
+ // Send it, and read the 401's WWW-Authenticate header, on one socket.
193
+ const challenge = parseChallengeMessage(extractNtlmChallenge(wwwAuthenticate))
194
+ const type3 = toAuthorizationHeader(
195
+ createAuthenticateMessage(challenge, credentials)
196
+ )
197
+ // Send the real request with `Authorization: type3` on the same socket.
198
+ ```
199
+
200
+ The credentials stay in your hands: you choose where the messages go.
201
+
202
+ ## API
203
+
204
+ Full generated reference:
205
+ **[b-jones-rfd.github.io/ntlm-handshake](https://b-jones-rfd.github.io/ntlm-handshake/)**.
206
+
207
+ | Action | Required options | `data` |
208
+ | ---------------- | ---------------- | ----------------- |
209
+ | `request` | `path` | `NtlmResponse<T>` |
210
+ | `testConnection` | none | `undefined` |
211
+
212
+ `./protocol`:
213
+
214
+ | Function | Input | Returns | Throws `NtlmError` |
215
+ | --------------------------- | ------------------------------- | --------------- | ----------------------------------- |
216
+ | `createNegotiateMessage` | credentials | `Uint8Array` | No |
217
+ | `extractNtlmChallenge` | the `WWW-Authenticate` value(s) | `Uint8Array` | When it carries no NTLM challenge |
218
+ | `parseChallengeMessage` | the challenge bytes | `NtlmChallenge` | When they are not a type 2 message |
219
+ | `createAuthenticateMessage` | the challenge, credentials | `Uint8Array` | When the server offered only NTLMv1 |
220
+ | `toAuthorizationHeader` | message bytes | `NTLM <base64>` | No |
221
+
222
+ ## Contributing
223
+
224
+ This is a personal project maintained for my own work and is not accepting
225
+ contributions. Bug reports via
226
+ [issues](https://github.com/B-Jones-RFD/ntlm-handshake/issues) are welcome;
227
+ security problems go through [private reporting](SECURITY.md).
228
+
229
+ If you want to build it locally:
230
+
231
+ ```sh
232
+ pnpm install
233
+ pnpm dev # vitest in watch mode
234
+ pnpm run ci # lint, test, build, package checks
235
+ pnpm run docs # generate the API reference into docs/
236
+ ```
237
+
238
+ ## Versioning
239
+
240
+ [SemVer](https://semver.org/). See the [CHANGELOG](CHANGELOG.md) for release notes and breaking changes.
241
+
242
+ ## License
243
+
244
+ [MIT](LICENSE)
@@ -0,0 +1,308 @@
1
+ import { Readable } from "node:stream";
2
+ import { IncomingHttpHeaders } from "node:http";
3
+ import { AgentOptions } from "node:https";
4
+ /**
5
+ * Public types for `@b-jones-rfd/ntlm-handshake`.
6
+ *
7
+ * Every action resolves to a {@link Result} and never throws: check
8
+ * `result.success` to narrow to {@link Success} or {@link Failure}.
9
+ *
10
+ * @module
11
+ */
12
+ /** Successful action result. The payload is in `data`. */
13
+ type Success<T> = {
14
+ success: true;
15
+ data: T;
16
+ };
17
+ /**
18
+ * Classification of a {@link Failure}. Branch on this rather than on the
19
+ * `error` text.
20
+ *
21
+ * - `HTTP`: the server answered with a non-2xx status other than 401/403. See `status` and `details`.
22
+ * - `AUTH`: 401 or 403 after the handshake: the server rejected the credentials or the account lacks access.
23
+ * - `PROTOCOL`: the server can't do NTLMv2. It offered no NTLM, sent a malformed challenge, offered only NTLMv1, or didn't ask for NTLM on a request that has a body.
24
+ * - `INVALID_REQUEST`: the call was refused before anything was sent: its `path` is on another origin or carries user info, or a per-call option is malformed.
25
+ * - `TIMEOUT`: the socket was idle longer than `timeout`.
26
+ * - `ABORTED`: the request was cancelled through `signal`.
27
+ * - `NETWORK`: DNS, connection or TLS failure before a response arrived.
28
+ * - `PARSE`: the server answered 2xx but the body was not in the expected shape.
29
+ * - `UNKNOWN`: anything else.
30
+ */
31
+ type FailureCode = 'HTTP' | 'AUTH' | 'PROTOCOL' | 'INVALID_REQUEST' | 'TIMEOUT' | 'ABORTED' | 'NETWORK' | 'PARSE' | 'UNKNOWN';
32
+ /**
33
+ * Failed action result.
34
+ *
35
+ * `error` is a human-readable message prefixed with the action name, for
36
+ * logging. It never contains credentials. `code` classifies the failure.
37
+ */
38
+ type Failure = {
39
+ success: false;
40
+ /** `Error in <action>: …`, for logging. */
41
+ error: string;
42
+ /** What went wrong. Branch on this, not on `error`. */
43
+ code: FailureCode;
44
+ /** HTTP status of the response, for `HTTP` and `AUTH` failures, and `PROTOCOL` failures that came with one. */
45
+ status?: number;
46
+ /** The response body as text, when a non-2xx response carried one. */
47
+ details?: unknown;
48
+ /** How long the server asked clients to wait, from a `Retry-After` header. The retry logic honours it. */
49
+ retryAfterMs?: number;
50
+ };
51
+ /**
52
+ * Discriminated union returned by every action.
53
+ *
54
+ * @example
55
+ * const res = await connection.testConnection()
56
+ * if (res.success) console.log('Authenticated')
57
+ * else console.error(res.code, res.error)
58
+ */
59
+ type Result<T> = Success<T> | Failure;
60
+ /**
61
+ * Opt-in retry for read actions. Writes are never retried automatically.
62
+ * Delays use exponential backoff with full jitter:
63
+ * `random(0, min(maxDelayMs, baseDelayMs * 2^(attempt - 1)))`. When the server
64
+ * sent `Retry-After`, that wait is used instead; if it exceeds `maxDelayMs`,
65
+ * retrying stops and the failure is returned with `retryAfterMs` set.
66
+ */
67
+ type RetryOptions = {
68
+ /** Extra attempts after the first failure. @defaultValue `2` */
69
+ retries?: number;
70
+ /** Base delay in milliseconds. @defaultValue `200` */
71
+ baseDelayMs?: number;
72
+ /** Upper bound on a single delay, including a server-requested `Retry-After`. @defaultValue `5000` */
73
+ maxDelayMs?: number;
74
+ /**
75
+ * Decides whether a failed attempt is retried. `attempt` is 1-based. The
76
+ * default is {@link isTransientFailure}. `ABORTED` is never retried.
77
+ */
78
+ retryOn?: (failure: Failure, attempt: number) => boolean;
79
+ };
80
+ /** The Windows account an NTLM handshake authenticates as. */
81
+ type NtlmCredentials = {
82
+ /**
83
+ * Account name. `DOMAIN\user` and `user@domain` are split into user and
84
+ * domain; an explicit `domain` wins over either.
85
+ */
86
+ username: string;
87
+ /** Password for `username`. Read it from the environment rather than hard-coding it. */
88
+ password: string;
89
+ /**
90
+ * NTLM (NetBIOS) domain of the account, e.g. `'CONTOSO'`. Leave it out for
91
+ * an account local to the server.
92
+ * @defaultValue the domain in `username`, else `''`
93
+ */
94
+ domain?: string;
95
+ /**
96
+ * Workstation name sent in the handshake. Empty sends none, so the client's
97
+ * host name is not disclosed.
98
+ * @defaultValue `''`
99
+ */
100
+ workstation?: string;
101
+ };
102
+ /** Where to connect and how to authenticate. */
103
+ type NtlmConnectionOptions = NtlmCredentials & {
104
+ /**
105
+ * The `http:` or `https:` URL the connection is bound to. Credentials are
106
+ * only ever sent to this URL's origin.
107
+ */
108
+ url: string;
109
+ /**
110
+ * Socket inactivity timeout for each leg of the handshake, in
111
+ * milliseconds. A call fails with `TIMEOUT` if no bytes arrive for this
112
+ * long. Use `signal` with `AbortSignal.timeout()` to cap the total time.
113
+ * @defaultValue `30000`
114
+ */
115
+ timeout?: number;
116
+ /**
117
+ * Options for the per-call `https.Agent` (or `http.Agent`), such as `ca`
118
+ * for an internal certificate authority. `keepAlive` and `maxSockets` are
119
+ * fixed by the handshake and cannot be overridden.
120
+ * @example
121
+ * agentOptions: { ca: fs.readFileSync('corp-root-ca.pem') }
122
+ */
123
+ agentOptions?: AgentOptions;
124
+ /**
125
+ * Retries transient failures on reads. Off unless set; `{}` turns on the
126
+ * defaults.
127
+ * @example
128
+ * retry: { retries: 3, baseDelayMs: 500 }
129
+ */
130
+ retry?: RetryOptions;
131
+ };
132
+ /** Options for {@link NtlmConnection.testConnection}. */
133
+ type TestConnectionOptions = {
134
+ /** Overrides the connection's `timeout` for this call. */
135
+ timeout?: number;
136
+ /**
137
+ * Cancels the call, which then fails with `ABORTED`.
138
+ * @example
139
+ * connection.testConnection({ signal: AbortSignal.timeout(5000) })
140
+ */
141
+ signal?: AbortSignal;
142
+ };
143
+ /** Options for {@link NtlmConnection.request}. */
144
+ type RequestOptions = {
145
+ /**
146
+ * Where to send the request, resolved against the connection's `url` by
147
+ * URL rules: `_api/web` resolves under `url`'s path, `/_api/web` replaces
148
+ * it, and an absolute URL is used as is. The result must be on `url`'s
149
+ * origin, or the call fails with `INVALID_REQUEST` before anything is sent.
150
+ * @example
151
+ * // url: 'https://sharepoint.contoso.local/sites/finance/'
152
+ * path: '_api/web/lists' // https://sharepoint.contoso.local/sites/finance/_api/web/lists
153
+ */
154
+ path: string;
155
+ /** HTTP method. @defaultValue `'GET'` */
156
+ method?: string;
157
+ /**
158
+ * Request headers. `Authorization`, `Connection` and `Host` belong to the
159
+ * handshake and the connection's origin, so they are dropped.
160
+ */
161
+ headers?: Record<string, string | number>;
162
+ /**
163
+ * Request body, sent only with the authenticated leg. A string or
164
+ * `Uint8Array` goes out with a `Content-Length`. A `Readable` goes out
165
+ * chunked unless you set `Content-Length`, can be sent only once, and is
166
+ * never retried. If the call fails before the body is sent, the stream is
167
+ * left unread: destroy it yourself (for a file stream, that closes the file).
168
+ */
169
+ body?: string | Uint8Array | Readable;
170
+ /**
171
+ * How a 2xx body is returned: decoded UTF-8 text, the bytes, or a
172
+ * `Readable` that releases the socket when it closes. A non-2xx body is
173
+ * always read as text, into the failure's `details`.
174
+ * @defaultValue `'text'`
175
+ */
176
+ responseType?: 'text' | 'buffer' | 'stream';
177
+ /**
178
+ * Opens the handshake with a `GET` of this path instead of the request
179
+ * itself, resolved as `path` is. Use it when the request's own URL can't
180
+ * take a body-less probe. If the probe isn't challenged, the request is
181
+ * sent without authentication.
182
+ */
183
+ probePath?: string;
184
+ /** Overrides the connection's `timeout` for this call. */
185
+ timeout?: number;
186
+ /** Cancels the call, which then fails with `ABORTED`. */
187
+ signal?: AbortSignal;
188
+ };
189
+ /** A server's answer to {@link NtlmConnection.request}. */
190
+ type NtlmResponse<T> = {
191
+ /** HTTP status, always 2xx: other statuses are a {@link Failure}. */
192
+ status: number;
193
+ /** Response headers, names lower-cased. */
194
+ headers: IncomingHttpHeaders;
195
+ /** The body, as `responseType` asked for. */
196
+ body: T;
197
+ };
198
+ /**
199
+ * The `request` action. Its result's `body` type follows `responseType`:
200
+ * `string` for `'text'` (the default), `Uint8Array` for `'buffer'` (a
201
+ * `Buffer` at runtime), and `Readable` for `'stream'`.
202
+ */
203
+ type RequestAction = {
204
+ (options: RequestOptions & {
205
+ responseType?: 'text';
206
+ }): Promise<Result<NtlmResponse<string>>>;
207
+ (options: RequestOptions & {
208
+ responseType: 'buffer';
209
+ }): Promise<Result<NtlmResponse<Uint8Array>>>;
210
+ (options: RequestOptions & {
211
+ responseType: 'stream';
212
+ }): Promise<Result<NtlmResponse<Readable>>>;
213
+ /** When `responseType` is only known as the union. */
214
+ (options: RequestOptions): Promise<Result<NtlmResponse<string | Uint8Array | Readable>>>;
215
+ };
216
+ /** The `testConnection` action. */
217
+ type TestConnectionAction = (options?: TestConnectionOptions) => Promise<Result<void>>;
218
+ /**
219
+ * State shared between actions on one connection. Each call does its own
220
+ * handshake, so today it holds nothing. Pass one context to several
221
+ * standalone factories so they share whatever later releases keep here.
222
+ */
223
+ interface ConnectionContext {}
224
+ /**
225
+ * Creates an action bound to one connection. Call it once with your
226
+ * {@link NtlmConnectionOptions}, then call the action as often as needed.
227
+ *
228
+ * @param options The connection's URL and account. Validated at once.
229
+ * @param context State to share with other actions; one is created if omitted.
230
+ * @returns The action.
231
+ * @throws {TypeError} When `options` are malformed.
232
+ */
233
+ type ActionFactory<TAction> = (options: NtlmConnectionOptions, context?: ConnectionContext) => TAction;
234
+ /** Every action, bound to one NTLM host. Create it with `createNtlmConnection`. */
235
+ type NtlmConnection = {
236
+ /**
237
+ * Sends one NTLM-authenticated request to a path on the connection's
238
+ * origin, running the whole handshake on one socket.
239
+ *
240
+ * - **Where:** `path` resolves against `url` by URL rules. A result on any
241
+ * other origin, or with user info, is refused before anything is sent.
242
+ * - **The handshake:** the first leg sends the request's method and URL
243
+ * without a body, or a `GET` of `probePath` when one is given. The body
244
+ * goes only with the authenticated leg.
245
+ * - **When the server doesn't ask for NTLM:** a request without a body
246
+ * takes that first response as its answer. A request with a body fails
247
+ * with `PROTOCOL` and its body is never sent. After an unchallenged
248
+ * `probePath`, the request is sent without authentication.
249
+ * - **The body:** `responseType` picks text (the default), bytes or a
250
+ * `Readable`. A streamed body holds the socket until the stream closes, so
251
+ * read it to the end or destroy it. The connection's `timeout` and the
252
+ * call's `signal` still apply while it is read: a stall longer than
253
+ * `timeout`, or an abort, destroys the stream with an error, so attach an
254
+ * `'error'` listener (`pipeline` does). When the server answered without
255
+ * asking for NTLM, the body was already read in full and the stream
256
+ * replays it from memory.
257
+ * - **Retry:** with the connection's `retry` set, `GET` and `HEAD` are
258
+ * retried on transient failures. Other methods, and a call with a
259
+ * `Readable` body, are sent once.
260
+ *
261
+ * @param options The request: `path` (required), `method`, `headers`,
262
+ * `body`, `responseType`, `probePath`, `timeout` and `signal`.
263
+ * @returns `data` is an {@link NtlmResponse} whose `body` follows
264
+ * `responseType`. A non-2xx answer is a failure: `AUTH` for 401 and 403,
265
+ * `HTTP` otherwise, with the body as text in `details`. `PROTOCOL` means
266
+ * the server can't do NTLMv2; `INVALID_REQUEST` means the call was refused
267
+ * before anything was sent.
268
+ * @example
269
+ * const res = await connection.request({ path: '_api/web/lists', headers: { Accept: 'application/json' } })
270
+ * if (res.success) console.log(JSON.parse(res.data.body))
271
+ * @example
272
+ * const file = await connection.request({ path: 'Shared Documents/report.pdf', responseType: 'stream' })
273
+ * if (file.success) await pipeline(file.data.body, createWriteStream('report.pdf'))
274
+ */
275
+ request: RequestAction;
276
+ /**
277
+ * Proves the credentials work: one authenticated `GET` of the
278
+ * connection's `url`, completing the NTLM handshake.
279
+ *
280
+ * A server that doesn't ask for NTLM and answers 2xx also succeeds, since
281
+ * nothing was refused.
282
+ *
283
+ * @param options An optional per-call `timeout` and `signal`.
284
+ * @returns `data` is `undefined`. A wrong password is an `AUTH` failure; a
285
+ * server that can't do NTLMv2 is a `PROTOCOL` failure.
286
+ */
287
+ testConnection: TestConnectionAction;
288
+ };
289
+ /**
290
+ * Raised when a server can't complete an NTLMv2 handshake: it offered no
291
+ * NTLM, sent a malformed challenge, or offered only NTLMv1. Actions convert it
292
+ * into a `PROTOCOL` {@link Failure}. It is exported so its shape can be
293
+ * reused, not because callers of the connection need to catch it.
294
+ */
295
+ declare class NtlmError extends Error {
296
+ readonly name = "NtlmError";
297
+ /** HTTP status of the response that carried the problem, when there was one. */
298
+ readonly status: number | undefined;
299
+ /**
300
+ * @param message What the server did wrong.
301
+ * @param options `status` of the response, and the underlying `cause`.
302
+ */
303
+ constructor(message: string, options?: {
304
+ status?: number;
305
+ cause?: unknown;
306
+ });
307
+ }
308
+ export { FailureCode as a, NtlmCredentials as c, RequestOptions as d, Result as f, TestConnectionOptions as g, TestConnectionAction as h, Failure as i, NtlmResponse as l, Success as m, ActionFactory as n, NtlmConnection as o, RetryOptions as p, ConnectionContext as r, NtlmConnectionOptions as s, NtlmError as t, RequestAction as u };
@@ -0,0 +1,82 @@
1
+ import { a as FailureCode, c as NtlmCredentials, d as RequestOptions, f as Result, g as TestConnectionOptions, h as TestConnectionAction, i as Failure, l as NtlmResponse, m as Success, n as ActionFactory, o as NtlmConnection, p as RetryOptions, r as ConnectionContext, s as NtlmConnectionOptions, t as NtlmError, u as RequestAction } from "./errors-Bc9WxpK5.js";
2
+ /**
3
+ * Checks the shape of connection options and throws a `TypeError` naming the
4
+ * first bad option and the value it got (never the password's). Catches a
5
+ * misconfiguration at startup rather than as an opaque failure on the first
6
+ * call.
7
+ *
8
+ * @param options The options to check.
9
+ * @throws {TypeError} When an option is missing or malformed.
10
+ */
11
+ export declare function validateNtlmOptions(options: NtlmConnectionOptions): void;
12
+ /**
13
+ * Binds every action to one NTLM host.
14
+ *
15
+ * Credentials are captured in closures and used on each call, and only ever
16
+ * sent to the origin of `url`. Creating a connection performs no network
17
+ * I/O; it does validate the shape of `options`, and throws a `TypeError` for
18
+ * a misconfiguration.
19
+ *
20
+ * @param options The host's URL and the account to authenticate as.
21
+ * @returns An {@link NtlmConnection} whose methods each resolve to a
22
+ * {@link Result} and never throw.
23
+ * @throws {TypeError} When `options` are malformed.
24
+ * @example
25
+ * import { createNtlmConnection } from '@b-jones-rfd/ntlm-handshake'
26
+ *
27
+ * const connection = createNtlmConnection({
28
+ * url: 'https://intranet.contoso.local/',
29
+ * username: 'CONTOSO\\jsmith',
30
+ * password: process.env.NTLM_PASSWORD!,
31
+ * })
32
+ *
33
+ * const res = await connection.testConnection()
34
+ * if (!res.success) console.error(res.code, res.error)
35
+ *
36
+ * const page = await connection.request({ path: 'default.aspx' })
37
+ * if (page.success) console.log(page.data.status, page.data.body.length)
38
+ */
39
+ export declare function createNtlmConnection(options: NtlmConnectionOptions): NtlmConnection;
40
+ /**
41
+ * Sends one NTLM-authenticated request to a path on the connection's origin.
42
+ *
43
+ * Factory form of {@link NtlmConnection.request}: call it with your
44
+ * {@link NtlmConnectionOptions} to get a reusable action. See that member for
45
+ * the full parameter and return documentation.
46
+ *
47
+ * @see https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/033d32cc-88f9-4483-9bf2-b273055038ce
48
+ * @throws {TypeError} When `options` are malformed (see `validateNtlmOptions`).
49
+ */
50
+ export declare const request: ActionFactory<RequestAction>;
51
+ /**
52
+ * Proves the credentials work with one authenticated `GET` of the
53
+ * connection's `url`.
54
+ *
55
+ * Factory form of {@link NtlmConnection.testConnection}: call it with your
56
+ * {@link NtlmConnectionOptions} to get a reusable action. See that member for
57
+ * the full parameter and return documentation.
58
+ *
59
+ * @see https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/033d32cc-88f9-4483-9bf2-b273055038ce
60
+ * @throws {TypeError} When `options` are malformed (see `validateNtlmOptions`).
61
+ */
62
+ export declare const testConnection: ActionFactory<TestConnectionAction>;
63
+ /**
64
+ * Creates the state shared between actions on one connection.
65
+ * `createNtlmConnection` calls this for you. Each call does its own
66
+ * handshake, so the context holds nothing yet; it exists so standalone
67
+ * factories can share one, and later releases can keep state in it without
68
+ * changing their signatures.
69
+ *
70
+ * @param _options The connection's options.
71
+ * @returns A {@link ConnectionContext} to pass to standalone factories.
72
+ */
73
+ export declare function createConnectionContext(_options: NtlmConnectionOptions): ConnectionContext;
74
+ /**
75
+ * The default {@link RetryOptions.retryOn}: `NETWORK`, `TIMEOUT`, and `HTTP`
76
+ * with status 429, 502, 503 or 504.
77
+ *
78
+ * @param failure A failed result.
79
+ * @returns `true` when the failure is likely to pass on a later attempt.
80
+ */
81
+ export declare function isTransientFailure(failure: Failure): boolean;
82
+ export { ActionFactory, ConnectionContext, Failure, FailureCode, NtlmConnection, NtlmConnectionOptions, NtlmCredentials, NtlmError, NtlmResponse, RequestAction, RequestOptions, Result, RetryOptions, Success, TestConnectionAction, TestConnectionOptions };