@vltpkg/registry-client 1.0.10 → 1.1.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/dist/auth.d.ts CHANGED
@@ -35,7 +35,12 @@ export declare const getToken: (registry: string, identity: string) => Promise<T
35
35
  /**
36
36
  * Find the best matching token for a request URL by performing a
37
37
  * longest-prefix match against all known registry keys (runtime
38
- * tokens, env-var registries, and keychain entries).
38
+ * tokens, env-var registries, and keychain entries). A key that
39
+ * resolves no token is skipped.
40
+ *
41
+ * `VLT_TOKEN_<key>` env vars are only read for a known key: their
42
+ * names are lossy (`.`, `-`, `/` all become `_`), so probing them by
43
+ * request URL would hand the token to lookalike hosts.
39
44
  *
40
45
  * This is used by `RegistryClient.request()` which only has the
41
46
  * full request URL — not the configured registry URL that was used
package/dist/auth.js CHANGED
@@ -78,7 +78,12 @@ export const getToken = async (registry, identity) => {
78
78
  /**
79
79
  * Find the best matching token for a request URL by performing a
80
80
  * longest-prefix match against all known registry keys (runtime
81
- * tokens, env-var registries, and keychain entries).
81
+ * tokens, env-var registries, and keychain entries). A key that
82
+ * resolves no token is skipped.
83
+ *
84
+ * `VLT_TOKEN_<key>` env vars are only read for a known key: their
85
+ * names are lossy (`.`, `-`, `/` all become `_`), so probing them by
86
+ * request URL would hand the token to lookalike hosts.
82
87
  *
83
88
  * This is used by `RegistryClient.request()` which only has the
84
89
  * full request URL — not the configured registry URL that was used
@@ -97,22 +102,14 @@ export const getTokenByURL = async (requestUrl, identity) => {
97
102
  for (const k of await kc.keys()) {
98
103
  candidates.push(k);
99
104
  }
100
- // Find the longest candidate key that is a prefix of the
101
- // normalized request URL.
102
- let bestKey;
103
- let bestLen = 0;
104
- for (const candidate of candidates) {
105
- if (candidate.length > bestLen &&
106
- (normalized === candidate ||
107
- normalized.startsWith(candidate + '/'))) {
108
- bestKey = candidate;
109
- bestLen = candidate.length;
110
- }
111
- }
112
- if (bestKey) {
113
- return getToken(bestKey, identity);
105
+ // Longest candidate key that is a prefix of the normalized request
106
+ // URL and has a token (VLT_REGISTRY may have none).
107
+ const matches = candidates
108
+ .filter(c => normalized === c || normalized.startsWith(c + '/'))
109
+ .sort((a, b) => b.length - a.length);
110
+ for (const key of matches) {
111
+ const tok = await getToken(key, identity);
112
+ if (tok)
113
+ return tok;
114
114
  }
115
- // Fall back to origin-only match (handles VLT_TOKEN_* env vars
116
- // which we can't enumerate by URL).
117
- return getToken(requestUrl, identity);
118
115
  };
@@ -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.
@@ -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;
@@ -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
- const key = `${method} ${url}`;
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) {
@@ -2,22 +2,19 @@ import { isIterable } from "./is-iterable.js";
2
2
  export const deleteHeader = (headers, key) => {
3
3
  if (!headers)
4
4
  return {};
5
+ const lk = key.toLowerCase();
5
6
  if (Array.isArray(headers)) {
6
7
  if (!headers.length)
7
8
  return headers;
8
- if (Array.isArray(headers[0])) {
9
- const index = headers.findIndex(([k]) => k.toLowerCase() === key.toLowerCase());
10
- if (index !== -1)
11
- headers.splice(index, 1);
12
- }
13
- else {
14
- const h = headers;
15
- for (let i = 0; i < h.length; i += 2) {
16
- if (h[i]?.toLowerCase() === key.toLowerCase()) {
17
- headers.splice(i, 2);
18
- break;
19
- }
20
- }
9
+ // remove every match, not just the first
10
+ const step = Array.isArray(headers[0]) ? 1 : 2;
11
+ for (let i = 0; i < headers.length;) {
12
+ const h = headers[i];
13
+ const k = Array.isArray(h) ? h[0] : h;
14
+ if (k.toLowerCase() === lk)
15
+ headers.splice(i, step);
16
+ else
17
+ i += step;
21
18
  }
22
19
  return headers;
23
20
  }
@@ -25,7 +22,10 @@ export const deleteHeader = (headers, key) => {
25
22
  return deleteHeader([...headers], key);
26
23
  }
27
24
  else {
28
- delete headers[key];
25
+ for (const k of Object.keys(headers)) {
26
+ if (k.toLowerCase() === lk)
27
+ delete headers[k];
28
+ }
29
29
  return headers;
30
30
  }
31
31
  };
package/dist/index.d.ts CHANGED
@@ -2,15 +2,18 @@ import { Cache } from '@vltpkg/cache';
2
2
  import type { Integrity } from '@vltpkg/types';
3
3
  import type { Dispatcher } from 'undici';
4
4
  import { RetryAgent } from 'undici';
5
+ import { userAgent } from '@vltpkg/user-agent';
5
6
  import type { Token } from './auth.ts';
6
7
  import { clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, registryBase, runtimeTokens, setRuntimeToken, setToken } from './auth.ts';
7
8
  import type { JSONObj } from './cache-entry.ts';
8
9
  import { CacheEntry } from './cache-entry.ts';
10
+ import { assertOk, registryErrorMessage, requestError } from './registry-error.ts';
11
+ import type { ErrorResponse } from './registry-error.ts';
9
12
  import type { TokenResponse } from './token-response.ts';
10
13
  import type { WebAuthChallenge } from './web-auth-challenge.ts';
11
14
  import { oidc } from './oidc.ts';
12
15
  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, };
16
+ 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
17
  /** A response body read straight out of the cache file. */
