@vltpkg/registry-client 1.1.0 → 1.2.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/README.md CHANGED
@@ -59,12 +59,22 @@ So,
59
59
  - json responses will always be un-zipped, in the response and in the
60
60
  cache.
61
61
  - artifact responses _may_ be gzipped (and thus, have to be unzipped
62
- by the unpack operation), but will eventually be cached as unzipped
62
+ by the unpack operation). Tarballs exploded into the global store
63
+ stay gzipped; the rest will eventually be cached as unzipped
63
64
  tarballs.
64
65
 
65
66
  Thus, the `content-length` response header will _usually_ not match
66
67
  the actual byte length of the response body.
67
68
 
69
+ Tarball entries with an `integrity` header, gzipped or not, are also
70
+ passed to that child with the global store root (the `storeRoot`
71
+ option, default `storeRoot(cache)`, i.e. `<cache>/store/v1`, also at
72
+ `@vltpkg/registry-client/store-root`), so it can explode them there
73
+ when `VLT_STORE_LINKER` enables the store.
74
+ `queueForStore(key, integrity)` queues an already cached tarball (a
75
+ `cachedBody()` hit) the same way: exploded when the store is on, else
76
+ un-gzipped.
77
+
68
78
  ## Proxies
69
79
 
70
80
  If `http_proxy` or `https_proxy` is set in the environment (either
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
  };
