@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/index.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
export { getApiHost, getApiUrl, getAuthToken, getAuthTokenProvider, } from './auth/auth.js';
|
|
2
|
-
export { Login } from './cli/cli-login.js';
|
|
3
1
|
export { cliTwoFactorPrompt, createCliTwoFactorPrompt, } from './cli/cli-two-factor-prompt.js';
|
|
4
2
|
export { HerokuApiClient } from './client/index.js';
|
|
5
3
|
export { AuthenticationError, HerokuApiError, NotFoundError, RateLimitError, TwoFactorRequiredError, } from './errors.js';
|
|
6
|
-
export
|
|
4
|
+
export { getApiHost, getApiUrl, } from './host.js';
|
|
5
|
+
export type * from './public-types.js';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
export { getApiHost, getApiUrl, getAuthToken, getAuthTokenProvider, } from './auth/auth.js';
|
|
2
|
-
export { Login } from './cli/cli-login.js';
|
|
3
1
|
export { cliTwoFactorPrompt, createCliTwoFactorPrompt, } from './cli/cli-two-factor-prompt.js';
|
|
4
2
|
export { HerokuApiClient } from './client/index.js';
|
|
5
3
|
export { AuthenticationError, HerokuApiError, NotFoundError, RateLimitError, TwoFactorRequiredError, } from './errors.js';
|
|
4
|
+
export { getApiHost, getApiUrl, } from './host.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The package's public type surface, in one place so the Node (`index.ts`) and
|
|
3
|
+
* browser (`browser.ts`) entry points export an identical set and can't drift.
|
|
4
|
+
* Types only — runtime values (the client class, errors, helpers) are exported
|
|
5
|
+
* directly from each entry point, which differ by environment.
|
|
6
|
+
*/
|
|
7
|
+
export type { FetchLike, HerokuAfterResponseHook, HerokuApiClientOptions, HerokuBeforeRequestHook, HerokuError, HerokuErrorResponse, HerokuHooks, HerokuService, RequestOptions, ResponseMetadata, ServiceConfig, TokenProvider, TwoFactorOptions, } from './types.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The package's public type surface, in one place so the Node (`index.ts`) and
|
|
3
|
+
* browser (`browser.ts`) entry points export an identical set and can't drift.
|
|
4
|
+
* Types only — runtime values (the client class, errors, helpers) are exported
|
|
5
|
+
* directly from each entry point, which differ by environment.
|
|
6
|
+
*/
|
|
7
|
+
export {};
|
package/dist/redact.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lazy, fail-closed secret scrubbing for DEBUG-gated log output.
|
|
3
|
+
*
|
|
4
|
+
* Wraps `@heroku/js-blanket`, loaded via dynamic `import()` the first time a
|
|
5
|
+
* debug namespace is enabled so it stays off the default code path.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Scrub a value for debug logging. Handles `Error`, `Headers`, plain objects,
|
|
9
|
+
* and primitives (passed through unchanged — a top-level string is not
|
|
10
|
+
* pattern-scrubbed; `VALUE_PATTERNS` only apply to strings nested inside a
|
|
11
|
+
* scrubbed object/Error). Fail-closed: any failure returns `'[unscrubbable]'`
|
|
12
|
+
* rather than risking the raw value. `depth` is internal, for `cause`
|
|
13
|
+
* recursion.
|
|
14
|
+
*/
|
|
15
|
+
export declare function scrubForLog(value: unknown, depth?: number): Promise<unknown>;
|
|
16
|
+
/** A `debug` logger: a format call plus an `enabled` flag for its namespace. */
|
|
17
|
+
export interface DebugLike {
|
|
18
|
+
(formatter: string, ...args: unknown[]): void;
|
|
19
|
+
readonly enabled: boolean;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Scrub each `value` and emit it through `logger` under `formatter`. No-ops
|
|
23
|
+
* when the namespace is disabled. Use this instead of passing raw objects to a
|
|
24
|
+
* `debug` logger with `%O`/`%o` (enforced by lint).
|
|
25
|
+
*/
|
|
26
|
+
export declare function logScrubbed(logger: DebugLike, formatter: string, ...values: unknown[]): Promise<void>;
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lazy, fail-closed secret scrubbing for DEBUG-gated log output.
|
|
3
|
+
*
|
|
4
|
+
* Wraps `@heroku/js-blanket`, loaded via dynamic `import()` the first time a
|
|
5
|
+
* debug namespace is enabled so it stays off the default code path.
|
|
6
|
+
*/
|
|
7
|
+
/** Replacement token for redacted values. */
|
|
8
|
+
const REPLACEMENT = '[REDACTED]';
|
|
9
|
+
/**
|
|
10
|
+
* Extra sensitive keys the preset doesn't cover, matched case-insensitively as
|
|
11
|
+
* substrings. `code` is deliberately excluded so it doesn't also redact
|
|
12
|
+
* `statusCode`/`errorCode` in logged error objects.
|
|
13
|
+
*/
|
|
14
|
+
const EXTRA_FIELDS = [
|
|
15
|
+
'secondfactor',
|
|
16
|
+
'second_factor',
|
|
17
|
+
'otp',
|
|
18
|
+
'sso',
|
|
19
|
+
];
|
|
20
|
+
/**
|
|
21
|
+
* Redact inline `Bearer`/`Basic` credentials in string leaf values reached
|
|
22
|
+
* while scrubbing an object or Error (e.g. an error message). Bare UUIDs/JWTs
|
|
23
|
+
* are intentionally not matched — they're indistinguishable from benign
|
|
24
|
+
* resource IDs. Note these patterns don't apply to a top-level string passed
|
|
25
|
+
* straight to `scrubForLog`.
|
|
26
|
+
*/
|
|
27
|
+
const VALUE_PATTERNS = [
|
|
28
|
+
/\b(?:Bearer|Basic)\s+[\w.~+/=-]+/gi,
|
|
29
|
+
];
|
|
30
|
+
/** Cap on `error.cause` recursion depth; guards against cyclic chains. */
|
|
31
|
+
const MAX_CAUSE_DEPTH = 8;
|
|
32
|
+
let scrubberPromise;
|
|
33
|
+
/** Build the shared Scrubber once, importing js-blanket lazily. */
|
|
34
|
+
async function getScrubber() {
|
|
35
|
+
if (!scrubberPromise) {
|
|
36
|
+
scrubberPromise = (async () => {
|
|
37
|
+
const [{ Scrubber }, { HEROKU_FIELDS }] = await Promise.all([
|
|
38
|
+
import('@heroku/js-blanket/core/scrubber'),
|
|
39
|
+
import('@heroku/js-blanket/core/presets'),
|
|
40
|
+
]);
|
|
41
|
+
return new Scrubber({
|
|
42
|
+
fields: [...HEROKU_FIELDS, ...EXTRA_FIELDS],
|
|
43
|
+
patterns: [...VALUE_PATTERNS],
|
|
44
|
+
replacement: REPLACEMENT,
|
|
45
|
+
});
|
|
46
|
+
})();
|
|
47
|
+
// Don't cache a rejected import: clear it so a later call retries rather
|
|
48
|
+
// than degrading all object logging to '[unscrubbable]' for the process.
|
|
49
|
+
scrubberPromise.catch(() => {
|
|
50
|
+
scrubberPromise = undefined;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return scrubberPromise;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Convert a `Headers` instance to a plain object. Scrubbing one directly yields
|
|
57
|
+
* `{}` (no enumerable own-properties); converting first preserves the entries.
|
|
58
|
+
*/
|
|
59
|
+
function headersToObject(headers) {
|
|
60
|
+
const out = {};
|
|
61
|
+
// eslint-disable-next-line unicorn/no-array-for-each
|
|
62
|
+
headers.forEach((value, key) => {
|
|
63
|
+
out[key] = value;
|
|
64
|
+
});
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Clear credentials embedded in a URL (userinfo and sensitive query values),
|
|
69
|
+
* keeping host/path. Returns the input unchanged if it isn't a parseable URL.
|
|
70
|
+
*/
|
|
71
|
+
function redactUrl(url) {
|
|
72
|
+
if (typeof url !== 'string')
|
|
73
|
+
return url;
|
|
74
|
+
try {
|
|
75
|
+
const u = new URL(url);
|
|
76
|
+
if (u.username)
|
|
77
|
+
u.username = REPLACEMENT;
|
|
78
|
+
if (u.password)
|
|
79
|
+
u.password = REPLACEMENT;
|
|
80
|
+
for (const key of u.searchParams.keys()) {
|
|
81
|
+
if (/token|secret|code|sso|key|password|auth|assertion|saml|signature|nonce|otp|credential/i.test(key)) {
|
|
82
|
+
u.searchParams.set(key, REPLACEMENT);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return u.toString();
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return url;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Normalize an `Error` into a plain, scrubbable object. An Error's own
|
|
93
|
+
* `name`/`message`/`stack`/`cause` are non-enumerable and would otherwise be
|
|
94
|
+
* dropped. Nested `Request`/`Response` are summarized rather than passed
|
|
95
|
+
* through: they serialize to `{}` and a `Request` can carry live auth headers.
|
|
96
|
+
*/
|
|
97
|
+
async function scrubError(error, depth) {
|
|
98
|
+
const scrubber = await getScrubber();
|
|
99
|
+
// Index signature makes the extra own-properties `unknown` without flattening
|
|
100
|
+
// the known `message`/`name`/`stack` off `Error` (string wins over unknown).
|
|
101
|
+
const err = error;
|
|
102
|
+
const { cause, message, name, request, response, stack, ...rest } = err;
|
|
103
|
+
const normalized = {
|
|
104
|
+
message, name, stack, ...rest,
|
|
105
|
+
};
|
|
106
|
+
if (response && typeof response === 'object') {
|
|
107
|
+
const r = response;
|
|
108
|
+
normalized.response = { status: r.status, statusText: r.statusText, url: redactUrl(r.url) };
|
|
109
|
+
}
|
|
110
|
+
if (request && typeof request === 'object') {
|
|
111
|
+
const r = request;
|
|
112
|
+
normalized.request = { method: r.method, url: redactUrl(r.url) };
|
|
113
|
+
}
|
|
114
|
+
const scrubbed = scrubber.scrub(normalized).data;
|
|
115
|
+
if (cause !== undefined) {
|
|
116
|
+
scrubbed.cause = depth >= MAX_CAUSE_DEPTH
|
|
117
|
+
? '[max cause depth exceeded]'
|
|
118
|
+
: await scrubForLog(cause, depth + 1);
|
|
119
|
+
}
|
|
120
|
+
return scrubbed;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Scrub a value for debug logging. Handles `Error`, `Headers`, plain objects,
|
|
124
|
+
* and primitives (passed through unchanged — a top-level string is not
|
|
125
|
+
* pattern-scrubbed; `VALUE_PATTERNS` only apply to strings nested inside a
|
|
126
|
+
* scrubbed object/Error). Fail-closed: any failure returns `'[unscrubbable]'`
|
|
127
|
+
* rather than risking the raw value. `depth` is internal, for `cause`
|
|
128
|
+
* recursion.
|
|
129
|
+
*/
|
|
130
|
+
export async function scrubForLog(value, depth = 0) {
|
|
131
|
+
try {
|
|
132
|
+
if (value instanceof Error)
|
|
133
|
+
return await scrubError(value, depth);
|
|
134
|
+
if (typeof Headers !== 'undefined' && value instanceof Headers) {
|
|
135
|
+
const scrubber = await getScrubber();
|
|
136
|
+
return scrubber.scrub(headersToObject(value)).data;
|
|
137
|
+
}
|
|
138
|
+
if (value !== null && typeof value === 'object') {
|
|
139
|
+
const scrubber = await getScrubber();
|
|
140
|
+
return scrubber.scrub(value).data;
|
|
141
|
+
}
|
|
142
|
+
return value;
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return '[unscrubbable]';
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Scrub each `value` and emit it through `logger` under `formatter`. No-ops
|
|
150
|
+
* when the namespace is disabled. Use this instead of passing raw objects to a
|
|
151
|
+
* `debug` logger with `%O`/`%o` (enforced by lint).
|
|
152
|
+
*/
|
|
153
|
+
export async function logScrubbed(logger, formatter, ...values) {
|
|
154
|
+
if (!logger.enabled)
|
|
155
|
+
return;
|
|
156
|
+
const scrubbed = await Promise.all(values.map(value => scrubForLog(value)));
|
|
157
|
+
logger(formatter, ...scrubbed);
|
|
158
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,5 +1,85 @@
|
|
|
1
1
|
export type HerokuService = 'custom' | 'data' | 'particleboard' | 'platform';
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* A `beforeRequest` hook: runs after the client's built-ins have prepared the
|
|
4
|
+
* `Request` and may inspect or mutate it, or return a replacement `Request`/
|
|
5
|
+
* `Response`. Structurally a subset of the underlying ky hook, but typed only
|
|
6
|
+
* on the standard `Request`/`Response` so the public API isn't welded to ky's
|
|
7
|
+
* major version — a ky upgrade that reshapes its own hook types can't become a
|
|
8
|
+
* breaking change here.
|
|
9
|
+
*/
|
|
10
|
+
export type HerokuBeforeRequestHook = (context: {
|
|
11
|
+
request: Request;
|
|
12
|
+
}) => Promise<Request | Response | void> | Request | Response | void;
|
|
13
|
+
/**
|
|
14
|
+
* An `afterResponse` hook: runs on the resolved success-path response (the
|
|
15
|
+
* built-in error hook throws on a non-2xx first) and may return a replacement
|
|
16
|
+
* `Response`. Typed only on the standard `Request`/`Response`, for the same
|
|
17
|
+
* decoupling reason as {@link HerokuBeforeRequestHook}.
|
|
18
|
+
*/
|
|
19
|
+
export type HerokuAfterResponseHook = (context: {
|
|
20
|
+
request: Request;
|
|
21
|
+
response: Response;
|
|
22
|
+
}) => Promise<Response | void> | Response | void;
|
|
23
|
+
/**
|
|
24
|
+
* Consumer-supplied ky hooks, merged with the client's built-in pipeline.
|
|
25
|
+
*
|
|
26
|
+
* Built-in hooks run first in each phase; the hooks here run after them:
|
|
27
|
+
* - `beforeRequest`: the built-ins attach auth, the `Accept` default, and the
|
|
28
|
+
* `Request-Id` header; your hooks then see (and may override) the fully
|
|
29
|
+
* prepared request before it goes out.
|
|
30
|
+
* - `afterResponse`: the built-ins handle 2FA, throw typed errors on non-2xx,
|
|
31
|
+
* track `Request-Id`s, and surface warnings. Your hooks run *after* that, so
|
|
32
|
+
* they only see the resolved success-path response — a non-2xx response has
|
|
33
|
+
* already been thrown as a typed error and never reaches them.
|
|
34
|
+
*
|
|
35
|
+
* Resolved once at construction: the ky instance is built lazily and cached,
|
|
36
|
+
* so hooks cannot be changed per request.
|
|
37
|
+
*/
|
|
38
|
+
export interface HerokuHooks {
|
|
39
|
+
afterResponse?: readonly HerokuAfterResponseHook[];
|
|
40
|
+
beforeRequest?: readonly HerokuBeforeRequestHook[];
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A `fetch`-shaped function. Returned by `getDefaultFetch()` on the
|
|
44
|
+
* `@heroku/heroku-fetch/client/environment-defaults.js` subpath: a drop-in
|
|
45
|
+
* `fetch` that, on Node, is already paired with the proxy dispatcher from the
|
|
46
|
+
* same undici copy, so proxy routing works. Pass it anywhere a `fetch` is
|
|
47
|
+
* accepted. See `getDefaultFetch` for why the pairing matters.
|
|
48
|
+
*/
|
|
49
|
+
export type FetchLike = (input: Request | string | URL, init?: Parameters<typeof fetch>[1]) => Promise<Response>;
|
|
50
|
+
/**
|
|
51
|
+
* A bearer token, or a function resolving one at request time. A provider may
|
|
52
|
+
* return `undefined` (sync or async) to send the request with no `Authorization`
|
|
53
|
+
* header — appropriate for endpoints or hosts that need no Heroku auth. Requests
|
|
54
|
+
* to endpoints that do require auth then receive a server 401, surfaced as
|
|
55
|
+
* `AuthenticationError`.
|
|
56
|
+
*/
|
|
57
|
+
export type TokenProvider = (() => Promise<string | undefined> | string | undefined) | string;
|
|
58
|
+
/**
|
|
59
|
+
* Structured, success-path metadata about a completed response, surfaced via
|
|
60
|
+
* the `onResponseMetadata` option so consumers can read request correlation and
|
|
61
|
+
* warnings without re-parsing headers. The bare `Response` is still returned
|
|
62
|
+
* from `get`/`post`/etc. unchanged — this is an additive side channel.
|
|
63
|
+
*/
|
|
64
|
+
export interface ResponseMetadata {
|
|
65
|
+
/**
|
|
66
|
+
* The `Request-Id`s the server echoed for this response, newest first. The
|
|
67
|
+
* server returns them comma-joined; this is that header split into the
|
|
68
|
+
* individual ids (matching the client's internal correlation tracking).
|
|
69
|
+
* Empty when the response carried no `Request-Id`.
|
|
70
|
+
*/
|
|
71
|
+
requestIds: readonly string[];
|
|
72
|
+
/** HTTP status code of the response. */
|
|
73
|
+
status: number;
|
|
74
|
+
/** Final request URL. */
|
|
75
|
+
url: string;
|
|
76
|
+
/**
|
|
77
|
+
* Warnings this response carried (normalized the same way the `warn`
|
|
78
|
+
* callback receives them). Empty when the response carried none. Not deduped
|
|
79
|
+
* against prior responses — reflects what *this* response carried.
|
|
80
|
+
*/
|
|
81
|
+
warnings: readonly string[];
|
|
82
|
+
}
|
|
3
83
|
export interface TwoFactorOptions {
|
|
4
84
|
/** Callback function to prompt for 2FA code */
|
|
5
85
|
onChallenge: () => Promise<string> | string;
|
|
@@ -34,6 +114,22 @@ export interface HerokuApiClientOptions {
|
|
|
34
114
|
defaultAccept?: string;
|
|
35
115
|
/** Additional custom headers */
|
|
36
116
|
headers?: Record<string, string>;
|
|
117
|
+
/**
|
|
118
|
+
* Consumer ky hooks merged after the client's built-in hooks. See
|
|
119
|
+
* {@link HerokuHooks} for ordering and the success-path caveat.
|
|
120
|
+
*/
|
|
121
|
+
hooks?: HerokuHooks;
|
|
122
|
+
/**
|
|
123
|
+
* Callback invoked on the success path with structured {@link ResponseMetadata}
|
|
124
|
+
* for each completed response — request-ids and warnings without re-parsing
|
|
125
|
+
* headers. Runs only after built-in error handling accepts the response (a
|
|
126
|
+
* non-2xx is thrown as a typed error and never reaches it). Omitted → no-op.
|
|
127
|
+
*
|
|
128
|
+
* Fires once per HTTP response, not once per logical operation: a caller that
|
|
129
|
+
* makes several requests (pagination, polling) receives several callbacks,
|
|
130
|
+
* with no built-in way to correlate them beyond the per-response metadata.
|
|
131
|
+
*/
|
|
132
|
+
onResponseMetadata?: (metadata: ResponseMetadata) => void;
|
|
37
133
|
/** Service region (e.g., 'eu', 'us') */
|
|
38
134
|
region?: string;
|
|
39
135
|
/** Heroku service type (platform, data, particleboard, custom) */
|
|
@@ -44,6 +140,14 @@ export interface HerokuApiClientOptions {
|
|
|
44
140
|
token?: TokenProvider;
|
|
45
141
|
/** Two-factor authentication configuration */
|
|
46
142
|
twoFactor?: TwoFactorOptions;
|
|
143
|
+
/**
|
|
144
|
+
* Callback for surfacing user-facing warnings the client raises — currently
|
|
145
|
+
* server `x-heroku-warning` / `warning-message` response headers. Called once
|
|
146
|
+
* per unique (normalized) warning over the client's lifetime. Keeps the
|
|
147
|
+
* client environment-agnostic: a host can log or display warnings however it
|
|
148
|
+
* likes. Omitted → warnings are dropped.
|
|
149
|
+
*/
|
|
150
|
+
warn?: (message: string) => void;
|
|
47
151
|
}
|
|
48
152
|
export interface RequestOptions {
|
|
49
153
|
/** Additional headers for this request */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@heroku/heroku-fetch",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "A JavaScript/TypeScript API client for Heroku APIs",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -50,14 +50,13 @@
|
|
|
50
50
|
},
|
|
51
51
|
"homepage": "https://github.com/heroku/heroku-fetch#readme",
|
|
52
52
|
"dependencies": {
|
|
53
|
+
"@heroku/js-blanket": "^1.2.0",
|
|
53
54
|
"debug": "^4.3.4",
|
|
54
|
-
"ky": "^2.0
|
|
55
|
+
"ky": "^2.2.0",
|
|
55
56
|
"undici": "^8.11.2"
|
|
56
57
|
},
|
|
57
58
|
"optionalDependencies": {
|
|
58
|
-
"@heroku/heroku-cli-util": "^10.8.0"
|
|
59
|
-
"netrc-parser": "^3.1.6",
|
|
60
|
-
"open": "^11.0.0"
|
|
59
|
+
"@heroku/heroku-cli-util": "^10.8.0"
|
|
61
60
|
},
|
|
62
61
|
"devDependencies": {
|
|
63
62
|
"@heroku-cli/test-utils": "^1.0.1",
|
package/dist/auth/auth.d.ts
DELETED
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Authentication utilities for Heroku API
|
|
3
|
-
* Handles token retrieval from environment variables and netrc file
|
|
4
|
-
*/
|
|
5
|
-
/**
|
|
6
|
-
* Get the Heroku API token from environment variable or netrc file
|
|
7
|
-
*
|
|
8
|
-
* Priority:
|
|
9
|
-
* 1. HEROKU_API_KEY environment variable
|
|
10
|
-
* 2. ~/.netrc file (uses api.heroku.com or HEROKU_HOST if set)
|
|
11
|
-
*
|
|
12
|
-
* @returns The API token or undefined if not found
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* ```typescript
|
|
16
|
-
* import { getAuthToken, HerokuApiClient } from '@heroku/heroku-fetch';
|
|
17
|
-
*
|
|
18
|
-
* const token = getAuthToken();
|
|
19
|
-
* const client = new HerokuApiClient({
|
|
20
|
-
* service: 'platform',
|
|
21
|
-
* token,
|
|
22
|
-
* });
|
|
23
|
-
* ```
|
|
24
|
-
*/
|
|
25
|
-
export declare function getAuthToken(): string | undefined;
|
|
26
|
-
/**
|
|
27
|
-
* Get the API host from environment or default
|
|
28
|
-
*
|
|
29
|
-
* @returns The API host (default: 'api.heroku.com')
|
|
30
|
-
*
|
|
31
|
-
* @example
|
|
32
|
-
* ```typescript
|
|
33
|
-
* const host = getApiHost();
|
|
34
|
-
* // Returns 'api.heroku.com' or value of HEROKU_HOST env var
|
|
35
|
-
* ```
|
|
36
|
-
*/
|
|
37
|
-
export declare function getApiHost(): string;
|
|
38
|
-
/**
|
|
39
|
-
* Get the full API URL from environment or default
|
|
40
|
-
*
|
|
41
|
-
* @returns The API URL (default: 'https://api.heroku.com')
|
|
42
|
-
*
|
|
43
|
-
* @example
|
|
44
|
-
* ```typescript
|
|
45
|
-
* const url = getApiUrl();
|
|
46
|
-
* // Returns 'https://api.heroku.com' or https://{HEROKU_HOST}
|
|
47
|
-
* ```
|
|
48
|
-
*/
|
|
49
|
-
export declare function getApiUrl(): string;
|
|
50
|
-
/**
|
|
51
|
-
* Create a token provider function for use with HerokuApiClient
|
|
52
|
-
* This is useful when you want the token to be fetched dynamically
|
|
53
|
-
*
|
|
54
|
-
* @returns A function that returns the current auth token
|
|
55
|
-
*
|
|
56
|
-
* @example
|
|
57
|
-
* ```typescript
|
|
58
|
-
* import { getAuthTokenProvider, HerokuApiClient } from '@heroku/heroku-fetch';
|
|
59
|
-
*
|
|
60
|
-
* const client = new HerokuApiClient({
|
|
61
|
-
* service: 'platform',
|
|
62
|
-
* token: getAuthTokenProvider(),
|
|
63
|
-
* });
|
|
64
|
-
* ```
|
|
65
|
-
*/
|
|
66
|
-
export declare function getAuthTokenProvider(): () => string | undefined;
|
package/dist/auth/auth.js
DELETED
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Authentication utilities for Heroku API
|
|
3
|
-
* Handles token retrieval from environment variables and netrc file
|
|
4
|
-
*/
|
|
5
|
-
import { Netrc } from 'netrc-parser';
|
|
6
|
-
// Defer netrc instantiation to avoid eager .netrc file operations at module load time
|
|
7
|
-
let _netrc;
|
|
8
|
-
function getNetrc() {
|
|
9
|
-
if (!_netrc) {
|
|
10
|
-
_netrc = new Netrc();
|
|
11
|
-
}
|
|
12
|
-
return _netrc;
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* Get the Heroku API token from environment variable or netrc file
|
|
16
|
-
*
|
|
17
|
-
* Priority:
|
|
18
|
-
* 1. HEROKU_API_KEY environment variable
|
|
19
|
-
* 2. ~/.netrc file (uses api.heroku.com or HEROKU_HOST if set)
|
|
20
|
-
*
|
|
21
|
-
* @returns The API token or undefined if not found
|
|
22
|
-
*
|
|
23
|
-
* @example
|
|
24
|
-
* ```typescript
|
|
25
|
-
* import { getAuthToken, HerokuApiClient } from '@heroku/heroku-fetch';
|
|
26
|
-
*
|
|
27
|
-
* const token = getAuthToken();
|
|
28
|
-
* const client = new HerokuApiClient({
|
|
29
|
-
* service: 'platform',
|
|
30
|
-
* token,
|
|
31
|
-
* });
|
|
32
|
-
* ```
|
|
33
|
-
*/
|
|
34
|
-
export function getAuthToken() {
|
|
35
|
-
// Check environment variable first
|
|
36
|
-
let token = process.env.HEROKU_API_KEY;
|
|
37
|
-
if (!token) {
|
|
38
|
-
// Fall back to netrc
|
|
39
|
-
const netrc = getNetrc();
|
|
40
|
-
netrc.loadSync();
|
|
41
|
-
const apiHost = getApiHost();
|
|
42
|
-
token = netrc.machines[apiHost]?.password;
|
|
43
|
-
}
|
|
44
|
-
return token;
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Get the API host from environment or default
|
|
48
|
-
*
|
|
49
|
-
* @returns The API host (default: 'api.heroku.com')
|
|
50
|
-
*
|
|
51
|
-
* @example
|
|
52
|
-
* ```typescript
|
|
53
|
-
* const host = getApiHost();
|
|
54
|
-
* // Returns 'api.heroku.com' or value of HEROKU_HOST env var
|
|
55
|
-
* ```
|
|
56
|
-
*/
|
|
57
|
-
export function getApiHost() {
|
|
58
|
-
return process.env.HEROKU_HOST || 'api.heroku.com';
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Get the full API URL from environment or default
|
|
62
|
-
*
|
|
63
|
-
* @returns The API URL (default: 'https://api.heroku.com')
|
|
64
|
-
*
|
|
65
|
-
* @example
|
|
66
|
-
* ```typescript
|
|
67
|
-
* const url = getApiUrl();
|
|
68
|
-
* // Returns 'https://api.heroku.com' or https://{HEROKU_HOST}
|
|
69
|
-
* ```
|
|
70
|
-
*/
|
|
71
|
-
export function getApiUrl() {
|
|
72
|
-
const host = getApiHost();
|
|
73
|
-
return `https://${host}`;
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* Create a token provider function for use with HerokuApiClient
|
|
77
|
-
* This is useful when you want the token to be fetched dynamically
|
|
78
|
-
*
|
|
79
|
-
* @returns A function that returns the current auth token
|
|
80
|
-
*
|
|
81
|
-
* @example
|
|
82
|
-
* ```typescript
|
|
83
|
-
* import { getAuthTokenProvider, HerokuApiClient } from '@heroku/heroku-fetch';
|
|
84
|
-
*
|
|
85
|
-
* const client = new HerokuApiClient({
|
|
86
|
-
* service: 'platform',
|
|
87
|
-
* token: getAuthTokenProvider(),
|
|
88
|
-
* });
|
|
89
|
-
* ```
|
|
90
|
-
*/
|
|
91
|
-
export function getAuthTokenProvider() {
|
|
92
|
-
return () => getAuthToken();
|
|
93
|
-
}
|
package/dist/cli/cli-login.d.ts
DELETED
package/dist/cli/cli-login.js
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Browser-based OAuth login flow
|
|
3
|
-
*/
|
|
4
|
-
import os from 'node:os';
|
|
5
|
-
import { debugCliLogin } from '../../debug-loggers.js';
|
|
6
|
-
import { headers } from './types.js';
|
|
7
|
-
const hostname = os.hostname();
|
|
8
|
-
/**
|
|
9
|
-
* Show the manual browser login URL to the user
|
|
10
|
-
*/
|
|
11
|
-
function showManualBrowserLoginUrl(url) {
|
|
12
|
-
console.warn('If browser does not open, visit:');
|
|
13
|
-
console.error(`\u001B[32m${url}\u001B[0m`); // Green color
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Poll the auth server for the access token with retry logic
|
|
17
|
-
*/
|
|
18
|
-
async function fetchAuth(loginHost, cliUrl, token, retries = 3) {
|
|
19
|
-
try {
|
|
20
|
-
debugCliLogin('Polling auth server: %s%s (retries left: %d)', loginHost, cliUrl, retries);
|
|
21
|
-
const response = await fetch(`${loginHost}${cliUrl}`, {
|
|
22
|
-
headers: { Authorization: `Bearer ${token}` },
|
|
23
|
-
});
|
|
24
|
-
if (!response.ok && retries > 0 && response.status >= 500) {
|
|
25
|
-
debugCliLogin('Auth server returned %d, retrying...', response.status);
|
|
26
|
-
return fetchAuth(loginHost, cliUrl, token, retries - 1);
|
|
27
|
-
}
|
|
28
|
-
if (!response.ok) {
|
|
29
|
-
debugCliLogin('Auth polling failed with status: %d', response.status);
|
|
30
|
-
throw new Error(`Login failed: ${response.statusText}`);
|
|
31
|
-
}
|
|
32
|
-
debugCliLogin('Access token received from auth server');
|
|
33
|
-
return (await response.json());
|
|
34
|
-
}
|
|
35
|
-
catch (error) {
|
|
36
|
-
if (retries > 0
|
|
37
|
-
&& error instanceof Error
|
|
38
|
-
&& error.message.includes('500')) {
|
|
39
|
-
debugCliLogin('Caught 500 error, retrying...');
|
|
40
|
-
return fetchAuth(loginHost, cliUrl, token, retries - 1);
|
|
41
|
-
}
|
|
42
|
-
debugCliLogin('Auth polling failed: %O', error);
|
|
43
|
-
throw error;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Perform browser-based OAuth login
|
|
48
|
-
*/
|
|
49
|
-
export async function browserLogin(config, browser) {
|
|
50
|
-
debugCliLogin('Starting browser login flow');
|
|
51
|
-
debugCliLogin('Creating auth session at %s/auth', config.loginHost);
|
|
52
|
-
// Create auth session
|
|
53
|
-
const response = await fetch(`${config.loginHost}/auth`, {
|
|
54
|
-
body: JSON.stringify({
|
|
55
|
-
description: `Heroku CLI login from ${hostname}`,
|
|
56
|
-
}),
|
|
57
|
-
headers: { 'Content-Type': 'application/json' },
|
|
58
|
-
method: 'POST',
|
|
59
|
-
});
|
|
60
|
-
if (!response.ok) {
|
|
61
|
-
debugCliLogin('Failed to create auth session: %d %s', response.status, response.statusText);
|
|
62
|
-
throw new Error(`Failed to initiate browser login: ${response.statusText}`);
|
|
63
|
-
}
|
|
64
|
-
const urls = (await response.json());
|
|
65
|
-
const url = `${config.loginHost}${urls.browser_url}`;
|
|
66
|
-
debugCliLogin('Auth session created, browser URL: %s', url);
|
|
67
|
-
console.error(`Opening browser to ${url}\n`);
|
|
68
|
-
let urlDisplayed = false;
|
|
69
|
-
const showUrl = () => {
|
|
70
|
-
if (!urlDisplayed)
|
|
71
|
-
console.warn('Cannot open browser.');
|
|
72
|
-
urlDisplayed = true;
|
|
73
|
-
};
|
|
74
|
-
showManualBrowserLoginUrl(url);
|
|
75
|
-
const open = (await import('open')).default;
|
|
76
|
-
debugCliLogin('Opening browser with %s', browser ? `browser: ${browser}` : 'default browser');
|
|
77
|
-
const cp = await open(url, {
|
|
78
|
-
wait: false,
|
|
79
|
-
...(browser ? { app: { name: browser } } : {}),
|
|
80
|
-
});
|
|
81
|
-
cp.on('error', err => {
|
|
82
|
-
debugCliLogin('Browser open error: %O', err);
|
|
83
|
-
console.warn(err);
|
|
84
|
-
showUrl();
|
|
85
|
-
});
|
|
86
|
-
if (process.env.HEROKU_TESTING_HEADLESS_LOGIN === '1')
|
|
87
|
-
showUrl();
|
|
88
|
-
cp.on('close', code => {
|
|
89
|
-
if (code !== 0) {
|
|
90
|
-
debugCliLogin('Browser process exited with non-zero code: %d', code);
|
|
91
|
-
showUrl();
|
|
92
|
-
}
|
|
93
|
-
});
|
|
94
|
-
console.error('heroku: Waiting for login...');
|
|
95
|
-
const auth = await fetchAuth(config.loginHost, urls.cli_url, urls.token);
|
|
96
|
-
if (auth.error) {
|
|
97
|
-
debugCliLogin('Auth response contained error: %s', auth.error);
|
|
98
|
-
throw new Error(auth.error);
|
|
99
|
-
}
|
|
100
|
-
console.error('Logging in...');
|
|
101
|
-
debugCliLogin('Fetching account information from %s/account', config.apiUrl);
|
|
102
|
-
const accountResponse = await fetch(`${config.apiUrl}/account`, {
|
|
103
|
-
headers: headers(auth.access_token),
|
|
104
|
-
});
|
|
105
|
-
if (!accountResponse.ok) {
|
|
106
|
-
debugCliLogin('Failed to fetch account: %d %s', accountResponse.status, accountResponse.statusText);
|
|
107
|
-
throw new Error(`Failed to fetch account: ${accountResponse.statusText}`);
|
|
108
|
-
}
|
|
109
|
-
const account = (await accountResponse.json());
|
|
110
|
-
debugCliLogin('Browser login successful for user: %s', account.email);
|
|
111
|
-
return {
|
|
112
|
-
login: account.email,
|
|
113
|
-
password: auth.access_token,
|
|
114
|
-
};
|
|
115
|
-
}
|