15
18
  export type CachedBody = {
16
19
  /** the cache file it came from */
@@ -122,7 +125,12 @@ export type RegistryClientRequestOptions = Omit<Dispatcher.RequestOptions, 'meth
122
125
  */
123
126
  forceRevalidate?: boolean;
124
127
  };
125
- export declare const userAgent: string;
128
+ /**
129
+ * The `User-Agent` header sent with every request. Re-exported from
130
+ * `@vltpkg/user-agent`, which is where the value is defined, so that
131
+ * existing importers of this package keep working.
132
+ */
133
+ export { userAgent };
126
134
  export declare class RegistryClient {
127
135
  #private;
128
136
  agent: RetryAgent;
package/dist/index.js CHANGED
@@ -11,17 +11,18 @@ import { STATUS_CODES } from 'node:http';
11
11
  import { availableParallelism } from 'node:os';
12
12
  import { dirname, resolve } from 'node:path';
13
13
  import { setTimeout } from 'node:timers/promises';
14
- import { loadPackageJson } from 'package-json-from-dist';
15
14
  import { RetryAgent } from 'undici';
15
+ import { userAgent } from '@vltpkg/user-agent';
16
16
  import { addHeader } from "./add-header.js";
17
17
  import { clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, registryBase, runtimeTokens, setRuntimeToken, setToken, } from "./auth.js";
18
18
  import { CacheEntry } from "./cache-entry.js";
19
19
  import { register } from "./cache-revalidate.js";
20
- import { bun, deno, node } from "./env.js";
20
+ import { getHeader } from "./get-header.js";
21
21
  import { handleCacheHitResponse } from "./handle-304-response.js";
22
22
  import { otplease } from "./otplease.js";
23
23
  import { getDispatcher } from "./proxy.js";
24
24
  import { isRedirect, redirect } from "./redirect.js";
25
+ import { assertOk, registryErrorMessage, requestError, } from "./registry-error.js";
25
26
  import { setCacheHeaders } from "./set-cache-headers.js";
26
27
  import { getTokenResponse } from "./token-response.js";
27
28
  import { getWebAuthChallenge } from "./web-auth-challenge.js";
@@ -29,16 +30,15 @@ import { collectHeaders, readBody } from "./response.js";
29
30
  import { oidc } from "./oidc.js";
30
31
  // eslint-disable-next-line no-console
31
32
  const log = (msg) => console.error(msg);
32
- export { CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, runtimeTokens, setRuntimeToken, setToken, };
33
+ export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, requestError, runtimeTokens, setRuntimeToken, setToken, };
33
34
  export const isCacheableMethod = (m) => m === 'GET' || m === 'HEAD';