@@ -99,18 +99,35 @@ export declare class CacheEntry {
99
99
  * This method **will throw** if the integrity values do not match.
100
100
  *
101
101
  * Note that this will *usually* not be true if the value is coming out of
102
- * the cache, because the cache entries are un-gzipped in place. It should
103
- * _only_ be called for artifacts that come from an actual http response.
102
+ * the cache, because cache entries not exploded into the global store are
103
+ * un-gzipped in place. It should _only_ be called for artifacts that come
104
+ * from an actual http response.
104
105
  *
105
106
  * Returns true if anything was actually verified.
106
107
  */
107
108
  checkIntegrity(context?: ErrorCauseOptions): this is CacheEntry & {
108
109
  integrity: Integrity;
109
110
  };
111
+ /**
112
+ * Check the body against the RFC 9530 digest the server sent with it,
113
+ * for a response that had no expected integrity. A registry that omits
114
+ * `dist.integrity` labels every tarball, so a missing digest fails when
115
+ * `required`. Like {@link checkIntegrity}, only for an actual http
116
+ * response: cached bodies are un-gzipped in place.
117
+ *
118
+ * **Will throw** on a mismatch. Returns the hash of the body.
119
+ */
120
+ checkDigest(required: boolean, context?: ErrorCauseOptions): Integrity;
110
121
  get integrityActual(): Integrity;
111
122
  set integrityActual(i: Integrity);
112
123
  set integrity(i: Integrity | undefined);
113
124
  get integrity(): Integrity | undefined;
125
+ /**
126
+ * The sha-512 member of an RFC 9530 `Repr-Digest` (or `Content-Digest`)
127
+ * response header, as an SRI string. A registry that serves packuments
128
+ * without `dist.integrity` labels each tarball this way instead.
129
+ */
130
+ get digest(): Integrity | undefined;
114
131
  /**
115
132
  * Give it a key, and it'll return the buffer of that header value
116
133
  */
@@ -123,6 +140,10 @@ export declare class CacheEntry {
123
140
  * Set a header to a specific value
124
141
  */
125
142
  setHeader(h: string, value: Uint8Array | string): void;
143
+ /**
144
+ * Remove a header, if present
145
+ */
146
+ deleteHeader(h: string): void;
126
147
  /**
127
148
  * Return the body of the entry as a Buffer
128
149
  */
@@ -158,6 +179,11 @@ export declare class CacheEntry {
158
179
  */
159
180
  static decode(buffer: Uint8Array, options?: CacheEntryOptions): CacheEntry;
160
181
  static isGzipEntry(buffer: Uint8Array): boolean;
182
+ /**
183
+ * Head-only check for a 200 non-JSON body with an integrity header,
184
+ * i.e. a tarball the global store can be built from.
185
+ */
186
+ static isTarballEntry(buffer: Uint8Array): boolean;
161
187
  /**
162
188
  * Encode status + headers (no body) as they appear at the start of
163
189
  * an on-disk cache file.
@@ -293,8 +293,9 @@ export class CacheEntry {
293
293
  * This method **will throw** if the integrity values do not match.
294
294
  *
295
295
  * Note that this will *usually* not be true if the value is coming out of
296
- * the cache, because the cache entries are un-gzipped in place. It should
297
- * _only_ be called for artifacts that come from an actual http response.
296
+ * the cache, because cache entries not exploded into the global store are
297
+ * un-gzipped in place. It should _only_ be called for artifacts that come
298
+ * from an actual http response.
298
299
  *
299
300
  * Returns true if anything was actually verified.
300
301
  */
@@ -312,6 +313,29 @@ export class CacheEntry {
312
313
  }
313
314
  return true;
314
315
  }
316
+ /**
317
+ * Check the body against the RFC 9530 digest the server sent with it,
318
+ * for a response that had no expected integrity. A registry that omits
319
+ * `dist.integrity` labels every tarball, so a missing digest fails when
320
+ * `required`. Like {@link checkIntegrity}, only for an actual http
321
+ * response: cached bodies are un-gzipped in place.
322
+ *
323
+ * **Will throw** on a mismatch. Returns the hash of the body.
324
+ */
325
+ checkDigest(required, context = {}) {
326
+ const computed = this.integrityActual;
327
+ const { digest } = this;
328
+ if (digest ? digest !== computed : required) {
329
+ throw error('Integrity check failure', {
330
+ code: 'EINTEGRITY',
331
+ response: this,
332
+ wanted: digest,
333
+ found: computed,
334
+ ...context,
335
+ });
336
+ }
337
+ return computed;
338
+ }
315
339
  get integrityActual() {
316
340
  if (this.#integrityActual)
317
341
  return this.#integrityActual;
@@ -335,6 +359,17 @@ export class CacheEntry {
335
359
  get integrity() {
336
360
  return this.#integrity;
337
361
  }
362
+ /**
363
+ * The sha-512 member of an RFC 9530 `Repr-Digest` (or `Content-Digest`)
364
+ * response header, as an SRI string. A registry that serves packuments
365
+ * without `dist.integrity` labels each tarball this way instead.
366
+ */
367
+ get digest() {
368
+ const value = this.getHeaderString('repr-digest') ??
369
+ this.getHeaderString('content-digest');
370
+ const m = value && /(?:^|,)\s*sha-512=:([A-Za-z0-9+/]{86}==):/.exec(value);
371
+ return m ? `sha512-${m[1]}` : undefined;
372
+ }
338
373
  /**
339
374
  * Give it a key, and it'll return the buffer of that header value
340
375
  */
@@ -356,6 +391,19 @@ export class CacheEntry {
356
391
  setHeader(h, value) {
357
392
  this.#headers = setRawHeader(this.#headers, h, value);
358
393
  }
394
+ /**
395
+ * Remove a header, if present
396
+ */
397
+ deleteHeader(h) {
398
+ const key = h.toLowerCase();
399
+ for (let i = 0; i < this.#headers.length; i += 2) {
400
+ const k = this.#headers[i];
401
+ if (k && getDecodedValue(k).toLowerCase() === key) {
402
+ this.#headers.splice(i, 2);
403
+ return;
404
+ }
405
+ }
406
+ }
359
407
  /**
360
408
  * Return the body of the entry as a Buffer
361
409
  */
@@ -546,6 +594,17 @@ export class CacheEntry {
546
594
  const gzipBytes = buffer.subarray(headSize, headSize + 2);
547
595
  return gzipBytes[0] === 0x1f && gzipBytes[1] === 0x8b;
548
596
  }
597
+ /**
598
+ * Head-only check for a 200 non-JSON body with an integrity header,
599
+ * i.e. a tarball the global store can be built from.
600
+ */
601
+ static isTarballEntry(buffer) {
602
+ const parsed = CacheEntry.#parseHead(buffer);
603
+ if (parsed?.statusCode !== 200 || !parsed.integrity)
604
+ return false;
605
+ const ct = getRawHeader(parsed.headers, 'content-type');
606
+ return !ct || !/\bjson\b/.test(getDecodedValue(ct));
607
+ }
549
608
  /**
550
609
  * Encode status + headers (no body) as they appear at the start of
551
610
  * an on-disk cache file.
@@ -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,6 +2,7 @@ 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';
@@ -10,15 +11,22 @@ import { assertOk, registryErrorMessage, requestError } from './registry-error.t
10
11
  import type { ErrorResponse } from './registry-error.ts';
11
12
  import type { TokenResponse } from './token-response.ts';
12
13
  import type { WebAuthChallenge } from './web-auth-challenge.ts';
14
+ import { storeRoot } from './store-root.ts';
13
15
  import { oidc } from './oidc.ts';
14
16
  import type { OidcOptions } from './oidc.ts';
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, };
17
+ export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, requestError, runtimeTokens, setRuntimeToken, setToken, storeRoot, type ErrorResponse, type JSONObj, type OidcOptions, type Token, type TokenResponse, type WebAuthChallenge, };
16
18
  /** A response body read straight out of the cache file. */
17
19
  export type CachedBody = {
18
20
  /** the cache file it came from */
19
21
  path: string;
22
+ /** the cache key of the request */
23
+ key: string;
20
24
  /** the body, a view into the file's bytes */
21
25
  body: Buffer;
26
+ /** the hash the entry was stored under, if it has one */
27
+ integrity?: Integrity;
28
+ /** the body on disk is gzipped (`body` may be un-gzipped) */
29
+ gzip: boolean;
22
30
  };
23
31
  export type CacheableMethod = 'GET' | 'HEAD';
24
32
  export declare const isCacheableMethod: (m: unknown) => m is CacheableMethod;
@@ -30,6 +38,8 @@ export type RegistryClientOptions = {
30
38
  * Defaults to the XDG cache folder for `vlt/registry-client`
31
39
  */
32
40
  cache?: string;
41
+ /** Global store root. Defaults to {@link storeRoot} of `cache`. */
42
+ storeRoot?: string;
33
43
  /**
34
44
  * Number of retries to perform when encountering network errors or
35
45
  * likely-transient errors from git hosts.
@@ -85,6 +95,13 @@ export type RegistryClientRequestOptions = Omit<Dispatcher.RequestOptions, 'meth
85
95
  * also serves the tarball itself.
86
96
  */
87
97
  trustIntegrity?: boolean;
98
+ /**
99
+ * With no `integrity` to expect, check the body against the RFC 9530
100
+ * `Repr-Digest` the server sent with it. `'required'` also rejects a
101
+ * response that carries no digest. Runs before the response is cached,
102
+ * so a body that fails is never served from the cache later.
103
+ */
104
+ verifyDigest?: boolean | 'required';
88
105
  /**
89
106
  * Follow up to 10 redirections by default. Set this to 0 to just return
90
107
  * the 3xx response. If the max redirections are expired, and we still get
@@ -124,7 +141,12 @@ export type RegistryClientRequestOptions = Omit<Dispatcher.RequestOptions, 'meth
124
141
  */
125
142
  forceRevalidate?: boolean;
126
143
  };
127
- export declare const userAgent: string;
144
+ /**
145
+ * The `User-Agent` header sent with every request. Re-exported from
146
+ * `@vltpkg/user-agent`, which is where the value is defined, so that
147
+ * existing importers of this package keep working.
148
+ */
149
+ export { userAgent };
128
150
  export declare class RegistryClient {
129
151
  #private;
130
152
  agent: RetryAgent;
@@ -181,5 +203,12 @@ export declare class RegistryClient {
181
203
  integrity?: Integrity;
182
204
  method?: CacheableMethod;
183
205
  }): CachedBody | undefined;
206
+ /**
207
+ * Queue the cached tarball at `key` (a {@link CachedBody} key) for the
208
+ * background child: exploded into the global store when that is on,
209
+ * else un-gzipped. `integrity` finds it when only the integrity path
210
+ * holds it.
211
+ */
212
+ queueForStore(key: string, integrity?: Integrity): void;
184
213
  request(url: URL | string, options?: RegistryClientRequestOptions): Promise<CacheEntry>;
185
214
  }
package/dist/index.js CHANGED
@@ -11,13 +11,12 @@ 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";
21
20
  import { getHeader } from "./get-header.js";
22
21
  import { handleCacheHitResponse } from "./handle-304-response.js";
23
22
  import { otplease } from "./otplease.js";
@@ -28,19 +27,19 @@ import { setCacheHeaders } from "./set-cache-headers.js";
28
27
  import { getTokenResponse } from "./token-response.js";
29
28
  import { getWebAuthChallenge } from "./web-auth-challenge.js";
30
29
  import { collectHeaders, readBody } from "./response.js";
30
+ import { storeRoot } from "./store-root.js";
31
31
  import { oidc } from "./oidc.js";
32
32
  // eslint-disable-next-line no-console
33
33
  const log = (msg) => console.error(msg);
34
- export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, requestError, runtimeTokens, setRuntimeToken, setToken, };
34
+ export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, requestError, runtimeTokens, setRuntimeToken, setToken, storeRoot, };
35
35
  export const isCacheableMethod = (m) => m === 'GET' || m === 'HEAD';
36
36
  export const cacheKey = (method, url) => `${method !== 'GET' ? method + ' ' : ''}${url}`;
37
- const { version } = loadPackageJson(import.meta.filename, process.env.__VLT_INTERNAL_REGISTRY_CLIENT_PACKAGE_JSON);
38
- const nua = globalThis.navigator?.userAgent ??
39
- (bun ? `Bun/${bun}`
40
- : deno ? `Deno/${deno}`
41
- : node ? `Node.js/${node}`
42
- : '(unknown platform)');
43
- export const userAgent = `@vltpkg/registry-client/${version} ${nua}`;
37
+ /**
38
+ * The `User-Agent` header sent with every request. Re-exported from
39
+ * `@vltpkg/user-agent`, which is where the value is defined, so that
40
+ * existing importers of this package keep working.
41
+ */
42
+ export { userAgent };
44
43
  // Agent-level knobs only. Do not spread these onto per-request options —
45
44
  // connections/pipelining/keepAlive/connect are ignored at dispatch time,
46
45
  // and bodyTimeout/headersTimeout would clobber caller overrides.
@@ -93,12 +92,15 @@ export class RegistryClient {
93
92
  this.identity = identity;
94
93
  this.staleWhileRevalidateFactor = staleWhileRevalidateFactor;
95
94
  const path = resolve(cache, 'registry-client');
95
+ const store = options.storeRoot ?? storeRoot(cache);
96
96
  this.cache = new Cache({
97
97
  path,
98
+ store,
98
99
  maxSize: parseCacheMaxSize(process.env.VLT_CACHE_MAX_SIZE),
99
100
  onDiskWrite(_path, key, data) {
100
- if (CacheEntry.isGzipEntry(data)) {
101
- cacheUnzipRegister(path, key);
101
+ if (CacheEntry.isGzipEntry(data) ||
102
+ CacheEntry.isTarballEntry(data)) {
103
+ cacheUnzipRegister(path, key, store);
102
104
  }
103
105
  },
104
106
  });
@@ -430,17 +432,32 @@ export class RegistryClient {
430
432
  entry.isJSON) {
431
433
  continue;
432
434
  }
433
- return { path, body: entry.buffer() };
435
+ return {
436
+ path,
437
+ key,
438
+ body: entry.buffer(),
439
+ integrity: entry.integrity,
440
+ gzip: CacheEntry.isGzipEntry(buf),
441
+ };
434
442
  }
435
443
  /* c8 ignore next */
436
444
  }
437
445
  catch { }
438
446
  return undefined;
439
447
  }
448
+ /**
449
+ * Queue the cached tarball at `key` (a {@link CachedBody} key) for the
450
+ * background child: exploded into the global store when that is on,
451
+ * else un-gzipped. `integrity` finds it when only the integrity path
452
+ * holds it.
453
+ */
454
+ queueForStore(key, integrity) {
455
+ cacheUnzipRegister(this.cache.path(), key, this.cache.store, integrity);
456
+ }
440
457
  async request(url, options = {}) {
441
458
  const u = typeof url === 'string' ? new URL(url) : url;
442
459
  const { method = 'GET', integrity, redirections = new Set(), signal, otp = (process.env.VLT_OTP ?? '').trim(), staleWhileRevalidate = true, forceRevalidate = false, } = options;
443
- let { trustIntegrity } = options;
460
+ const { trustIntegrity, verifyDigest } = options;
444
461
  const m = isCacheableMethod(method) ? method : undefined;
445
462
  const { useCache = !!m } = options;
446
463
  signal?.throwIfAborted();
@@ -477,6 +494,7 @@ export class RegistryClient {
477
494
  const requestStart = Date.now();
478
495
  // either no cache entry, or need to revalidate before use.
479
496
  setCacheHeaders(options, entry);
497
+ const redirected = redirections.size > 0;
480
498
  redirections.add(String(url));
481
499
  // eslint-disable-next-line @typescript-eslint/no-deprecated -- deprecated for callers; this is the one place that sets it
482
500
  options.path = u.pathname.replace(/\/+$/, '') + u.search;
@@ -489,8 +507,13 @@ export class RegistryClient {
489
507
  options.headers = addHeader(options.headers, 'accept-integrity', integrity);
490
508
  }
491
509
  options.method = options.method ?? 'GET';
492
- // will remove if we don't have a token.
493
- options.headers = addHeader(options.headers, 'authorization', await getTokenByURL(String(u), this.identity));
510
+ // a same-origin redirect keeps the credential of the hop that led
511
+ // here, since path-scoped keys may not match the new path.
512
+ // redirect() strips it when the origin changes.
513
+ if (!redirected || !getHeader(options.headers, 'authorization')) {
514
+ // will remove if we don't have a token.
515
+ options.headers = addHeader(options.headers, 'authorization', await getTokenByURL(String(u), this.identity));
516
+ }
494
517
  let response = null;
495
518
  try {
496
519
  response = await this.agent.request(options);
@@ -523,11 +546,22 @@ export class RegistryClient {
523
546
  statusCode: response.statusCode,
524
547
  durationMs: Date.now() - requestStart,
525
548
  });
526
- if (result.getHeader('integrity')) {
527
- trustIntegrity = true;
549
+ // a server-sent integrity header is not evidence: only the caller's
550
+ // expectation, or a body read back from the cache, is trusted. the
551
+ // header is dropped so it can never be stored as the entry's hash.
552
+ if (!trustIntegrity && !result.fromCache) {
553
+ result.deleteHeader('integrity');
554
+ if (result.isGzip)
555
+ result.checkIntegrity({ url });
528
556
  }
529
- if (result.isGzip && !trustIntegrity) {
530
- result.checkIntegrity({ url });
557
+ // same for the digest the server labels an unlabelled artifact with.
558
+ // before the cache write below, or a rejected body would be served
559
+ // from the cache on the next run, unverified.
560
+ if (verifyDigest &&
561
+ !integrity &&
562
+ !result.fromCache &&
563
+ result.statusCode === 200) {
564
+ result.checkDigest(verifyDigest === 'required', { url });
531
565
  }
532
566
  // a forced revalidation must never replace a cached entry with an
533
567
  // error response -- the flat 200-only rule revalidate-entry.ts has.
@@ -539,11 +573,16 @@ export class RegistryClient {
539
573
  // still gets written back.
540
574
  const clobbersCachedEntry = forceRevalidate && !!entry && result.statusCode !== 200;
541
575
  if (useCache && !clobbersCachedEntry) {
542
- // Get the encoded buffer from the cache entry
576
+ // content-address an artifact the caller had no expected hash for,
577
+ // so a later lookup by hash still finds it; packuments are not
578
+ // worth hashing. integrityActual also records the hash in the
579
+ // entry's headers, so it runs before encode().
580
+ const integrity = result.integrity ??
581
+ (result.statusCode === 200 && !result.isJSON ?
582
+ result.integrityActual
583
+ : undefined);
543
584
  const buffer = result.encode();
544
- this.cache.set(key, Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength), {
545
- integrity: result.integrity,
546
- });
585
+ this.cache.set(key, Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength), { integrity });
547
586
  }
548
587
  return result;
549
588
  }
package/dist/otplease.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { error } from '@vltpkg/error-cause';
2
+ import { tokenRefusal } from "./registry-error.js";
2
3
  import { getWebAuthChallenge } from "./web-auth-challenge.js";
3
4
  import { urlOpen } from '@vltpkg/url-open';
4
5
  import { createInterface } from 'node:readline/promises';
@@ -71,6 +72,13 @@ export const otplease = async (client, options, response) => {
71
72
  });
72
73
  }
73
74
  if (wwwAuth.has('bearer')) {
75
+ // A token the registry says is dead explains itself in the body, so hand
76
+ // it back to be rendered like any other 401. Every other bearer challenge
77
+ // -- npm's own registry sends one with no body -- keeps the generic line.
78
+ const text = await responseBodyText(response).catch(() => '');
79
+ if (tokenRefusal({ statusCode: 401, text: () => text })) {
80
+ return { bodyConsumed: text };
81
+ }
74
82
  throw error('Missing or invalid authentication token. Run `vlt login` or `vlt token add` to authenticate.', {
75
83
  code: 'ENEEDAUTH',
76
84
  status: response.statusCode,
@@ -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
@@ -19,6 +19,14 @@ export type ErrorResponse = {
19
19
  * decoded, and to the raw body text when it is not JSON.
20
20
  */
21
21
  export declare const registryErrorMessage: (response: ErrorResponse) => string;
22
+ /** How a 401 says the token it refused died, if it does. */
23
+ export declare const tokenRefusal: (response: unknown) => "expired" | "revoked" | undefined;
24
+ /**
25
+ * What to do about a 401 that says the token expired or was revoked, or
26
+ * `undefined` for every other response. The account is the first path segment
27
+ * of any request to a vlt registry, and one token covers every registry on it.
28
+ */
29
+ export declare const tokenRefusalAdvice: (response: unknown, url?: URL | string) => string | undefined;
22
30
  export type AssertOkOptions = {
23
31
  /** what we were trying to do, eg `'Failed to list dist-tags'` */
24
32
  message: string;
@@ -15,10 +15,7 @@ const stripTags = (s) => s
15
15
  .replace(/<[^>]*>/g, ' ')
16
16
  .replace(/\s+/g, ' ')
17
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) => {
18
+ const parseBody = (text) => {
22
19
  let body;
23
20
  try {
24
21
  body = JSON.parse(text);
@@ -27,9 +24,17 @@ const detailFromJSON = (text) => {
27
24
  // A non-JSON body is itself the most useful detail.
28
25
  return undefined;
29
26
  }
30
- if (!body || typeof body !== 'object')
27
+ return !body || typeof body !== 'object' ?
28
+ undefined
29
+ : body;
30
+ };
31
+ // npm writes `{"error":"..."}`; the `-/npm/v1/*` endpoints and several
32
+ // third-party registries write `{"message":"..."}`; a few nest it under
33
+ // `error.message`.
34
+ const detailFromJSON = (text) => {
35
+ const rec = parseBody(text);
36
+ if (!rec)
31
37
  return undefined;
32
- const rec = body;
33
38
  const nested = rec.error;
34
39
  for (const v of [rec.error, rec.message, nested?.message]) {
35
40
  if (typeof v === 'string' && v.trim())
@@ -60,6 +65,54 @@ export const registryErrorMessage = (response) => {
60
65
  const detail = detailFromJSON(text) ?? (isHTML(text) ? stripTags(text) : text);
61
66
  return detail ? `${status} — ${truncate(detail)}` : status;
62
67
  };
68
+ /** What a vlt registry calls the two 401s a client can resolve on its own. */
69
+ const refusals = {
70
+ TokenExpiredError: 'expired',
71
+ TokenRevokedError: 'revoked',
72
+ };
73
+ /** vlt.io account and organization slugs, as the registry mints them. */
74
+ const accountSlug = /^(?=.{3,63}$)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
75
+ /** How a 401 says the token it refused died, if it does. */
76
+ export const tokenRefusal = (response) => {
77
+ // a CacheEntry, a node:http message, or a bare object off an error's cause
78
+ // bag; `isObject` would refuse the class instances
79
+ const res = response;
80
+ if (typeof res !== 'object' || res?.statusCode !== 401)
81
+ return undefined;
82
+ let text = '';
83
+ try {
84
+ if (typeof res.text === 'function')
85
+ text = res.text();
86
+ }
87
+ catch {
88
+ // an undecodable body (bad gzip) says nothing either way
89
+ return undefined;
90
+ }
91
+ const code = parseBody(text)?.code;
92
+ return typeof code === 'string' ? refusals[code] : undefined;
93
+ };
94
+ /**
95
+ * What to do about a 401 that says the token expired or was revoked, or
96
+ * `undefined` for every other response. The account is the first path segment
97
+ * of any request to a vlt registry, and one token covers every registry on it.
98
+ */
99
+ export const tokenRefusalAdvice = (response, url) => {
100
+ const gone = tokenRefusal(response);
101
+ if (!gone || url === undefined)
102
+ return undefined;
103
+ let account;
104
+ try {
105
+ account = new URL(String(url)).pathname.split('/')[1];
106
+ }
107
+ catch {
108
+ return undefined;
109
+ }
110
+ if (!account || !accountSlug.test(account))
111
+ return undefined;
112
+ return (`Your token for the "${account}" account ` +
113
+ `${gone === 'expired' ? 'has expired' : 'was revoked'}. Run ` +
114
+ `\`vlt setup ${account}\` to log in again.`);
115
+ };
63
116
  /**
64
117
  * Throw a well-formed, user-facing error when a registry response is not
65
118
  * a 2xx.
@@ -76,7 +129,9 @@ export const registryErrorMessage = (response) => {
76
129
  const registryError = (response, { message, url, method = 'GET', advice }, from, cause) => {
77
130
  const { statusCode } = response;
78
131
  const denied = statusCode === 401 || statusCode === 403;
79
- const extra = advice?.(statusCode);
132
+ // A diagnosis off the response stands in for the caller's generic 401 line.
133
+ const refused = tokenRefusalAdvice(response, url);
134
+ const extra = refused ?? advice?.(statusCode);
80
135
  const tips = (Array.isArray(extra) ? extra : [extra]).filter((t) => !!t);
81
136
  const warn = tips.map(t => `\n⚠️ ${t}`).join('');
82
137
  return error(`${message}: ${registryErrorMessage(response)}${warn}`, {
@@ -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) => {
@@ -0,0 +1,2 @@
1
+ /** Global store root under the cache folder `cache`. */
2
+ export declare const storeRoot: (cache: string) => string;
@@ -0,0 +1,3 @@
1
+ import { resolve } from 'node:path';
2
+ /** Global store root under the cache folder `cache`. */
3
+ export const storeRoot = (cache) => resolve(cache, 'store', 'v1');
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.1.0",
4
+ "version": "1.2.0",
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.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",
16
+ "@vltpkg/cache": "1.2.0",
17
+ "@vltpkg/cache-unzip": "1.2.0",
18
+ "@vltpkg/error-cause": "1.2.0",
19
+ "@vltpkg/keychain": "1.2.0",
20
+ "@vltpkg/output": "1.2.0",
21
+ "@vltpkg/types": "1.2.0",
22
+ "@vltpkg/url-open": "1.2.0",
23
+ "@vltpkg/user-agent": "1.2.0",
24
+ "@vltpkg/xdg": "1.2.0",
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": {
@@ -30,7 +30,7 @@
30
30
  "@types/node": "^22.19.2",
31
31
  "eslint": "^9.39.1",
32
32
  "prettier": "^3.7.4",
33
- "tap": "^21.5.0",
33
+ "tap": "^21.8.0",
34
34
  "typedoc": "~0.27.9",
35
35
  "typescript": "5.7.3",
36
36
  "typescript-eslint": "^8.49.0"
@@ -72,6 +72,11 @@
72
72
  "import": {
73
73
  "default": "./dist/registry-error.js"
74
74
  }
75
+ },
76
+ "./store-root": {
77
+ "import": {
78
+ "default": "./dist/store-root.js"
79
+ }
75
80
  }
76
81
  },
77
82
  "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;