@vltpkg/registry-client 1.1.1 → 1.3.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
@@ -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.
package/dist/index.d.ts CHANGED
@@ -11,15 +11,22 @@ import { assertOk, registryErrorMessage, requestError } from './registry-error.t
11
11
  import type { ErrorResponse } from './registry-error.ts';
12
12
  import type { TokenResponse } from './token-response.ts';
13
13
  import type { WebAuthChallenge } from './web-auth-challenge.ts';
14
+ import { storeRoot } from './store-root.ts';
14
15
  import { oidc } from './oidc.ts';
15
16
  import type { OidcOptions } from './oidc.ts';
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, };
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, };
17
18
  /** A response body read straight out of the cache file. */
18
19
  export type CachedBody = {
19
20
  /** the cache file it came from */
20
21
  path: string;
22
+ /** the cache key of the request */
23
+ key: string;
21
24
  /** the body, a view into the file's bytes */
22
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;
23
30
  };
24
31
  export type CacheableMethod = 'GET' | 'HEAD';
25
32
  export declare const isCacheableMethod: (m: unknown) => m is CacheableMethod;
@@ -31,6 +38,8 @@ export type RegistryClientOptions = {
31
38
  * Defaults to the XDG cache folder for `vlt/registry-client`
32
39
  */
33
40
  cache?: string;
41
+ /** Global store root. Defaults to {@link storeRoot} of `cache`. */
42
+ storeRoot?: string;
34
43
  /**
35
44
  * Number of retries to perform when encountering network errors or
36
45
  * likely-transient errors from git hosts.
@@ -86,6 +95,13 @@ export type RegistryClientRequestOptions = Omit<Dispatcher.RequestOptions, 'meth
86
95
  * also serves the tarball itself.
87
96
  */
88
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';
89
105
  /**
90
106
  * Follow up to 10 redirections by default. Set this to 0 to just return
91
107
  * the 3xx response. If the max redirections are expired, and we still get
@@ -187,5 +203,12 @@ export declare class RegistryClient {
187
203
  integrity?: Integrity;
188
204
  method?: CacheableMethod;
189
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;
190
213
  request(url: URL | string, options?: RegistryClientRequestOptions): Promise<CacheEntry>;
191
214
  }
package/dist/index.js CHANGED
@@ -7,7 +7,6 @@ import { urlOpen } from '@vltpkg/url-open';
7
7
  import { XDG } from '@vltpkg/xdg';
8
8
  import { randomUUID } from 'node:crypto';
9
9
  import { readFileSync } from 'node:fs';
10
- import { STATUS_CODES } from 'node:http';
11
10
  import { availableParallelism } from 'node:os';
12
11
  import { dirname, resolve } from 'node:path';
13
12
  import { setTimeout } from 'node:timers/promises';
@@ -22,15 +21,16 @@ import { handleCacheHitResponse } from "./handle-304-response.js";
22
21
  import { otplease } from "./otplease.js";
23
22
  import { getDispatcher } from "./proxy.js";
24
23
  import { isRedirect, redirect } from "./redirect.js";
25
- import { assertOk, registryErrorMessage, requestError, } from "./registry-error.js";
24
+ import { assertOk, registryErrorMessage, requestError, statusText, } from "./registry-error.js";
26
25
  import { setCacheHeaders } from "./set-cache-headers.js";
27
26
  import { getTokenResponse } from "./token-response.js";
28
27
  import { getWebAuthChallenge } from "./web-auth-challenge.js";
29
28
  import { collectHeaders, readBody } from "./response.js";
29
+ import { storeRoot } from "./store-root.js";
30
30
  import { oidc } from "./oidc.js";
31
31
  // eslint-disable-next-line no-console
32
32
  const log = (msg) => console.error(msg);
33
- export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, requestError, runtimeTokens, setRuntimeToken, setToken, };
33
+ export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, requestError, runtimeTokens, setRuntimeToken, setToken, storeRoot, };
34
34
  export const isCacheableMethod = (m) => m === 'GET' || m === 'HEAD';
35
35
  export const cacheKey = (method, url) => `${method !== 'GET' ? method + ' ' : ''}${url}`;
36
36
  /**
@@ -91,12 +91,15 @@ export class RegistryClient {
91
91
  this.identity = identity;
92
92
  this.staleWhileRevalidateFactor = staleWhileRevalidateFactor;
93
93
  const path = resolve(cache, 'registry-client');
94
+ const store = options.storeRoot ?? storeRoot(cache);
94
95
  this.cache = new Cache({
95
96
  path,
97
+ store,
96
98
  maxSize: parseCacheMaxSize(process.env.VLT_CACHE_MAX_SIZE),
97
99
  onDiskWrite(_path, key, data) {
98
- if (CacheEntry.isGzipEntry(data)) {
99
- cacheUnzipRegister(path, key);
100
+ if (CacheEntry.isGzipEntry(data) ||
101
+ CacheEntry.isTarballEntry(data)) {
102
+ cacheUnzipRegister(path, key, store);
100
103
  }
101
104
  },
102
105
  });
@@ -136,7 +139,7 @@ export class RegistryClient {
136
139
  catch {
137
140
  // Registries and proxies can return plain text or HTML errors.
138
141
  }
139
- const status = STATUS_CODES[statusCode];
142
+ const status = statusText(statusCode);
140
143
  throw error(`Failed to fetch paginated results: ${statusCode}${status ? ` ${status}` : ''}${typeof detail === 'string' && detail ? `: ${detail}` : ''}`, { code: 'EREQUEST', status: statusCode, url: String(url) });
141
144
  }
142
145
  let body;
@@ -282,7 +285,7 @@ export class RegistryClient {
282
285
  }
283
286
  // TODO: fall back to username/password login, and/or couchdb PUT login
284
287
  const { statusCode } = response;
285
- const status = STATUS_CODES[statusCode];
288
+ const status = statusText(statusCode);
286
289
  throw error(`Failed to perform web login: ${statusCode}${status ? ` ${status}` : ''}`, {
287
290
  code: 'EREQUEST',
288
291
  url: webLoginURL,
@@ -401,7 +404,11 @@ export class RegistryClient {
401
404
  // disk underneath it -- benign, tarball urls are immutable.)
402
405
  if (this.cache.peek(key))
403
406
  return undefined;
404
- // same order as the cache's own disk read
407
+ // a pin reads only the integrity path: cache.set hardlinks every
408
+ // artifact under its hash, while the key holds whatever was last
409
+ // fetched from that url. nothing here hashes the body, so a miss
410
+ // -- which sends the caller to request(), which verifies -- is
411
+ // the safe answer.
405
412
  const paths = new Set();
406
413
  try {
407
414
  const i = this.cache.integrityPath(integrity);
@@ -409,7 +416,8 @@ export class RegistryClient {
409
416
  paths.add(i);
410
417
  }
411
418
  catch { }
412
- paths.add(this.cache.path(key));
419
+ if (!integrity)
420
+ paths.add(this.cache.path(key));
413
421
  for (const path of paths) {
414
422
  let buf;
415
423
  try {
@@ -428,17 +436,32 @@ export class RegistryClient {
428
436
  entry.isJSON) {
429
437
  continue;
430
438
  }
431
- return { path, body: entry.buffer() };
439
+ return {
440
+ path,
441
+ key,
442
+ body: entry.buffer(),
443
+ integrity: entry.integrity,
444
+ gzip: CacheEntry.isGzipEntry(buf),
445
+ };
432
446
  }
433
447
  /* c8 ignore next */
434
448
  }