34
35
  export const cacheKey = (method, url) => `${method !== 'GET' ? method + ' ' : ''}${url}`;
35
- const { version } = loadPackageJson(import.meta.filename, process.env.__VLT_INTERNAL_REGISTRY_CLIENT_PACKAGE_JSON);
36
- const nua = globalThis.navigator?.userAgent ??
37
- (bun ? `Bun/${bun}`
38
- : deno ? `Deno/${deno}`
39
- : node ? `Node.js/${node}`
40
- : '(unknown platform)');
41
- export const userAgent = `@vltpkg/registry-client/${version} ${nua}`;
36
+ /**
37
+ * The `User-Agent` header sent with every request. Re-exported from
38
+ * `@vltpkg/user-agent`, which is where the value is defined, so that
39
+ * existing importers of this package keep working.
40
+ */
41
+ export { userAgent };
42
42
  // Agent-level knobs only. Do not spread these onto per-request options —
43
43
  // connections/pipelining/keepAlive/connect are ignored at dispatch time,
44
44
  // and bodyTimeout/headersTimeout would clobber caller overrides.
@@ -124,7 +124,51 @@ export class RegistryClient {
124
124
  */
125
125
  async scroll(url, options = {}, seek) {
126
126
  const resp = await this.request(url, options);
127
- const { objects, urls } = resp.json();
127
+ const { statusCode } = resp;
128
+ if (statusCode < 200 || statusCode >= 300) {
129
+ let detail;
130
+ try {
131
+ const body = resp.json();
132
+ if (body && typeof body === 'object' && 'error' in body) {
133
+ detail = body.error;
134
+ }
135
+ }
136
+ catch {
137
+ // Registries and proxies can return plain text or HTML errors.
138
+ }
139
+ const status = STATUS_CODES[statusCode];
140
+ throw error(`Failed to fetch paginated results: ${statusCode}${status ? ` ${status}` : ''}${typeof detail === 'string' && detail ? `: ${detail}` : ''}`, { code: 'EREQUEST', status: statusCode, url: String(url) });
141
+ }
142
+ let body;
143
+ try {
144
+ body = resp.json();
145
+ }
146
+ catch (cause) {
147
+ throw error('Invalid JSON in paginated registry response', {
148
+ code: 'EREQUEST',
149
+ url: String(url),
150
+ cause,
151
+ });
152
+ }
153
+ if (!body ||
154
+ typeof body !== 'object' ||
155
+ !('objects' in body) ||
156
+ !Array.isArray(body.objects) ||
157
+ !('urls' in body) ||
158
+ !body.urls ||
159
+ typeof body.urls !== 'object' ||
160
+ Array.isArray(body.urls) ||
161
+ ('next' in body.urls &&
162
+ body.urls.next !== null &&
163
+ body.urls.next !== undefined &&
164
+ typeof body.urls.next !== 'string')) {
165
+ throw error('Invalid pagination in registry response', {
166
+ code: 'EREQUEST',
167
+ url: String(url),
168
+ });
169
+ }
170
+ const objects = body.objects;
171
+ const urls = body.urls;
128
172
  // if we have more, and haven't found our target, fetch more
129
173
  return urls.next && !(seek && objects.some(seek)) ?
130
174
  objects.concat(await this.scroll(urls.next, options, seek))
@@ -148,14 +192,47 @@ export class RegistryClient {
148
192
  const s = tok.replace(/^(Bearer|Basic) /i, '');
149
193
  const base = registryBase(registry);
150
194
  const tokensUrl = new URL('-/npm/v1/tokens', base);
151
- const record = await this.seek(tokensUrl, ({ token }) => s.startsWith(token), {
152
- useCache: false,
153
- }).catch(() => undefined);
154
- if (record) {
155
- const { key } = record;
156
- await this.request(new URL(`-/npm/v1/tokens/token/${key}`, base), { useCache: false, method: 'DELETE' });
195
+ // Logging out must always drop the local credential -- a registry
196
+ // that will not talk to us cannot be allowed to strand a token on
197
+ // disk. But a token that outlives `vlt logout` server-side is
198
+ // security-relevant, so a failure is said out loud rather than
199
+ // swallowed.
200
+ const stillLive = `Removing the local credential anyway; revoke the token in the ` +
201
+ `registry UI if it is still live.`;
202
+ // the `finally` is the guarantee: `request()` rethrows a transport
203
+ // failure as EREQUEST, so without it a registry we cannot reach at
204
+ // all would take the local credential down with it.
205
+ try {
206
+ let record;
207
+ try {
208
+ record = await this.seek(tokensUrl, ({ token }) => s.startsWith(token), {
209
+ useCache: false,
210
+ });
211
+ }
212
+ catch (er) {
213
+ log(`Could not list tokens at ${tokensUrl}: ${asError(er).message}\n` +
214
+ stillLive);
215
+ }
216
+ if (record) {
217
+ const deleteUrl = new URL(`-/npm/v1/tokens/token/${record.key}`, base);
218
+ const failed = (detail) => log(`Failed to revoke the token on the registry: ${detail}\n` +
219
+ stillLive);
220
+ try {
221
+ const response = await this.request(deleteUrl, {
222
+ useCache: false,
223
+ method: 'DELETE',
224
+ });
225
+ if (!response.ok)
226
+ failed(registryErrorMessage(response));
227
+ }
228
+ catch (er) {
229
+ failed(asError(er).message);
230
+ }
231
+ }
232
+ }
233
+ finally {
234
+ await deleteToken(registry, this.identity);
157
235
  }
158
- await deleteToken(registry, this.identity);
159
236
  }
160
237
  /**
161
238
  * Log into the registry specified.
@@ -278,12 +355,22 @@ export class RegistryClient {
278
355
  }
279
356
  return await this.#checkLogin(url, options);
280
357
  }
358
+ assertOk(response, {
359
+ message: 'Web login failed',
360
+ url,
361
+ advice: statusCode => statusCode === 404 ?
362
+ 'This registry does not implement the web login endpoint.'
363
+ : undefined,
364
+ });
281
365
  if (response.statusCode === 200) {
282
366
  const token = getTokenResponse(response.json());
283
367
  if (token)
284
368
  return token;
285
369
  }
286
370
  throw error('Invalid response from web login endpoint', {
371
+ code: 'EREQUEST',
372
+ url,
373
+ status: response.statusCode,
287
374
  response,
288
375
  });
289
376
  }
@@ -378,8 +465,9 @@ export class RegistryClient {
378
465
  staleWhileRevalidate &&
379
466
  entry?.staleWhileRevalidate &&
380
467
  m) {
381
- // revalidate while returning the stale entry
382
- register(dirname(this.cache.path()), m, url);
468
+ // revalidate while returning the stale entry, re-requesting the
469
+ // same representation since the cache key does not include accept
470
+ register(dirname(this.cache.path()), m, url, getHeader(options.headers, 'accept'));
383
471
  logRequest(url, 'stale', { method });
384
472
  return entry;
385
473
  }
@@ -387,6 +475,7 @@ export class RegistryClient {
387
475
  const requestStart = Date.now();
388
476
  // either no cache entry, or need to revalidate before use.
389
477
  setCacheHeaders(options, entry);
478
+ const redirected = redirections.size > 0;
390
479
  redirections.add(String(url));
391
480
  // eslint-disable-next-line @typescript-eslint/no-deprecated -- deprecated for callers; this is the one place that sets it
392
481
  options.path = u.pathname.replace(/\/+$/, '') + u.search;
@@ -399,8 +488,13 @@ export class RegistryClient {
399
488
  options.headers = addHeader(options.headers, 'accept-integrity', integrity);
400
489
  }
401
490
  options.method = options.method ?? 'GET';
402
- // will remove if we don't have a token.
403
- options.headers = addHeader(options.headers, 'authorization', await getTokenByURL(String(u), this.identity));
491
+ // a same-origin redirect keeps the credential of the hop that led
492
+ // here, since path-scoped keys may not match the new path.
493
+ // redirect() strips it when the origin changes.
494
+ if (!redirected || !getHeader(options.headers, 'authorization')) {
495
+ // will remove if we don't have a token.
496
+ options.headers = addHeader(options.headers, 'authorization', await getTokenByURL(String(u), this.identity));
497
+ }
404
498
  let response = null;
405
499
  try {
406
500
  response = await this.agent.request(options);
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.', { response });
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', { response });
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
@@ -16,6 +16,8 @@ export declare const isRedirect: (response: CacheEntry) => response is RedirectR
16
16
  * Throws an error if maxRedirections is hit or the redirections set already
17
17
  * contains the new location.
18
18
  *
19
+ * Strips the `authorization` header when the redirect changes origin.
20
+ *
19
21
  * Ensure that the response is in fact a redirection first, by calling
20
22
  * {@link isRedirect} on it.
21
23
  */
package/dist/redirect.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // given a RegistryClientOptions object, and a redirection response,
2
2
  import { error } from '@vltpkg/error-cause';
3
+ import { deleteHeader } from "./delete-header.js";
3
4
  const redirectStatuses = new Set([301, 302, 303, 307, 308]);
4
5
  export const isRedirect = (response) => redirectStatuses.has(response.statusCode) &&
5
6
  !!response.getHeader('location')?.length;
@@ -13,6 +14,8 @@ export const isRedirect = (response) => redirectStatuses.has(response.statusCode
13
14
  * Throws an error if maxRedirections is hit or the redirections set already
14
15
  * contains the new location.
15
16
  *
17
+ * Strips the `authorization` header when the redirect changes origin.
18
+ *
16
19
  * Ensure that the response is in fact a redirection first, by calling
17
20
  * {@link isRedirect} on it.
18
21
  */
@@ -47,6 +50,10 @@ export const redirect = (options, response, from) => {
47
50
  // eslint-disable-next-line @typescript-eslint/no-deprecated -- thats why we are deleting it
48
51
  delete nextOptions.path;
49
52
  redirections.add(String(nextURL));
53
+ // a credential belongs to the origin it was resolved for
54
+ if (nextURL.origin !== from.origin) {
55
+ nextOptions.headers = deleteHeader(nextOptions.headers, 'authorization');
56
+ }
50
57
  switch (response.statusCode) {
51
58
  case 303: {
52
59
  // drop body, change method to GET
@@ -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>;
@@ -1,10 +1,11 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { open, readFile } from 'node:fs/promises';
3
+ import { userAgent } from '@vltpkg/user-agent';
3
4
  import { addHeader } from "./add-header.js";
4
5
  import { getTokenByURL } from "./auth.js";
5
6
  import { CacheEntry } from "./cache-entry.js";
6
7
  import { handleCacheHitResponse } from "./handle-304-response.js";
7
- import { cacheKey, userAgent } from "./index.js";
8
+ import { cacheKey } from "./index.js";
8
9
  import { collectHeaders, readBody } from "./response.js";
9
10
  import { setCacheHeaders } from "./set-cache-headers.js";
10
11
  const patchDateFallback = async (rc, file, key, head) => {
@@ -36,7 +37,7 @@ const readHead = async (fh) => {
36
37
  const entry = CacheEntry.decodeHead(headBuf);
37
38
  return entry.statusCode ? entry : undefined;
38
39
  };
39
- export const revalidateEntry = async (rc, method, url) => {
40
+ export const revalidateEntry = async (rc, method, url, accept) => {
40
41
  try {
41
42
  const u = typeof url === 'string' ? new URL(url) : url;
42
43
  const key = cacheKey(method, u);
@@ -55,6 +56,10 @@ export const revalidateEntry = async (rc, method, url) => {
55
56
  // eslint-disable-next-line @typescript-eslint/no-deprecated -- dispatcher requires path
56
57
  options.path = u.pathname.replace(/\/+$/, '') + u.search;
57
58
  options.headers = addHeader(addHeader(addHeader(options.headers, 'accept-encoding', 'gzip;q=1.0, identity;q=0.5'), 'user-agent', userAgent), 'npm-session', randomUUID());
59
+ // the representation the entry was originally fetched with
60
+ if (accept) {
61
+ options.headers = addHeader(options.headers, 'accept', accept);
62
+ }
58
63
  setCacheHeaders(options, entry);
59
64
  options.headers = addHeader(options.headers, 'authorization', await getTokenByURL(String(u), rc.identity));
60
65
  const response = await rc.agent.request(options);
@@ -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[0], req[1]);
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
- .filter(i => !!i && (i.startsWith('GET ') || i.startsWith('HEAD ')))
47
- .map(i => i.startsWith('GET ') ?
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.10",
4
+ "version": "1.1.1",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/vltpkg/vltpkg.git",
@@ -13,16 +13,16 @@
13
13
  "url": "http://vlt.sh"
14
14
  },
15
15
  "dependencies": {
16
- "@vltpkg/cache": "1.0.10",
17
- "@vltpkg/cache-unzip": "1.0.10",
18
- "@vltpkg/error-cause": "1.0.10",
19
- "@vltpkg/keychain": "1.0.10",
20
- "@vltpkg/output": "1.0.10",
21
- "@vltpkg/types": "1.0.10",
22
- "@vltpkg/url-open": "1.0.10",
23
- "@vltpkg/xdg": "1.0.10",
16
+ "@vltpkg/cache": "1.1.1",
17
+ "@vltpkg/cache-unzip": "1.1.1",
18
+ "@vltpkg/error-cause": "1.1.1",
19
+ "@vltpkg/keychain": "1.1.1",
20
+ "@vltpkg/output": "1.1.1",
21
+ "@vltpkg/types": "1.1.1",
22
+ "@vltpkg/url-open": "1.1.1",
23
+ "@vltpkg/user-agent": "1.1.1",
24
+ "@vltpkg/xdg": "1.1.1",
24
25
  "cache-control-parser": "^2.0.6",
25
- "package-json-from-dist": "^1.0.1",
26
26
  "undici": "^7.16.0"
27
27
  },
28
28
  "devDependencies": {
@@ -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": [
package/dist/env.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export declare const isDeno: boolean;
2
- export declare const isBun: boolean;
3
- export declare const isNode: boolean;
4
- export declare const bun: string | undefined;
5
- export declare const deno: string | undefined;
6
- export declare const node: string | undefined;
package/dist/env.js DELETED
@@ -1,12 +0,0 @@
1
- import proc from 'node:process';
2
- const { Deno, Bun } = globalThis;
3
- const isObj = (v) => typeof v === 'object' && !!v;
4
- export const isDeno = isObj(Deno);
5
- export const isBun = !isDeno && isObj(Bun);
6
- // bun and deno also report 'node' in process.versions so its only
7
- // node if it is not bun or deno
8
- export const isNode = !isDeno && !isBun && 'node' in proc.versions;
9
- // All the runtimes put their versions into process.versions
10
- export const bun = isBun ? proc.versions.bun : undefined;
11
- export const deno = isDeno ? proc.versions.deno : undefined;
12
- export const node = isNode ? proc.versions.node : undefined;