@heroku/heroku-fetch 0.1.6 → 0.2.1
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 +19 -21
- package/dist/browser.d.ts +2 -3
- package/dist/browser.js +1 -2
- package/dist/client/browser-environment-defaults.d.ts +13 -1
- package/dist/client/browser-environment-defaults.js +14 -0
- package/dist/client/http-error-handler.js +2 -1
- package/dist/client/http-request-hooks.d.ts +68 -7
- package/dist/client/http-request-hooks.js +147 -44
- package/dist/client/index.d.ts +10 -3
- package/dist/client/index.js +72 -26
- package/dist/client/node-environment-defaults.d.ts +40 -6
- package/dist/client/node-environment-defaults.js +89 -14
- package/dist/client/request-id.d.ts +40 -0
- package/dist/client/request-id.js +78 -0
- package/dist/client/two-factor-authentication-handler.d.ts +18 -4
- package/dist/client/two-factor-authentication-handler.js +22 -18
- package/dist/debug-loggers.d.ts +0 -1
- package/dist/debug-loggers.js +0 -1
- package/dist/host.d.ts +33 -0
- package/dist/host.js +38 -0
- package/dist/index.d.ts +2 -3
- package/dist/index.js +1 -2
- package/dist/public-types.d.ts +7 -0
- package/dist/public-types.js +7 -0
- package/dist/redact.d.ts +26 -0
- package/dist/redact.js +158 -0
- package/dist/types.d.ts +105 -1
- package/package.json +4 -5
- package/dist/auth/auth.d.ts +0 -66
- package/dist/auth/auth.js +0 -93
- package/dist/cli/cli-login.d.ts +0 -7
- package/dist/cli/cli-login.js +0 -7
- package/dist/cli/login/browser-login.d.ts +0 -8
- package/dist/cli/login/browser-login.js +0 -115
- package/dist/cli/login/index.d.ts +0 -34
- package/dist/cli/login/index.js +0 -193
- package/dist/cli/login/interactive-login.d.ts +0 -8
- package/dist/cli/login/interactive-login.js +0 -59
- package/dist/cli/login/netrc-utils.d.ts +0 -22
- package/dist/cli/login/netrc-utils.js +0 -85
- package/dist/cli/login/oauth.d.ts +0 -20
- package/dist/cli/login/oauth.js +0 -142
- package/dist/cli/login/sso-login.d.ts +0 -8
- package/dist/cli/login/sso-login.js +0 -41
- package/dist/cli/login/types.d.ts +0 -42
- package/dist/cli/login/types.js +0 -11
package/dist/client/index.js
CHANGED
|
@@ -5,15 +5,20 @@
|
|
|
5
5
|
* Supports multiple services (platform, data, particleboard), authentication,
|
|
6
6
|
* two-factor authentication, and comprehensive error handling.
|
|
7
7
|
*/
|
|
8
|
-
import {
|
|
8
|
+
import { getDefaultFetch, getDefaultTokenProvider, getDefaultTwoFactorOptions } from '@heroku/heroku-fetch/client/environment-defaults.js';
|
|
9
9
|
import ky from 'ky';
|
|
10
10
|
import { debugAuth, debugRequest } from '../debug-loggers.js';
|
|
11
|
-
import {
|
|
11
|
+
import { create2FAAfterHook, createBeforeRequestHook, createErrorAfterHook, createMetadataAfterHook, createRequestIdAfterHook, createRequestIdBeforeHook, createWarningAfterHook, } from './http-request-hooks.js';
|
|
12
|
+
import { RequestIdStore } from './request-id.js';
|
|
12
13
|
import { SERVICE_CONFIGS } from './service-configurations.js';
|
|
13
14
|
export class HerokuApiClient {
|
|
14
15
|
constructor(options = {}) {
|
|
15
16
|
this.clientPromise = null;
|
|
16
|
-
|
|
17
|
+
// Per-client cross-cutting request state: the Request-Id accumulation and the
|
|
18
|
+
// set of warnings already surfaced, so dedupe spans a multi-request session
|
|
19
|
+
// but resets per client and parallel clients stay isolated.
|
|
20
|
+
this.requestIds = new RequestIdStore();
|
|
21
|
+
this.shownWarnings = new Set();
|
|
17
22
|
this.options = {
|
|
18
23
|
service: options.service || 'platform',
|
|
19
24
|
timeout: options.timeout || 30000,
|
|
@@ -37,18 +42,44 @@ export class HerokuApiClient {
|
|
|
37
42
|
}
|
|
38
43
|
debugAuth('Initializing client for service: %s, baseUrl: %s', this.options.service, baseUrl);
|
|
39
44
|
// Stash the ky options; the actual ky instance is built lazily so
|
|
40
|
-
// we can await
|
|
41
|
-
//
|
|
45
|
+
// we can await getDefaultFetch() (Node loads undici dynamically for
|
|
46
|
+
// env-var proxy support).
|
|
47
|
+
// Static headers go on the instance so ky merges them with per-call headers
|
|
48
|
+
// (per-call winning). A per-client `defaultAccept` override wins over the
|
|
49
|
+
// shared service default; services that declare no default (e.g. `custom`)
|
|
50
|
+
// and no override contribute no Accept at all.
|
|
51
|
+
const defaultAccept = options.defaultAccept ?? serviceConfig.defaultAccept;
|
|
52
|
+
const headers = { ...options.headers };
|
|
53
|
+
// Case-insensitive check: a consumer may have supplied Accept under any
|
|
54
|
+
// casing, and ky merges headers case-insensitively (last write wins), so a
|
|
55
|
+
// plain `'Accept' in headers` test would miss a lowercase `accept` and let
|
|
56
|
+
// our default clobber the consumer's choice.
|
|
57
|
+
if (defaultAccept && !new Headers(options.headers).has('accept')) {
|
|
58
|
+
headers.Accept = defaultAccept;
|
|
59
|
+
}
|
|
42
60
|
this.kyOptions = {
|
|
61
|
+
headers,
|
|
43
62
|
hooks: {
|
|
63
|
+
// Order matters: the 2FA hook runs first (so it sees a challenge before
|
|
64
|
+
// it's thrown as an error and can force a retry), then the error hook
|
|
65
|
+
// throws on a non-ok response — so the Request-Id tracking, warning, and
|
|
66
|
+
// metadata hooks after it run only on the success path.
|
|
44
67
|
afterResponse: [
|
|
45
|
-
|
|
68
|
+
create2FAAfterHook(this.options.twoFactor),
|
|
69
|
+
createErrorAfterHook(),
|
|
70
|
+
createRequestIdAfterHook(this.requestIds),
|
|
71
|
+
createWarningAfterHook(this.shownWarnings, message => this.options.warn?.(message)),
|
|
72
|
+
createMetadataAfterHook(metadata => this.options.onResponseMetadata?.(metadata)),
|
|
73
|
+
// Consumer hooks run last: they see the resolved success-path
|
|
74
|
+
// response (the error-handling built-in above throws on non-2xx).
|
|
75
|
+
...(options.hooks?.afterResponse ?? []),
|
|
46
76
|
],
|
|
47
77
|
beforeRequest: [
|
|
48
|
-
createBeforeRequestHook(() => this.getToken(),
|
|
49
|
-
|
|
50
|
-
//
|
|
51
|
-
|
|
78
|
+
createBeforeRequestHook(() => this.getToken(), this.options.debug),
|
|
79
|
+
createRequestIdBeforeHook(this.requestIds),
|
|
80
|
+
// Consumer hooks run last: they see (and may override) the fully
|
|
81
|
+
// prepared request after auth and Request-Id are attached.
|
|
82
|
+
...(options.hooks?.beforeRequest ?? []),
|
|
52
83
|
],
|
|
53
84
|
},
|
|
54
85
|
prefix: baseUrl,
|
|
@@ -96,11 +127,19 @@ export class HerokuApiClient {
|
|
|
96
127
|
setOption(key, value) {
|
|
97
128
|
if (key === 'token') {
|
|
98
129
|
this.tokenProvider = value;
|
|
130
|
+
return;
|
|
99
131
|
}
|
|
100
|
-
|
|
132
|
+
// Only these are re-read on each request, so changing them takes effect.
|
|
133
|
+
// Everything else — hooks, headers, the Accept default, the 2FA handler,
|
|
134
|
+
// and the base URL derived from service/region — is baked into the cached
|
|
135
|
+
// ky instance at construction; mutating it here would silently no-op, so
|
|
136
|
+
// reject it rather than lie about the change landing.
|
|
137
|
+
if (key === 'timeout' || key === 'warn' || key === 'onResponseMetadata') {
|
|
101
138
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
102
139
|
this.options[key] = value;
|
|
140
|
+
return;
|
|
103
141
|
}
|
|
142
|
+
throw new Error(`setOption: "${key}" is fixed at construction and cannot be changed on an existing client; pass it to the constructor instead.`);
|
|
104
143
|
}
|
|
105
144
|
/**
|
|
106
145
|
* Create a streaming request (returns the Response object for stream access)
|
|
@@ -108,29 +147,33 @@ export class HerokuApiClient {
|
|
|
108
147
|
async stream(path, options) {
|
|
109
148
|
debugRequest('STREAM %s', path);
|
|
110
149
|
const kyOptions = {
|
|
111
|
-
|
|
150
|
+
// Only set these when the caller supplied them: a literal `undefined`
|
|
151
|
+
// overrides (and for headers, clears) what ky merges from the instance,
|
|
152
|
+
// rather than leaving the instance value untouched.
|
|
153
|
+
...(options?.headers && { headers: options.headers }),
|
|
154
|
+
...(options?.searchParams && { searchParams: options.searchParams }),
|
|
155
|
+
...(options?.signal && { signal: options.signal }),
|
|
112
156
|
method: 'GET',
|
|
113
|
-
searchParams: options?.searchParams,
|
|
114
|
-
signal: options?.signal,
|
|
115
157
|
timeout: options?.timeout || this.options.timeout,
|
|
116
158
|
};
|
|
117
159
|
const client = await this.getClient();
|
|
118
160
|
return client(path, kyOptions);
|
|
119
161
|
}
|
|
120
162
|
/**
|
|
121
|
-
* Lazily construct ky
|
|
122
|
-
*
|
|
163
|
+
* Lazily construct ky over a fetch that is proxy-aware on Node (undici's own
|
|
164
|
+
* fetch paired with an env-var dispatcher) and the global fetch in the
|
|
165
|
+
* browser. Cached after the first call.
|
|
166
|
+
*
|
|
167
|
+
* We drive ky through `fetch` rather than ky's `dispatcher` option because
|
|
168
|
+
* ky calls the global `fetch`, which on Node 22 is backed by a different
|
|
169
|
+
* undici than our dispatcher and rejects it (`invalid onRequestStart
|
|
170
|
+
* method`). `getDefaultFetch()` returns a fetch from the matching undici.
|
|
123
171
|
*/
|
|
124
172
|
async getClient() {
|
|
125
173
|
if (!this.clientPromise) {
|
|
126
174
|
this.clientPromise = (async () => {
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
// passed through to fetch as undici expects it.
|
|
130
|
-
const opts = dispatcher
|
|
131
|
-
? { ...this.kyOptions, dispatcher }
|
|
132
|
-
: this.kyOptions;
|
|
133
|
-
return ky.create(opts);
|
|
175
|
+
const fetch = await getDefaultFetch();
|
|
176
|
+
return ky.create({ ...this.kyOptions, fetch });
|
|
134
177
|
})();
|
|
135
178
|
}
|
|
136
179
|
return this.clientPromise;
|
|
@@ -152,10 +195,13 @@ export class HerokuApiClient {
|
|
|
152
195
|
*/
|
|
153
196
|
async request(path, options) {
|
|
154
197
|
const kyOptions = {
|
|
155
|
-
|
|
198
|
+
// Only set these when the caller supplied them: a literal `undefined`
|
|
199
|
+
// overrides (and for headers, clears) what ky merges from the instance,
|
|
200
|
+
// rather than leaving the instance value untouched.
|
|
201
|
+
...(options?.headers && { headers: options.headers }),
|
|
202
|
+
...(options?.searchParams && { searchParams: options.searchParams }),
|
|
203
|
+
...(options?.signal && { signal: options.signal }),
|
|
156
204
|
method: options?.method || 'GET',
|
|
157
|
-
searchParams: options?.searchParams,
|
|
158
|
-
signal: options?.signal,
|
|
159
205
|
timeout: options?.timeout || this.options.timeout,
|
|
160
206
|
};
|
|
161
207
|
if (options?.body !== undefined) {
|
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Default providers for Node.js environments
|
|
3
|
-
* These use file system (netrc) and CLI utilities
|
|
4
3
|
*/
|
|
5
|
-
import type { TokenProvider, TwoFactorOptions } from '../types.js';
|
|
4
|
+
import type { FetchLike, TokenProvider, TwoFactorOptions } from '../types.js';
|
|
6
5
|
/**
|
|
7
|
-
* Get default token provider for Node.js (
|
|
6
|
+
* Get default token provider for Node.js (reads the HEROKU_API_KEY env var)
|
|
7
|
+
*
|
|
8
|
+
* heroku-fetch does not read stored credentials. To authenticate with
|
|
9
|
+
* credentials saved by the Heroku CLI, resolve a token with the
|
|
10
|
+
* heroku-credential-manager package and pass it to the client explicitly.
|
|
11
|
+
*
|
|
12
|
+
* When HEROKU_API_KEY is unset this returns `undefined`, so the request is sent
|
|
13
|
+
* with no `Authorization` header rather than failing eagerly — endpoints that
|
|
14
|
+
* need no auth still work, and endpoints that do get a server 401 surfaced as
|
|
15
|
+
* `AuthenticationError`.
|
|
8
16
|
*/
|
|
9
17
|
export declare function getDefaultTokenProvider(): TokenProvider;
|
|
10
18
|
/**
|
|
@@ -12,7 +20,29 @@ export declare function getDefaultTokenProvider(): TokenProvider;
|
|
|
12
20
|
*/
|
|
13
21
|
export declare function getDefaultTwoFactorOptions(): TwoFactorOptions;
|
|
14
22
|
/**
|
|
15
|
-
* Get
|
|
23
|
+
* Get a `fetch` that is already paired with the proxy dispatcher from
|
|
24
|
+
* `getDefaultDispatcher()`, drawn from the **same undici copy**.
|
|
25
|
+
*
|
|
26
|
+
* This exists because of a cross-undici-version trap: `getDefaultDispatcher()`
|
|
27
|
+
* builds its `EnvHttpProxyAgent` from the npm `undici` this package depends on
|
|
28
|
+
* (v8), but Node's built-in global `fetch` is backed by a *different* bundled
|
|
29
|
+
* undici (v6 on Node 22) whose dispatcher handler interface is incompatible.
|
|
30
|
+
* Handing an npm-undici dispatcher to global `fetch` fails
|
|
31
|
+
* (`InvalidArgumentError: invalid onRequestStart method`). So the dispatcher
|
|
32
|
+
* must be driven by undici's *own* `fetch`, and because the brand check on
|
|
33
|
+
* `Request` is per-copy, a `Request` built by the global constructor isn't
|
|
34
|
+
* recognized by undici's `fetch` and has to be decomposed into `(url, init)`.
|
|
35
|
+
*
|
|
36
|
+
* This function hides all of that: callers get a plain `FetchLike`.
|
|
37
|
+
* - No proxy env var set → the global `fetch` (no dispatcher needed; it is the
|
|
38
|
+
* one case that already works).
|
|
39
|
+
* - Proxy set → undici's `fetch` carrying the dispatcher, decomposing any
|
|
40
|
+
* `Request` input first.
|
|
41
|
+
* - undici not loadable (e.g. Bun) → the global `fetch`, unproxied.
|
|
42
|
+
*/
|
|
43
|
+
export declare function getDefaultFetch(): Promise<FetchLike>;
|
|
44
|
+
/**
|
|
45
|
+
* Get an undici Dispatcher that routes requests through an
|
|
16
46
|
* `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`-aware proxy agent.
|
|
17
47
|
*
|
|
18
48
|
* Returns `undefined` when no proxy env var is set, so we don't
|
|
@@ -25,7 +55,11 @@ export declare function getDefaultTwoFactorOptions(): TwoFactorOptions;
|
|
|
25
55
|
* ship undici); callers should skip the option in that case so ky
|
|
26
56
|
* falls back to native fetch.
|
|
27
57
|
*
|
|
28
|
-
*
|
|
29
|
-
* fetch —
|
|
58
|
+
* WARNING: the returned dispatcher comes from the npm `undici` this package
|
|
59
|
+
* depends on and must be driven by that same undici's `fetch` — NOT Node's
|
|
60
|
+
* built-in global `fetch`, which bundles a different, incompatible undici and
|
|
61
|
+
* throws `invalid onRequestStart method`. Most callers should use
|
|
62
|
+
* `getDefaultFetch()` instead, which pairs the two correctly and returns a
|
|
63
|
+
* ready-to-use `fetch`.
|
|
30
64
|
*/
|
|
31
65
|
export declare function getDefaultDispatcher(): Promise<undefined | unknown>;
|
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Default providers for Node.js environments
|
|
3
|
-
* These use file system (netrc) and CLI utilities
|
|
4
3
|
*/
|
|
5
4
|
import { debugRequest } from '../debug-loggers.js';
|
|
5
|
+
import { logScrubbed } from '../redact.js';
|
|
6
6
|
/**
|
|
7
|
-
* Get default token provider for Node.js (
|
|
7
|
+
* Get default token provider for Node.js (reads the HEROKU_API_KEY env var)
|
|
8
|
+
*
|
|
9
|
+
* heroku-fetch does not read stored credentials. To authenticate with
|
|
10
|
+
* credentials saved by the Heroku CLI, resolve a token with the
|
|
11
|
+
* heroku-credential-manager package and pass it to the client explicitly.
|
|
12
|
+
*
|
|
13
|
+
* When HEROKU_API_KEY is unset this returns `undefined`, so the request is sent
|
|
14
|
+
* with no `Authorization` header rather than failing eagerly — endpoints that
|
|
15
|
+
* need no auth still work, and endpoints that do get a server 401 surfaced as
|
|
16
|
+
* `AuthenticationError`.
|
|
8
17
|
*/
|
|
9
18
|
export function getDefaultTokenProvider() {
|
|
10
|
-
return
|
|
11
|
-
const { getAuthToken } = await import('../auth/auth.js');
|
|
12
|
-
const token = getAuthToken();
|
|
13
|
-
if (!token) {
|
|
14
|
-
throw new Error('No authentication token found. Please set HEROKU_API_KEY or run: heroku login');
|
|
15
|
-
}
|
|
16
|
-
return token;
|
|
17
|
-
};
|
|
19
|
+
return () => process.env.HEROKU_API_KEY;
|
|
18
20
|
}
|
|
19
21
|
/**
|
|
20
22
|
* Get default 2FA handler for Node.js (uses CLI prompts)
|
|
@@ -28,7 +30,42 @@ export function getDefaultTwoFactorOptions() {
|
|
|
28
30
|
};
|
|
29
31
|
}
|
|
30
32
|
/**
|
|
31
|
-
* Get
|
|
33
|
+
* Get a `fetch` that is already paired with the proxy dispatcher from
|
|
34
|
+
* `getDefaultDispatcher()`, drawn from the **same undici copy**.
|
|
35
|
+
*
|
|
36
|
+
* This exists because of a cross-undici-version trap: `getDefaultDispatcher()`
|
|
37
|
+
* builds its `EnvHttpProxyAgent` from the npm `undici` this package depends on
|
|
38
|
+
* (v8), but Node's built-in global `fetch` is backed by a *different* bundled
|
|
39
|
+
* undici (v6 on Node 22) whose dispatcher handler interface is incompatible.
|
|
40
|
+
* Handing an npm-undici dispatcher to global `fetch` fails
|
|
41
|
+
* (`InvalidArgumentError: invalid onRequestStart method`). So the dispatcher
|
|
42
|
+
* must be driven by undici's *own* `fetch`, and because the brand check on
|
|
43
|
+
* `Request` is per-copy, a `Request` built by the global constructor isn't
|
|
44
|
+
* recognized by undici's `fetch` and has to be decomposed into `(url, init)`.
|
|
45
|
+
*
|
|
46
|
+
* This function hides all of that: callers get a plain `FetchLike`.
|
|
47
|
+
* - No proxy env var set → the global `fetch` (no dispatcher needed; it is the
|
|
48
|
+
* one case that already works).
|
|
49
|
+
* - Proxy set → undici's `fetch` carrying the dispatcher, decomposing any
|
|
50
|
+
* `Request` input first.
|
|
51
|
+
* - undici not loadable (e.g. Bun) → the global `fetch`, unproxied.
|
|
52
|
+
*/
|
|
53
|
+
export async function getDefaultFetch() {
|
|
54
|
+
const dispatcher = await getDefaultDispatcher();
|
|
55
|
+
if (!dispatcher) {
|
|
56
|
+
return (input, init) => fetch(input, init);
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const { fetch: undiciFetch } = await import('undici');
|
|
60
|
+
return (input, init) => fetchThroughDispatcher(undiciFetch, dispatcher, input, init);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
await logScrubbed(debugRequest, 'undici fetch not available; using global fetch without proxy (%o)', error);
|
|
64
|
+
return (input, init) => fetch(input, init);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Get an undici Dispatcher that routes requests through an
|
|
32
69
|
* `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY`-aware proxy agent.
|
|
33
70
|
*
|
|
34
71
|
* Returns `undefined` when no proxy env var is set, so we don't
|
|
@@ -41,8 +78,12 @@ export function getDefaultTwoFactorOptions() {
|
|
|
41
78
|
* ship undici); callers should skip the option in that case so ky
|
|
42
79
|
* falls back to native fetch.
|
|
43
80
|
*
|
|
44
|
-
*
|
|
45
|
-
* fetch —
|
|
81
|
+
* WARNING: the returned dispatcher comes from the npm `undici` this package
|
|
82
|
+
* depends on and must be driven by that same undici's `fetch` — NOT Node's
|
|
83
|
+
* built-in global `fetch`, which bundles a different, incompatible undici and
|
|
84
|
+
* throws `invalid onRequestStart method`. Most callers should use
|
|
85
|
+
* `getDefaultFetch()` instead, which pairs the two correctly and returns a
|
|
86
|
+
* ready-to-use `fetch`.
|
|
46
87
|
*/
|
|
47
88
|
export async function getDefaultDispatcher() {
|
|
48
89
|
if (!hasProxyEnv()) {
|
|
@@ -56,7 +97,7 @@ export async function getDefaultDispatcher() {
|
|
|
56
97
|
return new EnvHttpProxyAgent();
|
|
57
98
|
}
|
|
58
99
|
catch (error) {
|
|
59
|
-
debugRequest
|
|
100
|
+
await logScrubbed(debugRequest, 'undici not available; skipping dispatcher (%o)', error);
|
|
60
101
|
return undefined;
|
|
61
102
|
}
|
|
62
103
|
}
|
|
@@ -66,3 +107,37 @@ function hasProxyEnv() {
|
|
|
66
107
|
|| process.env.HTTPS_PROXY
|
|
67
108
|
|| process.env.https_proxy);
|
|
68
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* Drive undici's `fetch` with a dispatcher from the same undici copy.
|
|
112
|
+
*
|
|
113
|
+
* A `string` / `URL` input is forwarded as-is. A `Request` input may have been
|
|
114
|
+
* built by the global constructor (a different undici copy), which undici's
|
|
115
|
+
* `fetch` won't recognize, so it is decomposed into `(url, init)`. The body is
|
|
116
|
+
* buffered — the Heroku API requests this transport sends carry small JSON
|
|
117
|
+
* payloads, not streamed uploads. An explicit `init` wins over the Request's
|
|
118
|
+
* own fields (matching `fetch` semantics); the dispatcher is always applied.
|
|
119
|
+
*/
|
|
120
|
+
async function fetchThroughDispatcher(undiciFetch, dispatcher, input, init) {
|
|
121
|
+
if (typeof input === 'string' || input instanceof URL) {
|
|
122
|
+
const withDispatcher = { ...init, dispatcher };
|
|
123
|
+
return undiciFetch(input, withDispatcher);
|
|
124
|
+
}
|
|
125
|
+
const headers = {};
|
|
126
|
+
// Headers isn't iterable under the project's ES2020+DOM lib (no DOM.Iterable),
|
|
127
|
+
// so forEach is the available copy idiom here.
|
|
128
|
+
// eslint-disable-next-line unicorn/no-array-for-each
|
|
129
|
+
input.headers.forEach((value, key) => {
|
|
130
|
+
headers[key] = value;
|
|
131
|
+
});
|
|
132
|
+
const hasBody = input.method !== 'GET' && input.method !== 'HEAD';
|
|
133
|
+
const withDispatcher = {
|
|
134
|
+
body: hasBody ? await input.arrayBuffer() : undefined,
|
|
135
|
+
headers,
|
|
136
|
+
method: input.method,
|
|
137
|
+
redirect: input.redirect,
|
|
138
|
+
signal: input.signal,
|
|
139
|
+
...init,
|
|
140
|
+
dispatcher,
|
|
141
|
+
};
|
|
142
|
+
return undiciFetch(input.url, withDispatcher);
|
|
143
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request-Id correlation store.
|
|
3
|
+
*
|
|
4
|
+
* Each client accumulates the `Request-Id`s it has generated and the ones the
|
|
5
|
+
* server echoes back, and sends the running list on every request so a chain of
|
|
6
|
+
* related calls can be correlated server-side. The store is per-client, so
|
|
7
|
+
* parallel clients don't cross-contaminate and the accumulation resets when a
|
|
8
|
+
* client is discarded.
|
|
9
|
+
*/
|
|
10
|
+
/** The header the Heroku API reads/echoes for request correlation. */
|
|
11
|
+
export declare const REQUEST_ID_HEADER = "Request-Id";
|
|
12
|
+
export declare class RequestIdStore {
|
|
13
|
+
private readonly generate;
|
|
14
|
+
private ids;
|
|
15
|
+
private readonly idSet;
|
|
16
|
+
/**
|
|
17
|
+
* @param generate UUID generator; defaults to the platform's
|
|
18
|
+
* `crypto.randomUUID` (present on Node 18+ and in browsers). Injectable for
|
|
19
|
+
* deterministic tests. Wrapped in an arrow rather than passed as a bare
|
|
20
|
+
* `globalThis.crypto.randomUUID` because it's a method that brand-checks its
|
|
21
|
+
* receiver — called unbound it throws `this` must be of type `Crypto`.
|
|
22
|
+
*/
|
|
23
|
+
constructor(generate?: () => string);
|
|
24
|
+
/** Current accumulated ids joined for the header (comma, no space). */
|
|
25
|
+
get headerValue(): string;
|
|
26
|
+
/** Generate a new id, prepend it to the accumulated list, return the list. */
|
|
27
|
+
create(): string[];
|
|
28
|
+
/**
|
|
29
|
+
* The header value to send on the next request: generate+accumulate a fresh
|
|
30
|
+
* id, then apply the overflow guard. On overflow the OLDEST ids are dropped
|
|
31
|
+
* (the chain is prepend-ordered, so the tail is oldest) until the header fits
|
|
32
|
+
* — keeping the newest end so correlation with the immediately preceding
|
|
33
|
+
* requests survives instead of being severed by a full reset. A lone id that
|
|
34
|
+
* already exceeds the cap is kept as-is. Always returns the comma-joined
|
|
35
|
+
* string.
|
|
36
|
+
*/
|
|
37
|
+
nextHeaderValue(): string;
|
|
38
|
+
/** Prepend server-returned ids not already tracked (dedupe), return the list. */
|
|
39
|
+
track(...ids: string[]): string[];
|
|
40
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request-Id correlation store.
|
|
3
|
+
*
|
|
4
|
+
* Each client accumulates the `Request-Id`s it has generated and the ones the
|
|
5
|
+
* server echoes back, and sends the running list on every request so a chain of
|
|
6
|
+
* related calls can be correlated server-side. The store is per-client, so
|
|
7
|
+
* parallel clients don't cross-contaminate and the accumulation resets when a
|
|
8
|
+
* client is discarded.
|
|
9
|
+
*/
|
|
10
|
+
/** The header the Heroku API reads/echoes for request correlation. */
|
|
11
|
+
export const REQUEST_ID_HEADER = 'Request-Id';
|
|
12
|
+
/**
|
|
13
|
+
* Cap the accumulated header at 7KB. Long-running polls (e.g. `pg:wait`) have
|
|
14
|
+
* been observed to push the accumulated `Request-Id` header past 8KB — Node's
|
|
15
|
+
* default max header size — which fails the request. 7KB leaves room for the
|
|
16
|
+
* other headers. Measured in bytes (not characters) via TextEncoder so it
|
|
17
|
+
* matches what goes on the wire without depending on Node's Buffer.
|
|
18
|
+
*/
|
|
19
|
+
const MAX_REQUEST_ID_BYTES = 1024 * 7;
|
|
20
|
+
function byteLength(value) {
|
|
21
|
+
return new TextEncoder().encode(value).length;
|
|
22
|
+
}
|
|
23
|
+
export class RequestIdStore {
|
|
24
|
+
/**
|
|
25
|
+
* @param generate UUID generator; defaults to the platform's
|
|
26
|
+
* `crypto.randomUUID` (present on Node 18+ and in browsers). Injectable for
|
|
27
|
+
* deterministic tests. Wrapped in an arrow rather than passed as a bare
|
|
28
|
+
* `globalThis.crypto.randomUUID` because it's a method that brand-checks its
|
|
29
|
+
* receiver — called unbound it throws `this` must be of type `Crypto`.
|
|
30
|
+
*/
|
|
31
|
+
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- global `crypto` is available on Node 22 (and in browsers); the lint engine's compatibility table conservatively marks it 23+. Using node:crypto would break the Node-agnostic core.
|
|
32
|
+
constructor(generate = () => globalThis.crypto.randomUUID()) {
|
|
33
|
+
this.generate = generate;
|
|
34
|
+
this.ids = [];
|
|
35
|
+
// Mirrors `ids` for O(1) membership in track(), so dedupe stays linear in the
|
|
36
|
+
// ids being added rather than scanning the whole accumulated chain per id.
|
|
37
|
+
this.idSet = new Set();
|
|
38
|
+
}
|
|
39
|
+
/** Current accumulated ids joined for the header (comma, no space). */
|
|
40
|
+
get headerValue() {
|
|
41
|
+
return this.ids.join(',');
|
|
42
|
+
}
|
|
43
|
+
/** Generate a new id, prepend it to the accumulated list, return the list. */
|
|
44
|
+
create() {
|
|
45
|
+
const id = this.generate();
|
|
46
|
+
this.ids = [id, ...this.ids];
|
|
47
|
+
this.idSet.add(id);
|
|
48
|
+
return this.ids;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The header value to send on the next request: generate+accumulate a fresh
|
|
52
|
+
* id, then apply the overflow guard. On overflow the OLDEST ids are dropped
|
|
53
|
+
* (the chain is prepend-ordered, so the tail is oldest) until the header fits
|
|
54
|
+
* — keeping the newest end so correlation with the immediately preceding
|
|
55
|
+
* requests survives instead of being severed by a full reset. A lone id that
|
|
56
|
+
* already exceeds the cap is kept as-is. Always returns the comma-joined
|
|
57
|
+
* string.
|
|
58
|
+
*/
|
|
59
|
+
nextHeaderValue() {
|
|
60
|
+
this.create();
|
|
61
|
+
while (this.ids.length > 1 && byteLength(this.headerValue) > MAX_REQUEST_ID_BYTES) {
|
|
62
|
+
const dropped = this.ids.pop();
|
|
63
|
+
if (dropped !== undefined) {
|
|
64
|
+
this.idSet.delete(dropped);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return this.headerValue;
|
|
68
|
+
}
|
|
69
|
+
/** Prepend server-returned ids not already tracked (dedupe), return the list. */
|
|
70
|
+
track(...ids) {
|
|
71
|
+
const novel = ids.filter(id => !this.idSet.has(id));
|
|
72
|
+
for (const id of novel) {
|
|
73
|
+
this.idSet.add(id);
|
|
74
|
+
}
|
|
75
|
+
this.ids = [...novel, ...this.ids];
|
|
76
|
+
return this.ids;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -3,14 +3,28 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Handles detection and processing of 2FA challenges from the API.
|
|
5
5
|
*/
|
|
6
|
+
import ky from 'ky';
|
|
6
7
|
import type { TwoFactorOptions } from '../types.js';
|
|
7
8
|
/**
|
|
8
9
|
* Check if a 403 response is a 2FA error by checking the error id
|
|
9
10
|
*/
|
|
10
11
|
export declare function is2FAError(response: Response): Promise<boolean>;
|
|
11
12
|
/**
|
|
12
|
-
* Handle a 2FA challenge by prompting for a code and
|
|
13
|
+
* Handle a 2FA challenge by prompting for a code and forcing a retry of the
|
|
14
|
+
* request with the `Heroku-Two-Factor-Code` header attached.
|
|
15
|
+
*
|
|
16
|
+
* Returns ky's forced-retry marker (`ky.retry`) so ky re-issues the request
|
|
17
|
+
* through this same client — reusing its fetch, auth, and the original
|
|
18
|
+
* request's per-call timeout and abort signal — and runs the retried response
|
|
19
|
+
* back through the full afterResponse chain (error handling, Request-Id,
|
|
20
|
+
* warnings, metadata, and consumer hooks) exactly once. The forced retry counts
|
|
21
|
+
* against `retry.limit` and is observable in `beforeRetry` as a
|
|
22
|
+
* `ForceRetryError`.
|
|
23
|
+
*
|
|
24
|
+
* Because it draws on the same retry budget as ky's transport retries, a
|
|
25
|
+
* request that already exhausted `retry.limit` on network/timeout retries would
|
|
26
|
+
* surface the raw `ForceRetryError` rather than re-issuing. In practice a 2FA
|
|
27
|
+
* challenge arrives on the first attempt (before any transport retry), so the
|
|
28
|
+
* budget is intact; this edge only matters if that assumption ever breaks.
|
|
13
29
|
*/
|
|
14
|
-
export declare function handle2FAChallenge(request: Request, twoFactorOptions: TwoFactorOptions
|
|
15
|
-
value: boolean;
|
|
16
|
-
}): Promise<Response>;
|
|
30
|
+
export declare function handle2FAChallenge(request: Request, twoFactorOptions: TwoFactorOptions): Promise<ReturnType<typeof ky.retry>>;
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import ky from 'ky';
|
|
7
7
|
import { debugAuth, debugError } from '../debug-loggers.js';
|
|
8
|
+
import { logScrubbed } from '../redact.js';
|
|
8
9
|
/**
|
|
9
10
|
* Check if a 403 response is a 2FA error by checking the error id
|
|
10
11
|
*/
|
|
@@ -23,31 +24,34 @@ export async function is2FAError(response) {
|
|
|
23
24
|
return false;
|
|
24
25
|
}
|
|
25
26
|
/**
|
|
26
|
-
* Handle a 2FA challenge by prompting for a code and
|
|
27
|
+
* Handle a 2FA challenge by prompting for a code and forcing a retry of the
|
|
28
|
+
* request with the `Heroku-Two-Factor-Code` header attached.
|
|
29
|
+
*
|
|
30
|
+
* Returns ky's forced-retry marker (`ky.retry`) so ky re-issues the request
|
|
31
|
+
* through this same client — reusing its fetch, auth, and the original
|
|
32
|
+
* request's per-call timeout and abort signal — and runs the retried response
|
|
33
|
+
* back through the full afterResponse chain (error handling, Request-Id,
|
|
34
|
+
* warnings, metadata, and consumer hooks) exactly once. The forced retry counts
|
|
35
|
+
* against `retry.limit` and is observable in `beforeRetry` as a
|
|
36
|
+
* `ForceRetryError`.
|
|
37
|
+
*
|
|
38
|
+
* Because it draws on the same retry budget as ky's transport retries, a
|
|
39
|
+
* request that already exhausted `retry.limit` on network/timeout retries would
|
|
40
|
+
* surface the raw `ForceRetryError` rather than re-issuing. In practice a 2FA
|
|
41
|
+
* challenge arrives on the first attempt (before any transport retry), so the
|
|
42
|
+
* budget is intact; this edge only matters if that assumption ever breaks.
|
|
27
43
|
*/
|
|
28
|
-
export async function handle2FAChallenge(request, twoFactorOptions
|
|
29
|
-
twoFactorAttemptedRef.value = true;
|
|
44
|
+
export async function handle2FAChallenge(request, twoFactorOptions) {
|
|
30
45
|
debugAuth('2FA challenge detected, invoking callback');
|
|
31
46
|
try {
|
|
32
47
|
const twoFactorCode = await twoFactorOptions.onChallenge();
|
|
33
48
|
debugAuth('2FA code received, retrying request');
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
request.headers.forEach((value, key) => {
|
|
38
|
-
headers[key] = value;
|
|
39
|
-
});
|
|
40
|
-
headers['Heroku-Two-Factor-Code'] = twoFactorCode;
|
|
41
|
-
const retryRequest = new Request(request, {
|
|
42
|
-
headers,
|
|
43
|
-
});
|
|
44
|
-
const retryResponse = await ky(retryRequest);
|
|
45
|
-
twoFactorAttemptedRef.value = false;
|
|
46
|
-
return retryResponse;
|
|
49
|
+
const headers = new Headers(request.headers);
|
|
50
|
+
headers.set('Heroku-Two-Factor-Code', twoFactorCode);
|
|
51
|
+
return ky.retry({ code: 'TWO_FACTOR', request: new Request(request, { headers }) });
|
|
47
52
|
}
|
|
48
53
|
catch (error) {
|
|
49
|
-
|
|
50
|
-
debugError('2FA retry failed: %O', error);
|
|
54
|
+
await logScrubbed(debugError, '2FA retry failed: %O', error);
|
|
51
55
|
throw error;
|
|
52
56
|
}
|
|
53
57
|
}
|
package/dist/debug-loggers.d.ts
CHANGED
package/dist/debug-loggers.js
CHANGED
|
@@ -3,4 +3,3 @@ export const debugRequest = debug('heroku:fetch:request');
|
|
|
3
3
|
export const debugResponse = debug('heroku:fetch:response');
|
|
4
4
|
export const debugAuth = debug('heroku:fetch:auth');
|
|
5
5
|
export const debugError = debug('heroku:fetch:error');
|
|
6
|
-
export const debugCliLogin = debug('heroku:fetch:cli:login');
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* API host/URL utilities for the Heroku API — resolve the API host and base
|
|
3
|
+
* URL from `HEROKU_HOST`, falling back to the public defaults.
|
|
4
|
+
*
|
|
5
|
+
* Note: heroku-fetch does not read stored credentials. Credential storage and
|
|
6
|
+
* retrieval (netrc, native credential stores) lives in the
|
|
7
|
+
* `@heroku/heroku-credential-manager` package; supply a token to the client
|
|
8
|
+
* explicitly.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Get the API host from environment or default
|
|
12
|
+
*
|
|
13
|
+
* @returns The API host (default: 'api.heroku.com')
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* const host = getApiHost();
|
|
18
|
+
* // Returns 'api.heroku.com' or value of HEROKU_HOST env var
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export declare function getApiHost(): string;
|
|
22
|
+
/**
|
|
23
|
+
* Get the full API URL from environment or default
|
|
24
|
+
*
|
|
25
|
+
* @returns The API URL (default: 'https://api.heroku.com')
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```typescript
|
|
29
|
+
* const url = getApiUrl();
|
|
30
|
+
* // Returns 'https://api.heroku.com' or https://{HEROKU_HOST}
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare function getApiUrl(): string;
|
package/dist/host.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* API host/URL utilities for the Heroku API — resolve the API host and base
|
|
3
|
+
* URL from `HEROKU_HOST`, falling back to the public defaults.
|
|
4
|
+
*
|
|
5
|
+
* Note: heroku-fetch does not read stored credentials. Credential storage and
|
|
6
|
+
* retrieval (netrc, native credential stores) lives in the
|
|
7
|
+
* `@heroku/heroku-credential-manager` package; supply a token to the client
|
|
8
|
+
* explicitly.
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Get the API host from environment or default
|
|
12
|
+
*
|
|
13
|
+
* @returns The API host (default: 'api.heroku.com')
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* const host = getApiHost();
|
|
18
|
+
* // Returns 'api.heroku.com' or value of HEROKU_HOST env var
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export function getApiHost() {
|
|
22
|
+
return process.env.HEROKU_HOST || 'api.heroku.com';
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Get the full API URL from environment or default
|
|
26
|
+
*
|
|
27
|
+
* @returns The API URL (default: 'https://api.heroku.com')
|
|
28
|
+
*
|
|
29
|
+
* @example
|
|
30
|
+
* ```typescript
|
|
31
|
+
* const url = getApiUrl();
|
|
32
|
+
* // Returns 'https://api.heroku.com' or https://{HEROKU_HOST}
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export function getApiUrl() {
|
|
36
|
+
const host = getApiHost();
|
|
37
|
+
return `https://${host}`;
|
|
38
|
+
}
|