435
449
  catch { }
436
450
  return undefined;
437
451
  }
452
+ /**
453
+ * Queue the cached tarball at `key` (a {@link CachedBody} key) for the
454
+ * background child: exploded into the global store when that is on,
455
+ * else un-gzipped. `integrity` finds it when only the integrity path
456
+ * holds it.
457
+ */
458
+ queueForStore(key, integrity) {
459
+ cacheUnzipRegister(this.cache.path(), key, this.cache.store, integrity);
460
+ }
438
461
  async request(url, options = {}) {
439
462
  const u = typeof url === 'string' ? new URL(url) : url;
440
463
  const { method = 'GET', integrity, redirections = new Set(), signal, otp = (process.env.VLT_OTP ?? '').trim(), staleWhileRevalidate = true, forceRevalidate = false, } = options;
441
- let { trustIntegrity } = options;
464
+ const { trustIntegrity, verifyDigest } = options;
442
465
  const m = isCacheableMethod(method) ? method : undefined;
443
466
  const { useCache = !!m } = options;
444
467
  signal?.throwIfAborted();
@@ -527,11 +550,34 @@ export class RegistryClient {
527
550
  statusCode: response.statusCode,
528
551
  durationMs: Date.now() - requestStart,
529
552
  });
530
- if (result.getHeader('integrity')) {
531
- trustIntegrity = true;
553
+ // a server-sent integrity header is not evidence: only the caller's
554
+ // expectation, or a body read back from the cache, is trusted. the
555
+ // header is dropped so it can never be stored as the entry's hash.
556
+ //
557
+ // the check has to happen here, before the cache write below, or a
558
+ // body that fails it is still stored under the hash it was supposed
559
+ // to have -- and served from there, unverified, on the next run.
560
+ // `!fromCache` is the whole precondition: only a cached entry can
561
+ // have been rewritten (cache-unzip un-gzips in place), so anything
562
+ // else is the bytes as they came off the wire and hashes as such.
563
+ // this used to also require `isGzip`, which was a proxy for that
564
+ // and silently exempted every artifact that is not gzip -- a
565
+ // `.tar.br` among them.
566
+ if (!trustIntegrity && !result.fromCache) {
567
+ result.deleteHeader('integrity');
568
+ // 200 only: an error body is not the artifact and was never
569
+ // supposed to hash to it, and it is not what gets cached either.
570
+ if (result.statusCode === 200)
571
+ result.checkIntegrity({ url });
532
572
  }
533
- if (result.isGzip && !trustIntegrity) {
534
- result.checkIntegrity({ url });
573
+ // same for the digest the server labels an unlabelled artifact with.
574
+ // before the cache write below, or a rejected body would be served
575
+ // from the cache on the next run, unverified.
576
+ if (verifyDigest &&
577
+ !integrity &&
578
+ !result.fromCache &&
579
+ result.statusCode === 200) {
580
+ result.checkDigest(verifyDigest === 'required', { url });
535
581
  }
536
582
  // a forced revalidation must never replace a cached entry with an
537
583
  // error response -- the flat 200-only rule revalidate-entry.ts has.
@@ -543,11 +589,16 @@ export class RegistryClient {
543
589
  // still gets written back.
544
590
  const clobbersCachedEntry = forceRevalidate && !!entry && result.statusCode !== 200;
545
591
  if (useCache && !clobbersCachedEntry) {
546
- // Get the encoded buffer from the cache entry
592
+ // content-address an artifact the caller had no expected hash for,
593
+ // so a later lookup by hash still finds it; packuments are not
594
+ // worth hashing. integrityActual also records the hash in the
595
+ // entry's headers, so it runs before encode().
596
+ const integrity = result.integrity ??
597
+ (result.statusCode === 200 && !result.isJSON ?
598
+ result.integrityActual
599
+ : undefined);
547
600
  const buffer = result.encode();
548
- this.cache.set(key, Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength), {
549
- integrity: result.integrity,
550
- });
601
+ this.cache.set(key, Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength), { integrity });
551
602
  }
552
603
  return result;
553
604
  }
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,
@@ -11,6 +11,7 @@ export type ErrorResponse = {
11
11
  text?: () => string;
12
12
  [k: number | string | symbol]: any;
13
13
  };
