@vltpkg/registry-client 1.0.10 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cache-entry.d.ts +11 -0
- package/dist/cache-entry.js +13 -0
- package/dist/cache-revalidate.d.ts +1 -1
- package/dist/cache-revalidate.js +4 -2
- package/dist/index.d.ts +3 -1
- package/dist/index.js +101 -11
- package/dist/otplease.js +18 -2
- package/dist/registry-error.d.ts +61 -0
- package/dist/registry-error.js +167 -0
- package/dist/revalidate-entry.d.ts +1 -1
- package/dist/revalidate-entry.js +5 -1
- package/dist/revalidate.js +16 -6
- package/package.json +14 -9
package/dist/cache-entry.d.ts
CHANGED
|
@@ -75,6 +75,17 @@ export declare class CacheEntry {
|
|
|
75
75
|
*/
|
|
76
76
|
get headSize(): number | undefined;
|
|
77
77
|
get statusCode(): number;
|
|
78
|
+
/**
|
|
79
|
+
* True when the registry answered with a 2xx.
|
|
80
|
+
*
|
|
81
|
+
* `RegistryClient.request()` resolves for every status, so this is how
|
|
82
|
+
* code holding a real CacheEntry asks "did it work?".
|
|
83
|
+
*
|
|
84
|
+
* Note this is the strict form. Use it only where a genuine CacheEntry
|
|
85
|
+
* is guaranteed; `assertOk` uses the loose range check because it is
|
|
86
|
+
* also handed duck-typed responses.
|
|
87
|
+
*/
|
|
88
|
+
get ok(): boolean;
|
|
78
89
|
get headers(): Uint8Array[];
|
|
79
90
|
/**
|
|
80
91
|
* Returns the body as a single Uint8Array, concatenating parts if needed.
|
package/dist/cache-entry.js
CHANGED
|
@@ -252,6 +252,19 @@ export class CacheEntry {
|
|
|
252
252
|
get statusCode() {
|
|
253
253
|
return this.#statusCode;
|
|
254
254
|
}
|
|
255
|
+
/**
|
|
256
|
+
* True when the registry answered with a 2xx.
|
|
257
|
+
*
|
|
258
|
+
* `RegistryClient.request()` resolves for every status, so this is how
|
|
259
|
+
* code holding a real CacheEntry asks "did it work?".
|
|
260
|
+
*
|
|
261
|
+
* Note this is the strict form. Use it only where a genuine CacheEntry
|
|
262
|
+
* is guaranteed; `assertOk` uses the loose range check because it is
|
|
263
|
+
* also handed duck-typed responses.
|
|
264
|
+
*/
|
|
265
|
+
get ok() {
|
|
266
|
+
return this.#statusCode >= 200 && this.#statusCode < 300;
|
|
267
|
+
}
|
|
255
268
|
get headers() {
|
|
256
269
|
return this.#headers;
|
|
257
270
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const register: (path: string, method: "HEAD" | "GET", url: string | URL) => void;
|
|
1
|
+
export declare const register: (path: string, method: "HEAD" | "GET", url: string | URL, accept?: string[] | string) => void;
|
package/dist/cache-revalidate.js
CHANGED
|
@@ -4,9 +4,11 @@ import { __CODE_SPLIT_SCRIPT_NAME } from "./revalidate.js";
|
|
|
4
4
|
const isDeno = globalThis.Deno != undefined;
|
|
5
5
|
let didProcessBeforeExitHook = false;
|
|
6
6
|
const registered = new Map();
|
|
7
|
-
export const register = (path, method, url) => {
|
|
7
|
+
export const register = (path, method, url, accept) => {
|
|
8
8
|
const r = registered.get(path) ?? new Set();
|
|
9
|
-
|
|
9
|
+
// `METHOD URL[ ACCEPT]`; a serialized URL never contains a space, so
|
|
10
|
+
// the child splits on the first two.
|
|
11
|
+
const key = `${method} ${url}${accept ? ` ${String(accept)}` : ''}`;
|
|
10
12
|
r.add(key);
|
|
11
13
|
registered.set(path, r);
|
|
12
14
|
if (!didProcessBeforeExitHook) {
|
package/dist/index.d.ts
CHANGED
|
@@ -6,11 +6,13 @@ import type { Token } from './auth.ts';
|
|
|
6
6
|
import { clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, registryBase, runtimeTokens, setRuntimeToken, setToken } from './auth.ts';
|
|
7
7
|
import type { JSONObj } from './cache-entry.ts';
|
|
8
8
|
import { CacheEntry } from './cache-entry.ts';
|
|
9
|
+
import { assertOk, registryErrorMessage, requestError } from './registry-error.ts';
|
|
10
|
+
import type { ErrorResponse } from './registry-error.ts';
|
|
9
11
|
import type { TokenResponse } from './token-response.ts';
|
|
10
12
|
import type { WebAuthChallenge } from './web-auth-challenge.ts';
|
|
11
13
|
import { oidc } from './oidc.ts';
|
|
12
14
|
import type { OidcOptions } from './oidc.ts';
|
|
13
|
-
export { CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, runtimeTokens, setRuntimeToken, setToken, type JSONObj, type OidcOptions, type Token, type TokenResponse, type WebAuthChallenge, };
|
|
15
|
+
export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, requestError, runtimeTokens, setRuntimeToken, setToken, type ErrorResponse, type JSONObj, type OidcOptions, type Token, type TokenResponse, type WebAuthChallenge, };
|
|
14
16
|
/** A response body read straight out of the cache file. */
|
|
15
17
|
export type CachedBody = {
|
|
16
18
|
/** the cache file it came from */
|
package/dist/index.js
CHANGED
|
@@ -18,10 +18,12 @@ import { clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToke
|
|
|
18
18
|
import { CacheEntry } from "./cache-entry.js";
|
|
19
19
|
import { register } from "./cache-revalidate.js";
|
|
20
20
|
import { bun, deno, node } from "./env.js";
|
|
21
|
+
import { getHeader } from "./get-header.js";
|
|
21
22
|
import { handleCacheHitResponse } from "./handle-304-response.js";
|
|
22
23
|
import { otplease } from "./otplease.js";
|
|
23
24
|
import { getDispatcher } from "./proxy.js";
|
|
24
25
|
import { isRedirect, redirect } from "./redirect.js";
|
|
26
|
+
import { assertOk, registryErrorMessage, requestError, } from "./registry-error.js";
|
|
25
27
|
import { setCacheHeaders } from "./set-cache-headers.js";
|
|
26
28
|
import { getTokenResponse } from "./token-response.js";
|
|
27
29
|
import { getWebAuthChallenge } from "./web-auth-challenge.js";
|
|
@@ -29,7 +31,7 @@ import { collectHeaders, readBody } from "./response.js";
|
|
|
29
31
|
import { oidc } from "./oidc.js";
|
|
30
32
|
// eslint-disable-next-line no-console
|
|
31
33
|
const log = (msg) => console.error(msg);
|
|
32
|
-
export { CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, runtimeTokens, setRuntimeToken, setToken, };
|
|
34
|
+
export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, requestError, runtimeTokens, setRuntimeToken, setToken, };
|
|
33
35
|
export const isCacheableMethod = (m) => m === 'GET' || m === 'HEAD';
|
|
34
36
|
export const cacheKey = (method, url) => `${method !== 'GET' ? method + ' ' : ''}${url}`;
|
|
35
37
|
const { version } = loadPackageJson(import.meta.filename, process.env.__VLT_INTERNAL_REGISTRY_CLIENT_PACKAGE_JSON);
|
|
@@ -124,7 +126,51 @@ export class RegistryClient {
|
|
|
124
126
|
*/
|
|
125
127
|
async scroll(url, options = {}, seek) {
|
|
126
128
|
const resp = await this.request(url, options);
|
|
127
|
-
const {
|
|
129
|
+
const { statusCode } = resp;
|
|
130
|
+
if (statusCode < 200 || statusCode >= 300) {
|
|
131
|
+
let detail;
|
|
132
|
+
try {
|
|
133
|
+
const body = resp.json();
|
|
134
|
+
if (body && typeof body === 'object' && 'error' in body) {
|
|
135
|
+
detail = body.error;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
// Registries and proxies can return plain text or HTML errors.
|
|
140
|
+
}
|
|
141
|
+
const status = STATUS_CODES[statusCode];
|
|
142
|
+
throw error(`Failed to fetch paginated results: ${statusCode}${status ? ` ${status}` : ''}${typeof detail === 'string' && detail ? `: ${detail}` : ''}`, { code: 'EREQUEST', status: statusCode, url: String(url) });
|
|
143
|
+
}
|
|
144
|
+
let body;
|
|
145
|
+
try {
|
|
146
|
+
body = resp.json();
|
|
147
|
+
}
|
|
148
|
+
catch (cause) {
|
|
149
|
+
throw error('Invalid JSON in paginated registry response', {
|
|
150
|
+
code: 'EREQUEST',
|
|
151
|
+
url: String(url),
|
|
152
|
+
cause,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
if (!body ||
|
|
156
|
+
typeof body !== 'object' ||
|
|
157
|
+
!('objects' in body) ||
|
|
158
|
+
!Array.isArray(body.objects) ||
|
|
159
|
+
!('urls' in body) ||
|
|
160
|
+
!body.urls ||
|
|
161
|
+
typeof body.urls !== 'object' ||
|
|
162
|
+
Array.isArray(body.urls) ||
|
|
163
|
+
('next' in body.urls &&
|
|
164
|
+
body.urls.next !== null &&
|
|
165
|
+
body.urls.next !== undefined &&
|
|
166
|
+
typeof body.urls.next !== 'string')) {
|
|
167
|
+
throw error('Invalid pagination in registry response', {
|
|
168
|
+
code: 'EREQUEST',
|
|
169
|
+
url: String(url),
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
const objects = body.objects;
|
|
173
|
+
const urls = body.urls;
|
|
128
174
|
// if we have more, and haven't found our target, fetch more
|
|
129
175
|
return urls.next && !(seek && objects.some(seek)) ?
|
|
130
176
|
objects.concat(await this.scroll(urls.next, options, seek))
|
|
@@ -148,14 +194,47 @@ export class RegistryClient {
|
|
|
148
194
|
const s = tok.replace(/^(Bearer|Basic) /i, '');
|
|
149
195
|
const base = registryBase(registry);
|
|
150
196
|
const tokensUrl = new URL('-/npm/v1/tokens', base);
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
197
|
+
// Logging out must always drop the local credential -- a registry
|
|
198
|
+
// that will not talk to us cannot be allowed to strand a token on
|
|
199
|
+
// disk. But a token that outlives `vlt logout` server-side is
|
|
200
|
+
// security-relevant, so a failure is said out loud rather than
|
|
201
|
+
// swallowed.
|
|
202
|
+
const stillLive = `Removing the local credential anyway; revoke the token in the ` +
|
|
203
|
+
`registry UI if it is still live.`;
|
|
204
|
+
// the `finally` is the guarantee: `request()` rethrows a transport
|
|
205
|
+
// failure as EREQUEST, so without it a registry we cannot reach at
|
|
206
|
+
// all would take the local credential down with it.
|
|
207
|
+
try {
|
|
208
|
+
let record;
|
|
209
|
+
try {
|
|
210
|
+
record = await this.seek(tokensUrl, ({ token }) => s.startsWith(token), {
|
|
211
|
+
useCache: false,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
catch (er) {
|
|
215
|
+
log(`Could not list tokens at ${tokensUrl}: ${asError(er).message}\n` +
|
|
216
|
+
stillLive);
|
|
217
|
+
}
|
|
218
|
+
if (record) {
|
|
219
|
+
const deleteUrl = new URL(`-/npm/v1/tokens/token/${record.key}`, base);
|
|
220
|
+
const failed = (detail) => log(`Failed to revoke the token on the registry: ${detail}\n` +
|
|
221
|
+
stillLive);
|
|
222
|
+
try {
|
|
223
|
+
const response = await this.request(deleteUrl, {
|
|
224
|
+
useCache: false,
|
|
225
|
+
method: 'DELETE',
|
|
226
|
+
});
|
|
227
|
+
if (!response.ok)
|
|
228
|
+
failed(registryErrorMessage(response));
|
|
229
|
+
}
|
|
230
|
+
catch (er) {
|
|
231
|
+
failed(asError(er).message);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
finally {
|
|
236
|
+
await deleteToken(registry, this.identity);
|
|
157
237
|
}
|
|
158
|
-
await deleteToken(registry, this.identity);
|
|
159
238
|
}
|
|
160
239
|
/**
|
|
161
240
|
* Log into the registry specified.
|
|
@@ -278,12 +357,22 @@ export class RegistryClient {
|
|
|
278
357
|
}
|
|
279
358
|
return await this.#checkLogin(url, options);
|
|
280
359
|
}
|
|
360
|
+
assertOk(response, {
|
|
361
|
+
message: 'Web login failed',
|
|
362
|
+
url,
|
|
363
|
+
advice: statusCode => statusCode === 404 ?
|
|
364
|
+
'This registry does not implement the web login endpoint.'
|
|
365
|
+
: undefined,
|
|
366
|
+
});
|
|
281
367
|
if (response.statusCode === 200) {
|
|
282
368
|
const token = getTokenResponse(response.json());
|
|
283
369
|
if (token)
|
|
284
370
|
return token;
|
|
285
371
|
}
|
|
286
372
|
throw error('Invalid response from web login endpoint', {
|
|
373
|
+
code: 'EREQUEST',
|
|
374
|
+
url,
|
|
375
|
+
status: response.statusCode,
|
|
287
376
|
response,
|
|
288
377
|
});
|
|
289
378
|
}
|
|
@@ -378,8 +467,9 @@ export class RegistryClient {
|
|
|
378
467
|
staleWhileRevalidate &&
|
|
379
468
|
entry?.staleWhileRevalidate &&
|
|
380
469
|
m) {
|
|
381
|
-
// revalidate while returning the stale entry
|
|
382
|
-
|
|
470
|
+
// revalidate while returning the stale entry, re-requesting the
|
|
471
|
+
// same representation since the cache key does not include accept
|
|
472
|
+
register(dirname(this.cache.path()), m, url, getHeader(options.headers, 'accept'));
|
|
383
473
|
logRequest(url, 'stale', { method });
|
|
384
474
|
return entry;
|
|
385
475
|
}
|
package/dist/otplease.js
CHANGED
|
@@ -27,6 +27,9 @@ export const otplease = async (client, options, response) => {
|
|
|
27
27
|
const wwwAuth = new Set(waHeader ? waHeader.toLowerCase().split(/,\s*/) : []);
|
|
28
28
|
if (wwwAuth.has('ipaddress')) {
|
|
29
29
|
throw error('Authorization is not allowed from your ip address', {
|
|
30
|
+
code: 'ENEEDAUTH',
|
|
31
|
+
status: response.statusCode,
|
|
32
|
+
method: options.method,
|
|
30
33
|
response,
|
|
31
34
|
});
|
|
32
35
|
}
|
|
@@ -61,14 +64,27 @@ export const otplease = async (client, options, response) => {
|
|
|
61
64
|
}
|
|
62
65
|
}
|
|
63
66
|
throw error('Unrecognized OTP authentication challenge', {
|
|
67
|
+
code: 'ENEEDAUTH',
|
|
68
|
+
status: response.statusCode,
|
|
69
|
+
method: options.method,
|
|
64
70
|
response,
|
|
65
71
|
});
|
|
66
72
|
}
|
|
67
73
|
if (wwwAuth.has('bearer')) {
|
|
68
|
-
throw error('Missing or invalid authentication token. Run `vlt login` or `vlt token add` to authenticate.', {
|
|
74
|
+
throw error('Missing or invalid authentication token. Run `vlt login` or `vlt token add` to authenticate.', {
|
|
75
|
+
code: 'ENEEDAUTH',
|
|
76
|
+
status: response.statusCode,
|
|
77
|
+
method: options.method,
|
|
78
|
+
response,
|
|
79
|
+
});
|
|
69
80
|
}
|
|
70
81
|
if (wwwAuth.size) {
|
|
71
|
-
throw error('Unknown authentication challenge', {
|
|
82
|
+
throw error('Unknown authentication challenge', {
|
|
83
|
+
code: 'ENEEDAUTH',
|
|
84
|
+
status: response.statusCode,
|
|
85
|
+
method: options.method,
|
|
86
|
+
response,
|
|
87
|
+
});
|
|
72
88
|
}
|
|
73
89
|
// Consume the body to check if it's prompting for OTP.
|
|
74
90
|
// We must return the consumed text so the caller doesn't try to
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The parts of a `CacheEntry` these helpers need.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately narrow and structural rather than `CacheEntry` itself:
|
|
5
|
+
* `RegistryClient.prototype.request` is duck-typed in a dozen tests, and a
|
|
6
|
+
* helper that every command calls must not be the thing that makes those
|
|
7
|
+
* mocks illegal. `text` is optional for the same reason.
|
|
8
|
+
*/
|
|
9
|
+
export type ErrorResponse = {
|
|
10
|
+
statusCode: number;
|
|
11
|
+
text?: () => string;
|
|
12
|
+
[k: number | string | symbol]: any;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Format a non-2xx registry response as `"403 Forbidden — <detail>"`,
|
|
16
|
+
* where the detail is whatever the registry actually said.
|
|
17
|
+
*
|
|
18
|
+
* Falls back to the bare status when the body is empty or cannot be
|
|
19
|
+
* decoded, and to the raw body text when it is not JSON.
|
|
20
|
+
*/
|
|
21
|
+
export declare const registryErrorMessage: (response: ErrorResponse) => string;
|
|
22
|
+
export type AssertOkOptions = {
|
|
23
|
+
/** what we were trying to do, eg `'Failed to list dist-tags'` */
|
|
24
|
+
message: string;
|
|
25
|
+
/** the url that was requested */
|
|
26
|
+
url: URL | string;
|
|
27
|
+
/** the method used; defaults to GET */
|
|
28
|
+
method?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Status-specific guidance appended to the message, one `⚠️` line
|
|
31
|
+
* per entry. Only consulted when the response is an error.
|
|
32
|
+
*/
|
|
33
|
+
advice?: (statusCode: number) => string | (string | undefined)[] | undefined;
|
|
34
|
+
};
|
|
35
|
+
export declare const assertOk: (response: ErrorResponse, options: AssertOkOptions) => void;
|
|
36
|
+
export type RequestErrorOptions = AssertOkOptions;
|
|
37
|
+
/**
|
|
38
|
+
* Wrap an error thrown *by* `RegistryClient.request()` -- as opposed to a
|
|
39
|
+
* non-2xx response it returned, which is {@link assertOk}'s job.
|
|
40
|
+
*
|
|
41
|
+
* A command that catches such an error and rethrows a flat
|
|
42
|
+
* `error(message, { code: 'EREQUEST' })` throws away the only part the
|
|
43
|
+
* user needed: an expired token arrives here as "Missing or invalid
|
|
44
|
+
* authentication token...", and the rethrow reduces that to "Failed to
|
|
45
|
+
* publish package" with the real reason buried in an error log.
|
|
46
|
+
*
|
|
47
|
+
* The auth challenges in `otplease` throw rather than return, but they
|
|
48
|
+
* still carry the response that provoked them. Where there is a status
|
|
49
|
+
* to be had, this builds the error through the same path a returned
|
|
50
|
+
* response takes, so a thrown 401 and a refused 401 read identically.
|
|
51
|
+
* The thrown message is the *reason* and is never dropped: it is the
|
|
52
|
+
* detail after the status, unless the registry's own words are readable,
|
|
53
|
+
* in which case those are the detail and the reason becomes a `⚠️` line
|
|
54
|
+
* ahead of whatever advice the caller adds.
|
|
55
|
+
*
|
|
56
|
+
* With no status at all -- a genuine transport failure -- the inner
|
|
57
|
+
* cause's message is appended so a redirect loop or a refused socket
|
|
58
|
+
* names itself, and that cause is carried through for `printErr` to
|
|
59
|
+
* show as Code/Syscall.
|
|
60
|
+
*/
|
|
61
|
+
export declare const requestError: (err: unknown, { message, url, method, advice }: RequestErrorOptions) => Error;
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { error } from '@vltpkg/error-cause';
|
|
2
|
+
import { asError, isObject } from '@vltpkg/types';
|
|
3
|
+
import { STATUS_CODES } from 'node:http';
|
|
4
|
+
/** longest registry-supplied detail spliced into an error message */
|
|
5
|
+
const MAX_DETAIL_LENGTH = 512;
|
|
6
|
+
const truncate = (s) => s.length <= MAX_DETAIL_LENGTH ?
|
|
7
|
+
s
|
|
8
|
+
: `${s.slice(0, MAX_DETAIL_LENGTH - 1)}…`;
|
|
9
|
+
// A proxy or CDN standing in front of the registry answers with an HTML
|
|
10
|
+
// error page. The tags are noise; the text inside them occasionally is
|
|
11
|
+
// not, so strip rather than discard.
|
|
12
|
+
const isHTML = (s) => /^\s*(<!doctype\s+html|<html\b)/i.test(s);
|
|
13
|
+
const stripTags = (s) => s
|
|
14
|
+
.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, ' ')
|
|
15
|
+
.replace(/<[^>]*>/g, ' ')
|
|
16
|
+
.replace(/\s+/g, ' ')
|
|
17
|
+
.trim();
|
|
18
|
+
// npm writes `{"error":"..."}`; the `-/npm/v1/*` endpoints and several
|
|
19
|
+
// third-party registries write `{"message":"..."}`; a few nest it under
|
|
20
|
+
// `error.message`.
|
|
21
|
+
const detailFromJSON = (text) => {
|
|
22
|
+
let body;
|
|
23
|
+
try {
|
|
24
|
+
body = JSON.parse(text);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// A non-JSON body is itself the most useful detail.
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
if (!body || typeof body !== 'object')
|
|
31
|
+
return undefined;
|
|
32
|
+
const rec = body;
|
|
33
|
+
const nested = rec.error;
|
|
34
|
+
for (const v of [rec.error, rec.message, nested?.message]) {
|
|
35
|
+
if (typeof v === 'string' && v.trim())
|
|
36
|
+
return v.trim();
|
|
37
|
+
}
|
|
38
|
+
return undefined;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Format a non-2xx registry response as `"403 Forbidden — <detail>"`,
|
|
42
|
+
* where the detail is whatever the registry actually said.
|
|
43
|
+
*
|
|
44
|
+
* Falls back to the bare status when the body is empty or cannot be
|
|
45
|
+
* decoded, and to the raw body text when it is not JSON.
|
|
46
|
+
*/
|
|
47
|
+
export const registryErrorMessage = (response) => {
|
|
48
|
+
const statusMessage = STATUS_CODES[response.statusCode];
|
|
49
|
+
const status = `${response.statusCode}${statusMessage ? ` ${statusMessage}` : ''}`;
|
|
50
|
+
let text;
|
|
51
|
+
try {
|
|
52
|
+
text = response.text?.().trim() ?? '';
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// an undecodable body (bad gzip) tells us nothing extra
|
|
56
|
+
return status;
|
|
57
|
+
}
|
|
58
|
+
if (!text)
|
|
59
|
+
return status;
|
|
60
|
+
const detail = detailFromJSON(text) ?? (isHTML(text) ? stripTags(text) : text);
|
|
61
|
+
return detail ? `${status} — ${truncate(detail)}` : status;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Throw a well-formed, user-facing error when a registry response is not
|
|
65
|
+
* a 2xx.
|
|
66
|
+
*
|
|
67
|
+
* `RegistryClient.request()` resolves for every status the registry
|
|
68
|
+
* answers with -- checking is the caller's job. This is that check.
|
|
69
|
+
*
|
|
70
|
+
* 401 and 403 become `ENEEDAUTH`, everything else `EREQUEST`. Both are
|
|
71
|
+
* codes `printErr` renders as a short, actionable message; an error with
|
|
72
|
+
* no code at all falls through to a full `util.inspect` dump and an "open
|
|
73
|
+
* an issue" footer, which is how a routine 403 ends up reported to the
|
|
74
|
+
* user as a vlt bug.
|
|
75
|
+
*/
|
|
76
|
+
const registryError = (response, { message, url, method = 'GET', advice }, from, cause) => {
|
|
77
|
+
const { statusCode } = response;
|
|
78
|
+
const denied = statusCode === 401 || statusCode === 403;
|
|
79
|
+
const extra = advice?.(statusCode);
|
|
80
|
+
const tips = (Array.isArray(extra) ? extra : [extra]).filter((t) => !!t);
|
|
81
|
+
const warn = tips.map(t => `\n⚠️ ${t}`).join('');
|
|
82
|
+
return error(`${message}: ${registryErrorMessage(response)}${warn}`, {
|
|
83
|
+
code: denied ? 'ENEEDAUTH' : 'EREQUEST',
|
|
84
|
+
url,
|
|
85
|
+
method,
|
|
86
|
+
status: statusCode,
|
|
87
|
+
response,
|
|
88
|
+
...(cause === undefined ? {} : { cause: asError(cause) }),
|
|
89
|
+
}, from);
|
|
90
|
+
};
|
|
91
|
+
export const assertOk = (response, options) => {
|
|
92
|
+
const { statusCode } = response;
|
|
93
|
+
// NOT `statusCode >= 200 && statusCode < 300`: duck-typed responses
|
|
94
|
+
// that omit statusCode must stay non-errors, and this matches every
|
|
95
|
+
// hand-rolled check it replaces.
|
|
96
|
+
if (!(statusCode < 200 || statusCode >= 300))
|
|
97
|
+
return;
|
|
98
|
+
throw registryError(response, options, assertOk);
|
|
99
|
+
};
|
|
100
|
+
const isTextFn = (v) => typeof v === 'function';
|
|
101
|
+
/**
|
|
102
|
+
* Wrap an error thrown *by* `RegistryClient.request()` -- as opposed to a
|
|
103
|
+
* non-2xx response it returned, which is {@link assertOk}'s job.
|
|
104
|
+
*
|
|
105
|
+
* A command that catches such an error and rethrows a flat
|
|
106
|
+
* `error(message, { code: 'EREQUEST' })` throws away the only part the
|
|
107
|
+
* user needed: an expired token arrives here as "Missing or invalid
|
|
108
|
+
* authentication token...", and the rethrow reduces that to "Failed to
|
|
109
|
+
* publish package" with the real reason buried in an error log.
|
|
110
|
+
*
|
|
111
|
+
* The auth challenges in `otplease` throw rather than return, but they
|
|
112
|
+
* still carry the response that provoked them. Where there is a status
|
|
113
|
+
* to be had, this builds the error through the same path a returned
|
|
114
|
+
* response takes, so a thrown 401 and a refused 401 read identically.
|
|
115
|
+
* The thrown message is the *reason* and is never dropped: it is the
|
|
116
|
+
* detail after the status, unless the registry's own words are readable,
|
|
117
|
+
* in which case those are the detail and the reason becomes a `⚠️` line
|
|
118
|
+
* ahead of whatever advice the caller adds.
|
|
119
|
+
*
|
|
120
|
+
* With no status at all -- a genuine transport failure -- the inner
|
|
121
|
+
* cause's message is appended so a redirect loop or a refused socket
|
|
122
|
+
* names itself, and that cause is carried through for `printErr` to
|
|
123
|
+
* show as Code/Syscall.
|
|
124
|
+
*/
|
|
125
|
+
export const requestError = (err, { message, url, method = 'GET', advice }) => {
|
|
126
|
+
const e = asError(err);
|
|
127
|
+
const reason = e.message;
|
|
128
|
+
// `error()` hangs its options bag off `.cause`
|
|
129
|
+
const bag = isObject(e.cause) ? e.cause : undefined;
|
|
130
|
+
const res = isObject(bag?.response) ? bag.response : undefined;
|
|
131
|
+
const statusCode = typeof bag?.status === 'number' ? bag.status
|
|
132
|
+
: typeof res?.statusCode === 'number' ? res.statusCode
|
|
133
|
+
: undefined;
|
|
134
|
+
if (statusCode !== undefined) {
|
|
135
|
+
// what the registry said, when the thrower kept a readable body.
|
|
136
|
+
// a raw undici response has none; a CacheEntry does.
|
|
137
|
+
let body = '';
|
|
138
|
+
try {
|
|
139
|
+
const text = res?.text;
|
|
140
|
+
if (isTextFn(text))
|
|
141
|
+
body = String(text()).trim();
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// an undecodable body is no worse than an absent one
|
|
145
|
+
}
|
|
146
|
+
return registryError({ ...res, statusCode, text: () => body || reason }, {
|
|
147
|
+
message,
|
|
148
|
+
url,
|
|
149
|
+
method,
|
|
150
|
+
advice: sc => [
|
|
151
|
+
// the reason only moves here when the body took its place
|
|
152
|
+
...(body ? [reason] : []),
|
|
153
|
+
...[advice?.(sc)].flat(),
|
|
154
|
+
],
|
|
155
|
+
}, requestError, e);
|
|
156
|
+
}
|
|
157
|
+
const inner = bag?.cause === undefined ? undefined : asError(bag.cause);
|
|
158
|
+
const detail = inner?.message && inner.message !== reason ?
|
|
159
|
+
`${reason}: ${inner.message}`
|
|
160
|
+
: reason;
|
|
161
|
+
return error(`${message}: ${detail}`, {
|
|
162
|
+
code: 'EREQUEST',
|
|
163
|
+
url,
|
|
164
|
+
method,
|
|
165
|
+
cause: inner ?? e,
|
|
166
|
+
}, requestError);
|
|
167
|
+
};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import type { RegistryClient } from './index.ts';
|
|
2
|
-
export declare const revalidateEntry: (rc: RegistryClient, method: "GET" | "HEAD", url: URL | string) => Promise<void>;
|
|
2
|
+
export declare const revalidateEntry: (rc: RegistryClient, method: "GET" | "HEAD", url: URL | string, accept?: string) => Promise<void>;
|
package/dist/revalidate-entry.js
CHANGED
|
@@ -36,7 +36,7 @@ const readHead = async (fh) => {
|
|
|
36
36
|
const entry = CacheEntry.decodeHead(headBuf);
|
|
37
37
|
return entry.statusCode ? entry : undefined;
|
|
38
38
|
};
|
|
39
|
-
export const revalidateEntry = async (rc, method, url) => {
|
|
39
|
+
export const revalidateEntry = async (rc, method, url, accept) => {
|
|
40
40
|
try {
|
|
41
41
|
const u = typeof url === 'string' ? new URL(url) : url;
|
|
42
42
|
const key = cacheKey(method, u);
|
|
@@ -55,6 +55,10 @@ export const revalidateEntry = async (rc, method, url) => {
|
|
|
55
55
|
// eslint-disable-next-line @typescript-eslint/no-deprecated -- dispatcher requires path
|
|
56
56
|
options.path = u.pathname.replace(/\/+$/, '') + u.search;
|
|
57
57
|
options.headers = addHeader(addHeader(addHeader(options.headers, 'accept-encoding', 'gzip;q=1.0, identity;q=0.5'), 'user-agent', userAgent), 'npm-session', randomUUID());
|
|
58
|
+
// the representation the entry was originally fetched with
|
|
59
|
+
if (accept) {
|
|
60
|
+
options.headers = addHeader(options.headers, 'accept', accept);
|
|
61
|
+
}
|
|
58
62
|
setCacheHeaders(options, entry);
|
|
59
63
|
options.headers = addHeader(options.headers, 'authorization', await getTokenByURL(String(u), rc.identity));
|
|
60
64
|
const response = await rc.agent.request(options);
|
package/dist/revalidate.js
CHANGED
|
@@ -12,6 +12,18 @@ const revalidateConcurrency = (raw) => {
|
|
|
12
12
|
Math.min(32, Math.floor(n))
|
|
13
13
|
: defaultConcurrency;
|
|
14
14
|
};
|
|
15
|
+
const parseReq = (line) => {
|
|
16
|
+
const method = line.startsWith('GET ') ? 'GET'
|
|
17
|
+
: line.startsWith('HEAD ') ? 'HEAD'
|
|
18
|
+
: undefined;
|
|
19
|
+
if (!method)
|
|
20
|
+
return undefined;
|
|
21
|
+
const rest = line.substring(method.length + 1);
|
|
22
|
+
const sp = rest.indexOf(' ');
|
|
23
|
+
return sp === -1 ?
|
|
24
|
+
[method, new URL(rest), undefined]
|
|
25
|
+
: [method, new URL(rest.substring(0, sp)), rest.substring(sp + 1)];
|
|
26
|
+
};
|
|
15
27
|
const runPool = async (reqs, concurrency, fn) => {
|
|
16
28
|
let next = 0;
|
|
17
29
|
const n = Math.min(concurrency, reqs.length);
|
|
@@ -24,7 +36,7 @@ const runPool = async (reqs, concurrency, fn) => {
|
|
|
24
36
|
/* c8 ignore next */
|
|
25
37
|
if (req === undefined)
|
|
26
38
|
return;
|
|
27
|
-
await fn(req
|
|
39
|
+
await fn(...req);
|
|
28
40
|
}
|
|
29
41
|
}));
|
|
30
42
|
};
|
|
@@ -43,10 +55,8 @@ export const main = async (cache, input = process.stdin) => {
|
|
|
43
55
|
const reqs = Buffer.concat(chunks, chunkLen)
|
|
44
56
|
.toString()
|
|
45
57
|
.split('\0')
|
|
46
|
-
.
|
|
47
|
-
.
|
|
48
|
-
['GET', new URL(i.substring('GET '.length))]
|
|
49
|
-
: ['HEAD', new URL(i.substring('HEAD '.length))]);
|
|
58
|
+
.map(parseReq)
|
|
59
|
+
.filter(req => req !== undefined);
|
|
50
60
|
res(reqs);
|
|
51
61
|
});
|
|
52
62
|
});
|
|
@@ -54,7 +64,7 @@ export const main = async (cache, input = process.stdin) => {
|
|
|
54
64
|
return false;
|
|
55
65
|
}
|
|
56
66
|
const rc = new RegistryClient({ cache });
|
|
57
|
-
await runPool(reqs, revalidateConcurrency(process.env.VLT_REVALIDATE_CONCURRENCY), (method, url) => revalidateEntry(rc, method, url));
|
|
67
|
+
await runPool(reqs, revalidateConcurrency(process.env.VLT_REVALIDATE_CONCURRENCY), (method, url, accept) => revalidateEntry(rc, method, url, accept));
|
|
58
68
|
return true;
|
|
59
69
|
};
|
|
60
70
|
if (isMain(process.argv[1])) {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vltpkg/registry-client",
|
|
3
3
|
"description": "Fetch package artifacts and metadata from registries",
|
|
4
|
-
"version": "1.0
|
|
4
|
+
"version": "1.1.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "git+https://github.com/vltpkg/vltpkg.git",
|
|
@@ -13,14 +13,14 @@
|
|
|
13
13
|
"url": "http://vlt.sh"
|
|
14
14
|
},
|
|
15
15
|
"dependencies": {
|
|
16
|
-
"@vltpkg/cache": "1.0
|
|
17
|
-
"@vltpkg/cache-unzip": "1.0
|
|
18
|
-
"@vltpkg/error-cause": "1.0
|
|
19
|
-
"@vltpkg/keychain": "1.0
|
|
20
|
-
"@vltpkg/output": "1.0
|
|
21
|
-
"@vltpkg/types": "1.0
|
|
22
|
-
"@vltpkg/url-open": "1.0
|
|
23
|
-
"@vltpkg/xdg": "1.0
|
|
16
|
+
"@vltpkg/cache": "1.1.0",
|
|
17
|
+
"@vltpkg/cache-unzip": "1.1.0",
|
|
18
|
+
"@vltpkg/error-cause": "1.1.0",
|
|
19
|
+
"@vltpkg/keychain": "1.1.0",
|
|
20
|
+
"@vltpkg/output": "1.1.0",
|
|
21
|
+
"@vltpkg/types": "1.1.0",
|
|
22
|
+
"@vltpkg/url-open": "1.1.0",
|
|
23
|
+
"@vltpkg/xdg": "1.1.0",
|
|
24
24
|
"cache-control-parser": "^2.0.6",
|
|
25
25
|
"package-json-from-dist": "^1.0.1",
|
|
26
26
|
"undici": "^7.16.0"
|
|
@@ -67,6 +67,11 @@
|
|
|
67
67
|
"import": {
|
|
68
68
|
"default": "./dist/cache-entry.js"
|
|
69
69
|
}
|
|
70
|
+
},
|
|
71
|
+
"./registry-error": {
|
|
72
|
+
"import": {
|
|
73
|
+
"default": "./dist/registry-error.js"
|
|
74
|
+
}
|
|
70
75
|
}
|
|
71
76
|
},
|
|
72
77
|
"files": [
|