@heroku/heroku-fetch 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/browser-environment-defaults.d.ts +16 -0
- package/dist/client/browser-environment-defaults.js +18 -0
- package/dist/client/index.d.ts +39 -0
- package/dist/client/index.js +140 -12
- package/dist/client/node-environment-defaults.d.ts +8 -0
- package/dist/client/node-environment-defaults.js +10 -0
- package/dist/client/user-agent.d.ts +32 -0
- package/dist/client/user-agent.js +39 -0
- package/dist/public-types.d.ts +1 -1
- package/dist/types.d.ts +111 -0
- package/package.json +3 -3
|
@@ -11,6 +11,22 @@ export declare function getDefaultTokenProvider(): TokenProvider | undefined;
|
|
|
11
11
|
* Get default 2FA handler for browsers (none - must be explicitly provided)
|
|
12
12
|
*/
|
|
13
13
|
export declare function getDefaultTwoFactorOptions(): TwoFactorOptions | undefined;
|
|
14
|
+
/**
|
|
15
|
+
* The `User-Agent` comment (RFC 9110 §5.6.5) for browsers: `undefined`, which
|
|
16
|
+
* signals the client to set no managed `User-Agent` at all on browser builds
|
|
17
|
+
* (see `resolveUserAgentHeader`). Two reasons the browser opts out rather than
|
|
18
|
+
* sending a bare `<name>/<version>`:
|
|
19
|
+
* - `User-Agent` is not a CORS-safelisted request header, so a cross-origin
|
|
20
|
+
* `fetch` that sets it triggers a preflight and fails the whole request if the
|
|
21
|
+
* server doesn't list it in `Access-Control-Allow-Headers`. Chromium silently
|
|
22
|
+
* drops a `fetch`-set `User-Agent`, but Firefox sends it — so emitting one
|
|
23
|
+
* would break Firefox callers against a server that doesn't allow the header.
|
|
24
|
+
* - The browser already sends its own `User-Agent`, and exposes no reliable
|
|
25
|
+
* platform/runtime token to add, so a client-managed one carries little value.
|
|
26
|
+
*
|
|
27
|
+
* Mirrors the Node `getUserAgentComment()` so the client can call it uniformly.
|
|
28
|
+
*/
|
|
29
|
+
export declare function getUserAgentComment(): string | undefined;
|
|
14
30
|
/**
|
|
15
31
|
* Get a default dispatcher for the browser.
|
|
16
32
|
*
|
|
@@ -14,6 +14,24 @@ export function getDefaultTokenProvider() {
|
|
|
14
14
|
export function getDefaultTwoFactorOptions() {
|
|
15
15
|
return undefined;
|
|
16
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* The `User-Agent` comment (RFC 9110 §5.6.5) for browsers: `undefined`, which
|
|
19
|
+
* signals the client to set no managed `User-Agent` at all on browser builds
|
|
20
|
+
* (see `resolveUserAgentHeader`). Two reasons the browser opts out rather than
|
|
21
|
+
* sending a bare `<name>/<version>`:
|
|
22
|
+
* - `User-Agent` is not a CORS-safelisted request header, so a cross-origin
|
|
23
|
+
* `fetch` that sets it triggers a preflight and fails the whole request if the
|
|
24
|
+
* server doesn't list it in `Access-Control-Allow-Headers`. Chromium silently
|
|
25
|
+
* drops a `fetch`-set `User-Agent`, but Firefox sends it — so emitting one
|
|
26
|
+
* would break Firefox callers against a server that doesn't allow the header.
|
|
27
|
+
* - The browser already sends its own `User-Agent`, and exposes no reliable
|
|
28
|
+
* platform/runtime token to add, so a client-managed one carries little value.
|
|
29
|
+
*
|
|
30
|
+
* Mirrors the Node `getUserAgentComment()` so the client can call it uniformly.
|
|
31
|
+
*/
|
|
32
|
+
export function getUserAgentComment() {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
17
35
|
/**
|
|
18
36
|
* Get a default dispatcher for the browser.
|
|
19
37
|
*
|
package/dist/client/index.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ export declare class HerokuApiClient {
|
|
|
10
10
|
private clientPromise;
|
|
11
11
|
private kyOptions;
|
|
12
12
|
private options;
|
|
13
|
+
private reauthorizePromise;
|
|
13
14
|
private readonly requestIds;
|
|
14
15
|
private readonly shownWarnings;
|
|
15
16
|
private tokenProvider?;
|
|
@@ -57,8 +58,46 @@ export declare class HerokuApiClient {
|
|
|
57
58
|
* Get the authorization token
|
|
58
59
|
*/
|
|
59
60
|
private getToken;
|
|
61
|
+
/**
|
|
62
|
+
* Run `reauthorize` at most once across concurrent 401s. The first 401 to
|
|
63
|
+
* arrive starts the refresh and every other 401 in flight awaits the same
|
|
64
|
+
* promise instead of each firing the callback — so a stale token shared by N
|
|
65
|
+
* parallel requests drives one `heroku login`, not N. The shared promise is
|
|
66
|
+
* cleared once it settles, so a *later* 401 (e.g. the refreshed token has
|
|
67
|
+
* since expired) starts a fresh refresh rather than reusing a stale result.
|
|
68
|
+
*
|
|
69
|
+
* The first caller's `signal` drives the shared refresh; a later waiter's own
|
|
70
|
+
* signal still aborts its request independently (checked in `send` before and
|
|
71
|
+
* surfaced by its own `client()` retry), it just can't cancel the in-flight
|
|
72
|
+
* refresh another request already started.
|
|
73
|
+
*/
|
|
74
|
+
private reauthorizeOnce;
|
|
60
75
|
/**
|
|
61
76
|
* Make a request with full control over options
|
|
62
77
|
*/
|
|
63
78
|
private request;
|
|
79
|
+
/**
|
|
80
|
+
* The `reauthorize` callback to apply for a request: the client-level one,
|
|
81
|
+
* unless the request opts out with `reauthorize: false` (the per-request
|
|
82
|
+
* escape hatch mirroring the legacy `APIClient`'s `retryAuth: false`, for
|
|
83
|
+
* call sites where a 401 must surface rather than drive a login).
|
|
84
|
+
*/
|
|
85
|
+
private resolveReauthorize;
|
|
86
|
+
/**
|
|
87
|
+
* Issue the request through ky. With an effective `reauthorize` callback, a
|
|
88
|
+
* 401 (thrown as `AuthenticationError` by the error hook) runs the callback
|
|
89
|
+
* and retries once — the retry re-runs the pipeline, so `beforeRequest`
|
|
90
|
+
* re-resolves the token. The retry sits outside the `try`, so a second 401
|
|
91
|
+
* propagates rather than looping; an already-aborted signal skips the
|
|
92
|
+
* (possibly interactive) refresh entirely. Without a callback (none configured,
|
|
93
|
+
* or the request opted out via `RequestOptions.reauthorize: false`), a plain
|
|
94
|
+
* pass-through.
|
|
95
|
+
*
|
|
96
|
+
* Replaying a non-idempotent write this way is safe for Heroku's front-door
|
|
97
|
+
* auth, which rejects a 401 before the server executes the request. It is not
|
|
98
|
+
* universally safe: a `data`/`particleboard`/`custom` host that returns a
|
|
99
|
+
* downstream or proxied 401 *after* side effects have begun would see the
|
|
100
|
+
* write run twice. Opt such a request out with `reauthorize: false`.
|
|
101
|
+
*/
|
|
102
|
+
private send;
|
|
64
103
|
}
|
package/dist/client/index.js
CHANGED
|
@@ -5,15 +5,36 @@
|
|
|
5
5
|
* Supports multiple services (platform, data, particleboard), authentication,
|
|
6
6
|
* two-factor authentication, and comprehensive error handling.
|
|
7
7
|
*/
|
|
8
|
-
import { getDefaultFetch, getDefaultTokenProvider, getDefaultTwoFactorOptions } from '@heroku/heroku-fetch/client/environment-defaults.js';
|
|
8
|
+
import { getDefaultFetch, getDefaultTokenProvider, getDefaultTwoFactorOptions, getUserAgentComment, } 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 { AuthenticationError } from '../errors.js';
|
|
11
12
|
import { create2FAAfterHook, createBeforeRequestHook, createErrorAfterHook, createMetadataAfterHook, createRequestIdAfterHook, createRequestIdBeforeHook, createWarningAfterHook, } from './http-request-hooks.js';
|
|
12
13
|
import { RequestIdStore } from './request-id.js';
|
|
13
14
|
import { SERVICE_CONFIGS } from './service-configurations.js';
|
|
15
|
+
import { resolveUserAgentHeader } from './user-agent.js';
|
|
16
|
+
/**
|
|
17
|
+
* Combine zero or more optional abort signals into one. Returns `undefined`
|
|
18
|
+
* when none are present (so callers can omit `signal` entirely rather than pass
|
|
19
|
+
* a signal that never fires), the single signal when only one is present, and
|
|
20
|
+
* an `AbortSignal.any(...)` composite when several are — the composite aborts as
|
|
21
|
+
* soon as any input does. Lets a client-level default signal and a per-request
|
|
22
|
+
* signal both abort the same request instead of one shadowing the other.
|
|
23
|
+
*/
|
|
24
|
+
function combineSignals(...signals) {
|
|
25
|
+
const present = signals.filter((signal) => signal !== undefined);
|
|
26
|
+
if (present.length <= 1) {
|
|
27
|
+
return present[0];
|
|
28
|
+
}
|
|
29
|
+
return AbortSignal.any(present);
|
|
30
|
+
}
|
|
14
31
|
export class HerokuApiClient {
|
|
15
32
|
constructor(options = {}) {
|
|
16
33
|
this.clientPromise = null;
|
|
34
|
+
// A single in-flight reauthorize refresh, shared across concurrent 401s so the
|
|
35
|
+
// callback (e.g. an interactive `heroku login`) fires once rather than once
|
|
36
|
+
// per request. Null when no refresh is running; cleared when one settles.
|
|
37
|
+
this.reauthorizePromise = null;
|
|
17
38
|
// Per-client cross-cutting request state: the Request-Id accumulation and the
|
|
18
39
|
// set of warnings already surfaced, so dedupe spans a multi-request session
|
|
19
40
|
// but resets per client and parallel clients stay isolated.
|
|
@@ -50,13 +71,27 @@ export class HerokuApiClient {
|
|
|
50
71
|
// and no override contribute no Accept at all.
|
|
51
72
|
const defaultAccept = options.defaultAccept ?? serviceConfig.defaultAccept;
|
|
52
73
|
const headers = { ...options.headers };
|
|
53
|
-
// Case-insensitive check: a consumer may have supplied
|
|
74
|
+
// Case-insensitive check: a consumer may have supplied a header under any
|
|
54
75
|
// casing, and ky merges headers case-insensitively (last write wins), so a
|
|
55
76
|
// plain `'Accept' in headers` test would miss a lowercase `accept` and let
|
|
56
77
|
// our default clobber the consumer's choice.
|
|
57
|
-
|
|
78
|
+
const providedHeaders = new Headers(options.headers);
|
|
79
|
+
if (defaultAccept && !providedHeaders.has('accept')) {
|
|
58
80
|
headers.Accept = defaultAccept;
|
|
59
81
|
}
|
|
82
|
+
// Self-identifying User-Agent, same fill-if-absent rule as Accept: set it
|
|
83
|
+
// only when the caller hasn't supplied one on the client (a per-call
|
|
84
|
+
// `User-Agent` still wins via ky's per-call-over-instance merge). Omitted or
|
|
85
|
+
// incomplete `userAgent` → no User-Agent is set (resolveUserAgentHeader
|
|
86
|
+
// returns undefined). Browser builds opt out entirely: getUserAgentComment
|
|
87
|
+
// returns undefined there (a fetch-set User-Agent isn't CORS-safelisted), so
|
|
88
|
+
// no managed User-Agent is sent regardless of the option.
|
|
89
|
+
if (!providedHeaders.has('user-agent')) {
|
|
90
|
+
const userAgent = resolveUserAgentHeader(options.userAgent, getUserAgentComment());
|
|
91
|
+
if (userAgent) {
|
|
92
|
+
headers['User-Agent'] = userAgent;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
60
95
|
this.kyOptions = {
|
|
61
96
|
headers,
|
|
62
97
|
hooks: {
|
|
@@ -130,11 +165,14 @@ export class HerokuApiClient {
|
|
|
130
165
|
return;
|
|
131
166
|
}
|
|
132
167
|
// Only these are re-read on each request, so changing them takes effect.
|
|
133
|
-
//
|
|
134
|
-
//
|
|
135
|
-
//
|
|
136
|
-
//
|
|
137
|
-
|
|
168
|
+
// hooks, headers, the Accept default, the 2FA handler, and the
|
|
169
|
+
// service/region base URL are baked into the cached ky instance at
|
|
170
|
+
// construction, so mutating them here would silently no-op — reject rather
|
|
171
|
+
// than lie about the change landing. `reauthorize` IS read per request (so a
|
|
172
|
+
// mutation would land), but is deliberately kept construction-only: it's an
|
|
173
|
+
// auth policy that should be fixed for the client, with per-request control
|
|
174
|
+
// exposed instead through `RequestOptions.reauthorize: false`.
|
|
175
|
+
if (key === 'timeout' || key === 'warn' || key === 'onResponseMetadata' || key === 'signal') {
|
|
138
176
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
139
177
|
this.options[key] = value;
|
|
140
178
|
return;
|
|
@@ -146,18 +184,19 @@ export class HerokuApiClient {
|
|
|
146
184
|
*/
|
|
147
185
|
async stream(path, options) {
|
|
148
186
|
debugRequest('STREAM %s', path);
|
|
187
|
+
const signal = combineSignals(this.options.signal, options?.signal);
|
|
149
188
|
const kyOptions = {
|
|
150
189
|
// Only set these when the caller supplied them: a literal `undefined`
|
|
151
190
|
// overrides (and for headers, clears) what ky merges from the instance,
|
|
152
191
|
// rather than leaving the instance value untouched.
|
|
153
192
|
...(options?.headers && { headers: options.headers }),
|
|
154
193
|
...(options?.searchParams && { searchParams: options.searchParams }),
|
|
155
|
-
...(
|
|
194
|
+
...(signal && { signal }),
|
|
156
195
|
method: 'GET',
|
|
157
196
|
timeout: options?.timeout || this.options.timeout,
|
|
158
197
|
};
|
|
159
198
|
const client = await this.getClient();
|
|
160
|
-
return client
|
|
199
|
+
return this.send(client, path, kyOptions, this.resolveReauthorize(options?.reauthorize));
|
|
161
200
|
}
|
|
162
201
|
/**
|
|
163
202
|
* Lazily construct ky over a fetch that is proxy-aware on Node (undici's own
|
|
@@ -190,17 +229,42 @@ export class HerokuApiClient {
|
|
|
190
229
|
}
|
|
191
230
|
return this.tokenProvider();
|
|
192
231
|
}
|
|
232
|
+
/**
|
|
233
|
+
* Run `reauthorize` at most once across concurrent 401s. The first 401 to
|
|
234
|
+
* arrive starts the refresh and every other 401 in flight awaits the same
|
|
235
|
+
* promise instead of each firing the callback — so a stale token shared by N
|
|
236
|
+
* parallel requests drives one `heroku login`, not N. The shared promise is
|
|
237
|
+
* cleared once it settles, so a *later* 401 (e.g. the refreshed token has
|
|
238
|
+
* since expired) starts a fresh refresh rather than reusing a stale result.
|
|
239
|
+
*
|
|
240
|
+
* The first caller's `signal` drives the shared refresh; a later waiter's own
|
|
241
|
+
* signal still aborts its request independently (checked in `send` before and
|
|
242
|
+
* surfaced by its own `client()` retry), it just can't cancel the in-flight
|
|
243
|
+
* refresh another request already started.
|
|
244
|
+
*/
|
|
245
|
+
reauthorizeOnce(reauthorize, signal) {
|
|
246
|
+
this.reauthorizePromise ?? (this.reauthorizePromise = (async () => {
|
|
247
|
+
try {
|
|
248
|
+
await reauthorize({ signal });
|
|
249
|
+
}
|
|
250
|
+
finally {
|
|
251
|
+
this.reauthorizePromise = null;
|
|
252
|
+
}
|
|
253
|
+
})());
|
|
254
|
+
return this.reauthorizePromise;
|
|
255
|
+
}
|
|
193
256
|
/**
|
|
194
257
|
* Make a request with full control over options
|
|
195
258
|
*/
|
|
196
259
|
async request(path, options) {
|
|
260
|
+
const signal = combineSignals(this.options.signal, options?.signal);
|
|
197
261
|
const kyOptions = {
|
|
198
262
|
// Only set these when the caller supplied them: a literal `undefined`
|
|
199
263
|
// overrides (and for headers, clears) what ky merges from the instance,
|
|
200
264
|
// rather than leaving the instance value untouched.
|
|
201
265
|
...(options?.headers && { headers: options.headers }),
|
|
202
266
|
...(options?.searchParams && { searchParams: options.searchParams }),
|
|
203
|
-
...(
|
|
267
|
+
...(signal && { signal }),
|
|
204
268
|
method: options?.method || 'GET',
|
|
205
269
|
timeout: options?.timeout || this.options.timeout,
|
|
206
270
|
};
|
|
@@ -208,6 +272,70 @@ export class HerokuApiClient {
|
|
|
208
272
|
kyOptions.json = options.body;
|
|
209
273
|
}
|
|
210
274
|
const client = await this.getClient();
|
|
211
|
-
return client
|
|
275
|
+
return this.send(client, path, kyOptions, this.resolveReauthorize(options?.reauthorize));
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* The `reauthorize` callback to apply for a request: the client-level one,
|
|
279
|
+
* unless the request opts out with `reauthorize: false` (the per-request
|
|
280
|
+
* escape hatch mirroring the legacy `APIClient`'s `retryAuth: false`, for
|
|
281
|
+
* call sites where a 401 must surface rather than drive a login).
|
|
282
|
+
*/
|
|
283
|
+
resolveReauthorize(optOut) {
|
|
284
|
+
return optOut === false ? undefined : this.options.reauthorize;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Issue the request through ky. With an effective `reauthorize` callback, a
|
|
288
|
+
* 401 (thrown as `AuthenticationError` by the error hook) runs the callback
|
|
289
|
+
* and retries once — the retry re-runs the pipeline, so `beforeRequest`
|
|
290
|
+
* re-resolves the token. The retry sits outside the `try`, so a second 401
|
|
291
|
+
* propagates rather than looping; an already-aborted signal skips the
|
|
292
|
+
* (possibly interactive) refresh entirely. Without a callback (none configured,
|
|
293
|
+
* or the request opted out via `RequestOptions.reauthorize: false`), a plain
|
|
294
|
+
* pass-through.
|
|
295
|
+
*
|
|
296
|
+
* Replaying a non-idempotent write this way is safe for Heroku's front-door
|
|
297
|
+
* auth, which rejects a 401 before the server executes the request. It is not
|
|
298
|
+
* universally safe: a `data`/`particleboard`/`custom` host that returns a
|
|
299
|
+
* downstream or proxied 401 *after* side effects have begun would see the
|
|
300
|
+
* write run twice. Opt such a request out with `reauthorize: false`.
|
|
301
|
+
*/
|
|
302
|
+
async send(client, path, kyOptions, reauthorize) {
|
|
303
|
+
if (!reauthorize) {
|
|
304
|
+
return client(path, kyOptions);
|
|
305
|
+
}
|
|
306
|
+
try {
|
|
307
|
+
return await client(path, kyOptions);
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
if (error instanceof AuthenticationError) {
|
|
311
|
+
// Don't run the refresh if the caller already aborted; hand the callback
|
|
312
|
+
// the same combined signal so an interactive refresh can bail too.
|
|
313
|
+
const signal = kyOptions.signal ?? undefined;
|
|
314
|
+
signal?.throwIfAborted();
|
|
315
|
+
debugAuth('401 received; invoking reauthorize and retrying once');
|
|
316
|
+
try {
|
|
317
|
+
// Coalesced: concurrent 401s sharing a stale token await one refresh.
|
|
318
|
+
await this.reauthorizeOnce(reauthorize, signal);
|
|
319
|
+
}
|
|
320
|
+
catch (reauthorizeError) {
|
|
321
|
+
// The callback's own failure propagates in place of the 401, but keep
|
|
322
|
+
// the original attached as `cause` so consumers don't lose the 401's
|
|
323
|
+
// statusCode/id/request context (and an `instanceof AuthenticationError`
|
|
324
|
+
// check on the cause chain still works). Only set it when the callback
|
|
325
|
+
// didn't already supply a cause of its own. (Cast for `cause`: the
|
|
326
|
+
// package targets the ES2020 lib, where it isn't yet on `Error`.)
|
|
327
|
+
const withCause = reauthorizeError;
|
|
328
|
+
if (reauthorizeError instanceof Error && withCause.cause === undefined) {
|
|
329
|
+
withCause.cause = error;
|
|
330
|
+
}
|
|
331
|
+
throw reauthorizeError;
|
|
332
|
+
}
|
|
333
|
+
// The retry is a fresh request: if the original also cleared a 2FA
|
|
334
|
+
// challenge, the retried one re-prompts (it drops the one-shot
|
|
335
|
+
// Heroku-Two-Factor-Code header). Bounded to one extra prompt, not a loop.
|
|
336
|
+
return client(path, kyOptions);
|
|
337
|
+
}
|
|
338
|
+
throw error;
|
|
339
|
+
}
|
|
212
340
|
}
|
|
213
341
|
}
|
|
@@ -15,6 +15,14 @@ import type { FetchLike, TokenProvider, TwoFactorOptions } from '../types.js';
|
|
|
15
15
|
* `AuthenticationError`.
|
|
16
16
|
*/
|
|
17
17
|
export declare function getDefaultTokenProvider(): TokenProvider;
|
|
18
|
+
/**
|
|
19
|
+
* The Node-specific `User-Agent` comment (RFC 9110 §5.6.5) appended after the
|
|
20
|
+
* product token: `(<platform>; <arch>) Node.js/<version>`, e.g.
|
|
21
|
+
* `(darwin; arm64) Node.js/22.21.0`. The browser build returns `undefined`
|
|
22
|
+
* instead, opting out of a client-managed `User-Agent` entirely (a `fetch`-set
|
|
23
|
+
* `User-Agent` isn't CORS-safelisted); see the browser `getUserAgentComment`.
|
|
24
|
+
*/
|
|
25
|
+
export declare function getUserAgentComment(): string | undefined;
|
|
18
26
|
/**
|
|
19
27
|
* Get default 2FA handler for Node.js (uses CLI prompts)
|
|
20
28
|
*/
|
|
@@ -18,6 +18,16 @@ import { logScrubbed } from '../redact.js';
|
|
|
18
18
|
export function getDefaultTokenProvider() {
|
|
19
19
|
return () => process.env.HEROKU_API_KEY;
|
|
20
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* The Node-specific `User-Agent` comment (RFC 9110 §5.6.5) appended after the
|
|
23
|
+
* product token: `(<platform>; <arch>) Node.js/<version>`, e.g.
|
|
24
|
+
* `(darwin; arm64) Node.js/22.21.0`. The browser build returns `undefined`
|
|
25
|
+
* instead, opting out of a client-managed `User-Agent` entirely (a `fetch`-set
|
|
26
|
+
* `User-Agent` isn't CORS-safelisted); see the browser `getUserAgentComment`.
|
|
27
|
+
*/
|
|
28
|
+
export function getUserAgentComment() {
|
|
29
|
+
return `(${process.platform}; ${process.arch}) Node.js/${process.versions.node}`;
|
|
30
|
+
}
|
|
21
31
|
/**
|
|
22
32
|
* Get default 2FA handler for Node.js (uses CLI prompts)
|
|
23
33
|
*/
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { UserAgentOptions } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Assemble a `User-Agent` string in the canonical form defined by RFC 9110
|
|
4
|
+
* §10.1.5 — a `product` token (`<name>/<version>`) optionally followed by a
|
|
5
|
+
* `comment` (RFC 9110 §5.6.5) carrying implementation detail. The comment (the
|
|
6
|
+
* Node platform/runtime token from `getUserAgentComment` in the
|
|
7
|
+
* environment-defaults modules) is appended after the product token when
|
|
8
|
+
* present: `heroku-cli/11.4.0 (darwin; arm64) Node.js/22.21.0`, degrading to the
|
|
9
|
+
* bare `heroku-cli/11.4.0` when the comment is empty. (The browser build opts
|
|
10
|
+
* out of a client-managed `User-Agent` entirely upstream in
|
|
11
|
+
* {@link resolveUserAgentHeader}, so it never reaches here.)
|
|
12
|
+
*
|
|
13
|
+
* Note this canonical `product (comment)` shape differs from the older Heroku
|
|
14
|
+
* clients (`@heroku-cli/command` emits `heroku-cli/<v> <platform>`, `http-call`
|
|
15
|
+
* emits `node-<v>`): server-side consumers that pattern-match the legacy string
|
|
16
|
+
* shape will not match this one.
|
|
17
|
+
*/
|
|
18
|
+
export declare function formatUserAgent(userAgent: UserAgentOptions, comment: string): string;
|
|
19
|
+
/**
|
|
20
|
+
* Resolve the `User-Agent` header value to apply, or `undefined` when none
|
|
21
|
+
* should be set. Returns `undefined` when:
|
|
22
|
+
* - `comment` is `undefined` — the platform opts out of a client-managed
|
|
23
|
+
* `User-Agent` entirely (the browser build, which returns `undefined` from
|
|
24
|
+
* `getUserAgentComment`: a `fetch`-set `User-Agent` isn't CORS-safelisted, so
|
|
25
|
+
* emitting one risks a preflight rejection, and the browser sends its own
|
|
26
|
+
* anyway); or
|
|
27
|
+
* - the option is absent or incomplete (either `name` or `version` empty), so
|
|
28
|
+
* the client never emits a malformed token like `/ (darwin; arm64) …`.
|
|
29
|
+
*
|
|
30
|
+
* Otherwise delegates to {@link formatUserAgent}.
|
|
31
|
+
*/
|
|
32
|
+
export declare function resolveUserAgentHeader(userAgent: undefined | UserAgentOptions, comment: string | undefined): string | undefined;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Assemble a `User-Agent` string in the canonical form defined by RFC 9110
|
|
3
|
+
* §10.1.5 — a `product` token (`<name>/<version>`) optionally followed by a
|
|
4
|
+
* `comment` (RFC 9110 §5.6.5) carrying implementation detail. The comment (the
|
|
5
|
+
* Node platform/runtime token from `getUserAgentComment` in the
|
|
6
|
+
* environment-defaults modules) is appended after the product token when
|
|
7
|
+
* present: `heroku-cli/11.4.0 (darwin; arm64) Node.js/22.21.0`, degrading to the
|
|
8
|
+
* bare `heroku-cli/11.4.0` when the comment is empty. (The browser build opts
|
|
9
|
+
* out of a client-managed `User-Agent` entirely upstream in
|
|
10
|
+
* {@link resolveUserAgentHeader}, so it never reaches here.)
|
|
11
|
+
*
|
|
12
|
+
* Note this canonical `product (comment)` shape differs from the older Heroku
|
|
13
|
+
* clients (`@heroku-cli/command` emits `heroku-cli/<v> <platform>`, `http-call`
|
|
14
|
+
* emits `node-<v>`): server-side consumers that pattern-match the legacy string
|
|
15
|
+
* shape will not match this one.
|
|
16
|
+
*/
|
|
17
|
+
export function formatUserAgent(userAgent, comment) {
|
|
18
|
+
const product = `${userAgent.name}/${userAgent.version}`;
|
|
19
|
+
return comment ? `${product} ${comment}` : product;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Resolve the `User-Agent` header value to apply, or `undefined` when none
|
|
23
|
+
* should be set. Returns `undefined` when:
|
|
24
|
+
* - `comment` is `undefined` — the platform opts out of a client-managed
|
|
25
|
+
* `User-Agent` entirely (the browser build, which returns `undefined` from
|
|
26
|
+
* `getUserAgentComment`: a `fetch`-set `User-Agent` isn't CORS-safelisted, so
|
|
27
|
+
* emitting one risks a preflight rejection, and the browser sends its own
|
|
28
|
+
* anyway); or
|
|
29
|
+
* - the option is absent or incomplete (either `name` or `version` empty), so
|
|
30
|
+
* the client never emits a malformed token like `/ (darwin; arm64) …`.
|
|
31
|
+
*
|
|
32
|
+
* Otherwise delegates to {@link formatUserAgent}.
|
|
33
|
+
*/
|
|
34
|
+
export function resolveUserAgentHeader(userAgent, comment) {
|
|
35
|
+
if (comment === undefined || !userAgent?.name || !userAgent.version) {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
return formatUserAgent(userAgent, comment);
|
|
39
|
+
}
|
package/dist/public-types.d.ts
CHANGED
|
@@ -4,4 +4,4 @@
|
|
|
4
4
|
* Types only — runtime values (the client class, errors, helpers) are exported
|
|
5
5
|
* directly from each entry point, which differ by environment.
|
|
6
6
|
*/
|
|
7
|
-
export type { FetchLike, HerokuAfterResponseHook, HerokuApiClientOptions, HerokuBeforeRequestHook, HerokuError, HerokuErrorResponse, HerokuHooks, HerokuService, RequestOptions, ResponseMetadata, ServiceConfig, TokenProvider, TwoFactorOptions, } from './types.js';
|
|
7
|
+
export type { FetchLike, HerokuAfterResponseHook, HerokuApiClientOptions, HerokuBeforeRequestHook, HerokuError, HerokuErrorResponse, HerokuHooks, HerokuService, RequestOptions, ResponseMetadata, ServiceConfig, TokenProvider, TwoFactorOptions, UserAgentOptions, } from './types.js';
|
package/dist/types.d.ts
CHANGED
|
@@ -98,6 +98,20 @@ export interface ServiceConfig {
|
|
|
98
98
|
/** Default region (if applicable) */
|
|
99
99
|
region?: string;
|
|
100
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* Identifies the consumer in the `User-Agent` header: a product `name` and
|
|
103
|
+
* `version`. On Node the client assembles these into a canonical token with a
|
|
104
|
+
* platform/runtime comment appended
|
|
105
|
+
* (`<name>/<version> (<platform>; <arch>) Node.js/<version>`). Ignored on
|
|
106
|
+
* browser builds (no `User-Agent` is sent — see
|
|
107
|
+
* {@link HerokuApiClientOptions.userAgent}).
|
|
108
|
+
*/
|
|
109
|
+
export interface UserAgentOptions {
|
|
110
|
+
/** Product name, e.g. `heroku-cli`. */
|
|
111
|
+
name: string;
|
|
112
|
+
/** Product version, e.g. `11.4.0`. */
|
|
113
|
+
version: string;
|
|
114
|
+
}
|
|
101
115
|
export interface HerokuApiClientOptions {
|
|
102
116
|
/** Custom base URL (for 'custom' service type) */
|
|
103
117
|
baseUrl?: string;
|
|
@@ -130,16 +144,104 @@ export interface HerokuApiClientOptions {
|
|
|
130
144
|
* with no built-in way to correlate them beyond the per-response metadata.
|
|
131
145
|
*/
|
|
132
146
|
onResponseMetadata?: (metadata: ResponseMetadata) => void;
|
|
147
|
+
/**
|
|
148
|
+
* Callback given one chance to refresh credentials when a request fails with a
|
|
149
|
+
* 401: the client awaits it, then retries the request exactly once, re-resolving
|
|
150
|
+
* the {@link HerokuApiClientOptions.token} provider so a refreshed token is
|
|
151
|
+
* picked up. A second 401 propagates; a rejection from the callback propagates
|
|
152
|
+
* in its place (with the original 401 attached as its `cause`). The callback
|
|
153
|
+
* fires at most once per request, and is skipped if the request's signal has
|
|
154
|
+
* already aborted.
|
|
155
|
+
*
|
|
156
|
+
* The retry only sends a *different* credential if {@link HerokuApiClientOptions.token} is a function
|
|
157
|
+
* that reads refreshed state (the callback mutates what the provider returns,
|
|
158
|
+
* as the CLI does by flipping to a fresh token). A static string `token` is
|
|
159
|
+
* resent unchanged, so the retry 401s again — if you set `reauthorize`, use a
|
|
160
|
+
* function `token`.
|
|
161
|
+
*
|
|
162
|
+
* Receives a context carrying the request's combined abort `signal` (the
|
|
163
|
+
* client-level signal composed with any per-call one), so an interactive
|
|
164
|
+
* refresh can bail when the caller aborts. The callback is itself untimed —
|
|
165
|
+
* ky's `timeout` bounds each HTTP attempt but not the awaited refresh between
|
|
166
|
+
* them, so a non-interactive refresh should honor the `signal` or impose its
|
|
167
|
+
* own bound rather than hang.
|
|
168
|
+
*
|
|
169
|
+
* Concurrent 401s are coalesced: when several requests share a stale token,
|
|
170
|
+
* the first to 401 runs the callback and the rest await that same refresh, so
|
|
171
|
+
* the client drives one `heroku login` rather than one per request. The shared
|
|
172
|
+
* refresh is per-client and cleared once it settles, so a later 401 (the
|
|
173
|
+
* refreshed token has since expired) starts a fresh one. The first 401's
|
|
174
|
+
* `signal` drives the shared refresh (see {@link HerokuApiClientOptions.signal}
|
|
175
|
+
* for the waiter-cancellation caveat). Beyond this coalescing the callback is
|
|
176
|
+
* policy-free: prompting and any "give up" rule belong in it. The Heroku CLI
|
|
177
|
+
* wires this to `heroku login`, so an SDK call with an expired or missing token
|
|
178
|
+
* re-prompts and retries. A single request can opt out with
|
|
179
|
+
* {@link RequestOptions.reauthorize} `: false` (so its 401 surfaces untouched).
|
|
180
|
+
* Omitted → a 401 throws `AuthenticationError` with no retry (unchanged behavior).
|
|
181
|
+
*/
|
|
182
|
+
reauthorize?: (context: {
|
|
183
|
+
signal?: AbortSignal;
|
|
184
|
+
}) => Promise<void> | void;
|
|
133
185
|
/** Service region (e.g., 'eu', 'us') */
|
|
134
186
|
region?: string;
|
|
135
187
|
/** Heroku service type (platform, data, particleboard, custom) */
|
|
136
188
|
service?: HerokuService;
|
|
189
|
+
/**
|
|
190
|
+
* Default `AbortSignal` applied to every request this client makes: when it
|
|
191
|
+
* fires, all in-flight and subsequent requests abort. Re-read per request, so
|
|
192
|
+
* it may also be set later via `setOption('signal', …)`. Composed (not
|
|
193
|
+
* replaced) with a per-call {@link RequestOptions.signal} and the client's
|
|
194
|
+
* `timeout` by the underlying ky layer — either firing aborts the request.
|
|
195
|
+
* Omitted → no client-level abort.
|
|
196
|
+
*
|
|
197
|
+
* There is no per-request opt-out: this signal is folded into *every* request,
|
|
198
|
+
* so once it fires, a call issued afterward — including best-effort cleanup
|
|
199
|
+
* from a SIGINT/abort handler — aborts immediately. Work that must outlive the
|
|
200
|
+
* abort should run on a separate client that doesn't carry the shared signal
|
|
201
|
+
* (or you should scope signals to the unit of work rather than wiring one
|
|
202
|
+
* process-wide signal into a shared, long-lived client).
|
|
203
|
+
*
|
|
204
|
+
* Caveat for {@link HerokuApiClientOptions.reauthorize}: a request's signal
|
|
205
|
+
* aborts *its own* HTTP attempts, but once another request's 401 has started
|
|
206
|
+
* the shared refresh, this request's signal can't cancel that in-flight
|
|
207
|
+
* refresh — only the signal of the request that started it can. Aborting a
|
|
208
|
+
* waiter still abandons its wait (its next `throwIfAborted`/HTTP attempt
|
|
209
|
+
* rejects); it just doesn't interrupt the refresh already running elsewhere.
|
|
210
|
+
*
|
|
211
|
+
* On long-lived hosts (a server or editor-extension process, vs. a short-lived
|
|
212
|
+
* CLI), a signal that never fires accumulates ~180 bytes/request on Node ≥ 22:
|
|
213
|
+
* ky composes it afresh with each request's timeout and Node retains the
|
|
214
|
+
* composite in the source signal's dependents set until that signal aborts or
|
|
215
|
+
* is GC'd. The retained memory is released on abort/GC, but while the signal
|
|
216
|
+
* lives it grows linearly with request count (~18 MB over 100k requests). So
|
|
217
|
+
* scope this signal (and the client) to a unit of work, or prefer a per-call
|
|
218
|
+
* {@link RequestOptions.signal}, rather than wiring a process-lifetime one.
|
|
219
|
+
*/
|
|
220
|
+
signal?: AbortSignal;
|
|
137
221
|
/** Request timeout in milliseconds */
|
|
138
222
|
timeout?: number;
|
|
139
223
|
/** Static bearer token or function to retrieve token */
|
|
140
224
|
token?: TokenProvider;
|
|
141
225
|
/** Two-factor authentication configuration */
|
|
142
226
|
twoFactor?: TwoFactorOptions;
|
|
227
|
+
/**
|
|
228
|
+
* Identifies this client's traffic with a `User-Agent` header, assembled from
|
|
229
|
+
* a product {@link UserAgentOptions.name} and {@link UserAgentOptions.version}:
|
|
230
|
+
* `heroku-cli/11.4.0 (darwin; arm64) Node.js/22.21.0` on Node. Applied only
|
|
231
|
+
* when the client's own `headers` don't already carry a `User-Agent`, so a
|
|
232
|
+
* client-level `headers: {'User-Agent'}` wins; a per-call `User-Agent` also
|
|
233
|
+
* wins via ky's per-call-over-instance header merge. Both `name` and `version`
|
|
234
|
+
* must be non-empty, else no `User-Agent` is set. Omitted → the client sets no
|
|
235
|
+
* `User-Agent`; the `@heroku/sdk` layer supplies its own default so
|
|
236
|
+
* SDK-originated traffic stays identifiable even when a consumer passes none.
|
|
237
|
+
*
|
|
238
|
+
* **Node only.** On browser builds this option is ignored and no `User-Agent`
|
|
239
|
+
* is sent: a `fetch`-set `User-Agent` is not a CORS-safelisted header, so a
|
|
240
|
+
* cross-origin request that sets it triggers a preflight and fails entirely if
|
|
241
|
+
* the server doesn't allow the header (Chromium silently drops it, but Firefox
|
|
242
|
+
* sends it) — and the browser sends its own `User-Agent` regardless.
|
|
243
|
+
*/
|
|
244
|
+
userAgent?: UserAgentOptions;
|
|
143
245
|
/**
|
|
144
246
|
* Callback for surfacing user-facing warnings the client raises — currently
|
|
145
247
|
* server `x-heroku-warning` / `warning-message` response headers. Called once
|
|
@@ -152,6 +254,15 @@ export interface HerokuApiClientOptions {
|
|
|
152
254
|
export interface RequestOptions {
|
|
153
255
|
/** Additional headers for this request */
|
|
154
256
|
headers?: Record<string, string>;
|
|
257
|
+
/**
|
|
258
|
+
* Opt this request out of the client-level {@link HerokuApiClientOptions.reauthorize}
|
|
259
|
+
* retry: when `false`, a 401 surfaces as `AuthenticationError` without running
|
|
260
|
+
* the callback or retrying. The per-request escape hatch mirroring the legacy
|
|
261
|
+
* `APIClient`'s `retryAuth: false` — for call sites where a 401 means something
|
|
262
|
+
* other than an expired Heroku credential (e.g. a non-Heroku bearer token) and
|
|
263
|
+
* must not drive a login. Omitted → the client-level behavior applies.
|
|
264
|
+
*/
|
|
265
|
+
reauthorize?: false;
|
|
155
266
|
/** Query parameters */
|
|
156
267
|
searchParams?: Record<string, boolean | number | string>;
|
|
157
268
|
/** Aborts the in-flight request when the signal fires. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@heroku/heroku-fetch",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.4",
|
|
4
4
|
"description": "A JavaScript/TypeScript API client for Heroku APIs",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -63,13 +63,13 @@
|
|
|
63
63
|
"@oclif/core": "^4.10.5",
|
|
64
64
|
"@types/debug": "^4.1.12",
|
|
65
65
|
"@types/node": "^26.5.0",
|
|
66
|
-
"@vitest/coverage-v8": "^
|
|
66
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
67
67
|
"eslint": "^9.39.4",
|
|
68
68
|
"eslint-config-oclif": "^6.0.152",
|
|
69
69
|
"rimraf": "^6.1.3",
|
|
70
70
|
"tsx": "^4.7.1",
|
|
71
71
|
"typescript": "^5.3.3",
|
|
72
|
-
"vitest": "^
|
|
72
|
+
"vitest": "^5.0.5"
|
|
73
73
|
},
|
|
74
74
|
"engines": {
|
|
75
75
|
"node": ">=22"
|