14
+ export declare const statusText: (code: number) => string | undefined;
14
15
  /**
15
16
  * Format a non-2xx registry response as `"403 Forbidden — <detail>"`,
16
17
  * where the detail is whatever the registry actually said.
@@ -19,6 +20,14 @@ export type ErrorResponse = {
19
20
  * decoded, and to the raw body text when it is not JSON.
20
21
  */
21
22
  export declare const registryErrorMessage: (response: ErrorResponse) => string;
23
+ /** How a 401 says the token it refused died, if it does. */
24
+ export declare const tokenRefusal: (response: unknown) => "expired" | "revoked" | undefined;
25
+ /**
26
+ * What to do about a 401 that says the token expired or was revoked, or
27
+ * `undefined` for every other response. The account is the first path segment
28
+ * of any request to a vlt registry, and one token covers every registry on it.
29
+ */
30
+ export declare const tokenRefusalAdvice: (response: unknown, url?: URL | string) => string | undefined;
22
31
  export type AssertOkOptions = {
23
32
  /** what we were trying to do, eg `'Failed to list dist-tags'` */
24
33
  message: string;
@@ -1,6 +1,7 @@
1
1
  import { error } from '@vltpkg/error-cause';
2
2
  import { asError, isObject } from '@vltpkg/types';
3
- import { STATUS_CODES } from 'node:http';
3
+ // read on use: a static node:http import loads undici, http2, tls at startup
4
+ export const statusText = (code) => process.getBuiltinModule('node:http').STATUS_CODES[code];
4
5
  /** longest registry-supplied detail spliced into an error message */
5
6
  const MAX_DETAIL_LENGTH = 512;
6
7
  const truncate = (s) => s.length <= MAX_DETAIL_LENGTH ?
@@ -15,10 +16,7 @@ const stripTags = (s) => s
15
16
  .replace(/<[^>]*>/g, ' ')
16
17
  .replace(/\s+/g, ' ')
17
18
  .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) => {
19
+ const parseBody = (text) => {
22
20
  let body;
23
21
  try {
24
22
  body = JSON.parse(text);
@@ -27,9 +25,17 @@ const detailFromJSON = (text) => {
27
25
  // A non-JSON body is itself the most useful detail.
28
26
  return undefined;
29
27
  }
30
- if (!body || typeof body !== 'object')
28
+ return !body || typeof body !== 'object' ?
29
+ undefined
30
+ : body;
31
+ };
32
+ // npm writes `{"error":"..."}`; the `-/npm/v1/*` endpoints and several
33
+ // third-party registries write `{"message":"..."}`; a few nest it under
34
+ // `error.message`.
35
+ const detailFromJSON = (text) => {
36
+ const rec = parseBody(text);
37
+ if (!rec)
31
38
  return undefined;
32
- const rec = body;
33
39
  const nested = rec.error;
34
40
  for (const v of [rec.error, rec.message, nested?.message]) {
35
41
  if (typeof v === 'string' && v.trim())
@@ -45,7 +51,7 @@ const detailFromJSON = (text) => {
45
51
  * decoded, and to the raw body text when it is not JSON.
46
52
  */
47
53
  export const registryErrorMessage = (response) => {
48
- const statusMessage = STATUS_CODES[response.statusCode];
54
+ const statusMessage = statusText(response.statusCode);
49
55
  const status = `${response.statusCode}${statusMessage ? ` ${statusMessage}` : ''}`;
50
56
  let text;
51
57
  try {
@@ -60,6 +66,54 @@ export const registryErrorMessage = (response) => {
60
66
  const detail = detailFromJSON(text) ?? (isHTML(text) ? stripTags(text) : text);
61
67
  return detail ? `${status} — ${truncate(detail)}` : status;
62
68
  };
69
+ /** What a vlt registry calls the two 401s a client can resolve on its own. */
70
+ const refusals = {
71
+ TokenExpiredError: 'expired',
72
+ TokenRevokedError: 'revoked',
73
+ };
74
+ /** vlt.io account and organization slugs, as the registry mints them. */
75
+ const accountSlug = /^(?=.{3,63}$)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
76
+ /** How a 401 says the token it refused died, if it does. */
77
+ export const tokenRefusal = (response) => {
78
+ // a CacheEntry, a node:http message, or a bare object off an error's cause
79
+ // bag; `isObject` would refuse the class instances
80
+ const res = response;
81
+ if (typeof res !== 'object' || res?.statusCode !== 401)
82
+ return undefined;
83
+ let text = '';
84
+ try {
85
+ if (typeof res.text === 'function')
86
+ text = res.text();
87
+ }
88
+ catch {
89
+ // an undecodable body (bad gzip) says nothing either way
90
+ return undefined;
91
+ }
92
+ const code = parseBody(text)?.code;
93
+ return typeof code === 'string' ? refusals[code] : undefined;
94
+ };
95
+ /**
96
+ * What to do about a 401 that says the token expired or was revoked, or
97
+ * `undefined` for every other response. The account is the first path segment
98
+ * of any request to a vlt registry, and one token covers every registry on it.
99
+ */
100
+ export const tokenRefusalAdvice = (response, url) => {
101
+ const gone = tokenRefusal(response);
102
+ if (!gone || url === undefined)
103
+ return undefined;
104
+ let account;
105
+ try {
106
+ account = new URL(String(url)).pathname.split('/')[1];
107
+ }
108
+ catch {
109
+ return undefined;
110
+ }
111
+ if (!account || !accountSlug.test(account))
112
+ return undefined;
113
+ return (`Your token for the "${account}" account ` +
114
+ `${gone === 'expired' ? 'has expired' : 'was revoked'}. Run ` +
115
+ `\`vlt setup ${account}\` to log in again.`);
116
+ };
63
117
  /**
64
118
  * Throw a well-formed, user-facing error when a registry response is not
65
119
  * a 2xx.
@@ -76,7 +130,9 @@ export const registryErrorMessage = (response) => {
76
130
  const registryError = (response, { message, url, method = 'GET', advice }, from, cause) => {
77
131
  const { statusCode } = response;
78
132
  const denied = statusCode === 401 || statusCode === 403;
79
- const extra = advice?.(statusCode);
133
+ // A diagnosis off the response stands in for the caller's generic 401 line.
134
+ const refused = tokenRefusalAdvice(response, url);
135
+ const extra = refused ?? advice?.(statusCode);
80
136
  const tips = (Array.isArray(extra) ? extra : [extra]).filter((t) => !!t);
81
137
  const warn = tips.map(t => `\n⚠️ ${t}`).join('');
82
138
  return error(`${message}: ${registryErrorMessage(response)}${warn}`, {
@@ -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.1",
4
+ "version": "1.3.0",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/vltpkg/vltpkg.git",
@@ -13,15 +13,15 @@
13
13
  "url": "http://vlt.sh"
14
14
  },
15
15
  "dependencies": {
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",
16
+ "@vltpkg/cache": "1.3.0",
17
+ "@vltpkg/cache-unzip": "1.3.0",
18
+ "@vltpkg/error-cause": "1.3.0",
19
+ "@vltpkg/keychain": "1.3.0",
20
+ "@vltpkg/output": "1.3.0",
21
+ "@vltpkg/types": "1.3.0",
22
+ "@vltpkg/url-open": "1.3.0",
23
+ "@vltpkg/user-agent": "1.3.0",
24
+ "@vltpkg/xdg": "1.3.0",
25
25
  "cache-control-parser": "^2.0.6",
26
26
  "undici": "^7.16.0"
27
27
  },
@@ -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": [