@vltpkg/registry-client 1.3.3 → 1.3.4

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.
@@ -101,7 +101,9 @@ export declare class CacheEntry {
101
101
  * Note that this will *usually* not be true if the value is coming out of
102
102
  * the cache, because cache entries not exploded into the global store are
103
103
  * un-gzipped in place. It should _only_ be called for artifacts that come
104
- * from an actual http response.
104
+ * from an actual http response, whatever its encoding: an identity body
105
+ * is hashed as it came, a gzipped one before anything un-gzips it in
106
+ * memory.
105
107
  *
106
108
  * Returns true if anything was actually verified.
107
109
  */
@@ -118,6 +120,16 @@ export declare class CacheEntry {
118
120
  * **Will throw** on a mismatch. Returns the hash of the body.
119
121
  */
120
122
  checkDigest(required: boolean, context?: ErrorCauseOptions): Integrity;
123
+ /**
124
+ * The hash of the body un-gzipped, or of the body itself if it is not
125
+ * gzipped, without un-gzipping the entry. Bounded like {@link unzip},
126
+ * and throws like it on a body that will not un-gzip.
127
+ *
128
+ * Never the hash to record for an artifact, which is the hash of its
129
+ * bytes as served. It pins the same content, though, and is what a
130
+ * body hashed after something un-gzipped it was pinned with.
131
+ */
132
+ unzippedIntegrity(): Integrity;
121
133
  get integrityActual(): Integrity;
122
134
  set integrityActual(i: Integrity);
123
135
  set integrity(i: Integrity | undefined);
@@ -150,6 +162,26 @@ export declare class CacheEntry {
150
162
  buffer(): Buffer;
151
163
  get body(): Uint8Array | Record<string, any>;
152
164
  get isJSON(): boolean;
165
+ /**
166
+ * Label a 200 network body that is not json and came with no
167
+ * content-type `application/octet-stream`, the way the json sniff
168
+ * labels json `text/json`.
169
+ *
170
+ * The label says the hash the entry is stored under is the hash of
171
+ * its bytes as served, checked or recorded by
172
+ * `RegistryClient.request()`. So it is applied only where that is
173
+ * known, right before such an entry is stored, and never by the
174
+ * sniff: an entry with no content-type read back from the cache is
175
+ * not known to be one.
176
+ *
177
+ * A decoded entry, an error body, an empty body, json, and a body
178
+ * served with a content-type are left as they are. Not an error body
179
+ * or an empty one: a content-type that is not json makes an entry
180
+ * immutable (see {@link valid}), which neither was when served with
181
+ * none, and no artifact is empty. The length is checked after the
182
+ * sniff, which un-gzips a body with no content-type.
183
+ */
184
+ labelArtifact(): void;
153
185
  get isGzip(): boolean;
154
186
  /**
155
187
  * Un-gzip encode the body.
@@ -295,7 +295,9 @@ export class CacheEntry {
295
295
  * Note that this will *usually* not be true if the value is coming out of
296
296
  * the cache, because cache entries not exploded into the global store are
297
297
  * un-gzipped in place. It should _only_ be called for artifacts that come
298
- * from an actual http response.
298
+ * from an actual http response, whatever its encoding: an identity body
299
+ * is hashed as it came, a gzipped one before anything un-gzips it in
300
+ * memory.
299
301
  *
300
302
  * Returns true if anything was actually verified.
301
303
  */
@@ -336,12 +338,27 @@ export class CacheEntry {
336
338
  }
337
339
  return computed;
338
340
  }
341
+ #hash(body = this._body) {
342
+ const hash = createHash('sha512');
343
+ hash.update(body);
344
+ return `sha512-${hash.digest('base64')}`;
345
+ }
346
+ /**
347
+ * The hash of the body un-gzipped, or of the body itself if it is not
348
+ * gzipped, without un-gzipping the entry. Bounded like {@link unzip},
349
+ * and throws like it on a body that will not un-gzip.
350
+ *
351
+ * Never the hash to record for an artifact, which is the hash of its
352
+ * bytes as served. It pins the same content, though, and is what a
353
+ * body hashed after something un-gzipped it was pinned with.
354
+ */
355
+ unzippedIntegrity() {
356
+ return this.#hash(this.isGzip ? this.#gunzip() : this._body);
357
+ }
339
358
  get integrityActual() {
340
359
  if (this.#integrityActual)
341
360
  return this.#integrityActual;
342
- const hash = createHash('sha512');
343
- hash.update(this._body);
344
- const i = `sha512-${hash.digest('base64')}`;
361
+ const i = this.#hash();
345
362
  this.integrityActual = i;
346
363
  return i;
347
364
  }
@@ -433,6 +450,16 @@ export class CacheEntry {
433
450
  // don't cache, because we might just not have it yet.
434
451
  if (!this._body.length)
435
452
  return false;
453
+ // the sniff un-gzips the body in place. hash a gzipped network body
454
+ // first, so a tarball served without a content-type is recorded
455
+ // under the hash of the bytes every other fetch of it gets, not of
456
+ // the un-gzipped copy only this cache holds. an identity body is
457
+ // left as it is, and the cache write hashes it as it came; a body
458
+ // already un-gzipped in memory is not the wire bytes any more, so
459
+ // no hash of it is ever recorded.
460
+ const wire = !this.#fromCache && !this.#integrityActual && this.isGzip ?
461
+ this.#hash()
462
+ : undefined;
436
463
  this.unzip();
437
464
  const buf = this._body;
438
465
  if (!buf.length)
@@ -441,8 +468,39 @@ export class CacheEntry {
441
468
  this.#isJSON = buf[0] === 0x7b;
442
469
  if (this.#isJSON)
443
470
  this.setHeader('content-type', 'text/json');
471
+ else if (wire)
472
+ this.integrityActual = wire;
444
473
  return this.#isJSON;
445
474
  }
475
+ /**
476
+ * Label a 200 network body that is not json and came with no
477
+ * content-type `application/octet-stream`, the way the json sniff
478
+ * labels json `text/json`.
479
+ *
480
+ * The label says the hash the entry is stored under is the hash of
481
+ * its bytes as served, checked or recorded by
482
+ * `RegistryClient.request()`. So it is applied only where that is
483
+ * known, right before such an entry is stored, and never by the
484
+ * sniff: an entry with no content-type read back from the cache is
485
+ * not known to be one.
486
+ *
487
+ * A decoded entry, an error body, an empty body, json, and a body
488
+ * served with a content-type are left as they are. Not an error body
489
+ * or an empty one: a content-type that is not json makes an entry
490
+ * immutable (see {@link valid}), which neither was when served with
491
+ * none, and no artifact is empty. The length is checked after the
492
+ * sniff, which un-gzips a body with no content-type.
493
+ */
494
+ labelArtifact() {
495
+ if (this.#fromCache ||
496
+ this.#statusCode !== 200 ||
497
+ this.isJSON ||
498
+ this.getHeaderString('content-type') ||
499
+ !this.#bodyLength) {
500
+ return;
501
+ }
502
+ this.setHeader('content-type', 'application/octet-stream');
503
+ }
446
504
  #isGzip;
447
505
  get isGzip() {
448
506
  if (this.#isGzip !== undefined)
@@ -463,6 +521,29 @@ export class CacheEntry {
463
521
  }
464
522
  return this.#isGzip;
465
523
  }
524
+ // the body un-gzipped, for a body known to be gzipped
525
+ #gunzip() {
526
+ // we know that if we know it's gzip, that the body has been
527
+ // flattened to a single buffer, so save the extra call.
528
+ /* c8 ignore start */
529
+ if (this._body.length === 0)
530
+ throw error('Invalid buffer, cant unzip');
531
+ /* c8 ignore stop */
532
+ const max = Math.min(maxUnpackedBytes, this._body.length * MAX_DECOMPRESSION_RATIO);
533
+ try {
534
+ return gunzipSync(this._body, { maxOutputLength: max });
535
+ }
536
+ catch (er) {
537
+ throw (er.code ===
538
+ 'ERR_BUFFER_TOO_LARGE') ?
539
+ error('cache entry exceeds maximum unpacked size', {
540
+ found: this._body.length,
541
+ max,
542
+ cause: er,
543
+ })
544
+ : er;
545
+ }
546
+ }
466
547
  /**
467
548
  * Un-gzip encode the body.
468
549
  * Returns true if it was previously gzip (so something was done), otherwise
@@ -470,27 +551,7 @@ export class CacheEntry {
470
551
  */
471
552
  unzip() {
472
553
  if (this.isGzip) {
473
- // we know that if we know it's gzip, that the body has been
474
- // flattened to a single buffer, so save the extra call.
475
- /* c8 ignore start */
476
- if (this._body.length === 0)
477
- throw error('Invalid buffer, cant unzip');
478
- /* c8 ignore stop */
479
- const max = Math.min(maxUnpackedBytes, this._body.length * MAX_DECOMPRESSION_RATIO);
480
- let b;
481
- try {
482
- b = gunzipSync(this._body, { maxOutputLength: max });
483
- }
484
- catch (er) {
485
- throw (er.code ===
486
- 'ERR_BUFFER_TOO_LARGE') ?
487
- error('cache entry exceeds maximum unpacked size', {
488
- found: this._body.length,
489
- max,
490
- cause: er,
491
- })
492
- : er;
493
- }
554
+ const b = this.#gunzip();
494
555
  this.setHeader('content-encoding', 'identity');
495
556
  const u8 = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
496
557
  this.#body = u8;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Cache } from '@vltpkg/cache';
2
2
  import type { Integrity } from '@vltpkg/types';
3
+ import type { Readable } from 'node:stream';
3
4
  import type { Dispatcher } from 'undici';
4
5
  import { RetryAgent } from 'undici';
5
6
  import { userAgent } from '@vltpkg/user-agent';
@@ -120,6 +121,18 @@ export type RegistryClientRequestOptions = Omit<Dispatcher.RequestOptions, 'meth
120
121
  * prevent storing the result to the cache.
121
122
  */
122
123
  useCache?: false;
124
+ /**
125
+ * Set to `false` to fetch from the network without looking in the
126
+ * cache first, on this url and on every url it redirects to, while
127
+ * still storing the result. No cached entry is served, stale or
128
+ * not, or revalidated, so nothing is sent conditionally either.
129
+ *
130
+ * Meant for an entry that cannot be trusted any more:
131
+ * `forceRevalidate` would still hand it back on a 304, and evicting
132
+ * it does not stop a redirect from reading the entry under the final
133
+ * url back instead.
134
+ */
135
+ readCache?: false;
123
136
  /**
124
137
  * Set to pass an `npm-otp` header on the request.
125
138
  *
@@ -227,5 +240,21 @@ export declare class RegistryClient {
227
240
  * holds it.
228
241
  */
229
242
  queueForStore(key: string, integrity?: Integrity): void;
243
+ /**
244
+ * Make a request and hand back the response body as it arrives, instead of
245
+ * buffering it into a {@link CacheEntry}. For a body a caller acts on line
246
+ * by line — the NDJSON the batch endpoints stream — waiting for the last
247
+ * byte is the difference between using the first record now and using it
248
+ * once the server has finished computing the last one.
249
+ *
250
+ * The body is gunzipped here when the registry compressed it, so a caller
251
+ * always reads what the server serialized. Nothing is cached and nothing is
252
+ * retried: a caller that loses the stream falls back to the requests it was
253
+ * avoiding.
254
+ */
255
+ requestStream(url: URL | string, options?: RegistryClientRequestOptions): Promise<{
256
+ statusCode: number;
257
+ body: Readable;
258
+ }>;
230
259
  request(url: URL | string, options?: RegistryClientRequestOptions): Promise<CacheEntry>;
231
260
  }
package/dist/index.js CHANGED
@@ -9,7 +9,9 @@ import { randomUUID } from 'node:crypto';
9
9
  import { closeSync, openSync, readFileSync, readSync } from 'node:fs';
10
10
  import { availableParallelism } from 'node:os';
11
11
  import { dirname, resolve } from 'node:path';
12
+ import { pipeline } from 'node:stream';
12
13
  import { setTimeout } from 'node:timers/promises';
14
+ import { createGunzip } from 'node:zlib';
13
15
  import { RetryAgent } from 'undici';
14
16
  import { userAgent } from '@vltpkg/user-agent';
15
17
  import { addHeader } from "./add-header.js";
@@ -506,18 +508,60 @@ export class RegistryClient {
506
508
  queueForStore(key, integrity) {
507
509
  cacheUnzipRegister(this.cache.path(), key, this.cache.store, integrity);
508
510
  }
511
+ /**
512
+ * Make a request and hand back the response body as it arrives, instead of
513
+ * buffering it into a {@link CacheEntry}. For a body a caller acts on line
514
+ * by line — the NDJSON the batch endpoints stream — waiting for the last
515
+ * byte is the difference between using the first record now and using it
516
+ * once the server has finished computing the last one.
517
+ *
518
+ * The body is gunzipped here when the registry compressed it, so a caller
519
+ * always reads what the server serialized. Nothing is cached and nothing is
520
+ * retried: a caller that loses the stream falls back to the requests it was
521
+ * avoiding.
522
+ */
523
+ async requestStream(url, options = {}) {
524
+ const u = typeof url === 'string' ? new URL(url) : url;
525
+ const o = {
526
+ ...options,
527
+ method: options.method ?? 'GET',
528
+ path: u.pathname.replace(/\/+$/, '') + u.search,
529
+ origin: u.origin,
530
+ headers: addHeader(addHeader(addHeader(options.headers, 'accept-encoding', 'gzip;q=1.0, identity;q=0.5'), 'user-agent', userAgent), 'npm-session', this.#session),
531
+ };
532
+ o.headers = addHeader(o.headers, 'authorization', await getTokenByURL(String(u), this.identity));
533
+ logRequest(url, 'start', { method: o.method });
534
+ const requestStart = Date.now();
535
+ const response = await this.agent.request(o);
536
+ logRequest(url, 'complete', {
537
+ method: o.method,
538
+ statusCode: response.statusCode,
539
+ durationMs: Date.now() - requestStart,
540
+ });
541
+ const encoding = response.headers['content-encoding'];
542
+ const gzipped = typeof encoding === 'string' && /\bgzip\b/.test(encoding);
543
+ let body = response.body;
544
+ if (gzipped) {
545
+ // a pipeline, so an error on the connection reaches whoever is
546
+ // reading the gunzipped body
547
+ const gunzip = createGunzip();
548
+ pipeline(response.body, gunzip, () => { });
549
+ body = gunzip;
550
+ }
551
+ return { statusCode: response.statusCode, body };
552
+ }
509
553
  async request(url, options = {}) {
510
554
  const u = typeof url === 'string' ? new URL(url) : url;
511
555
  const { method = 'GET', integrity, redirections = new Set(), signal, otp = (process.env.VLT_OTP ?? '').trim(), staleWhileRevalidate = true, forceRevalidate = false, } = options;
512
556
  const { trustIntegrity, verifyDigest } = options;
513
557
  const m = isCacheableMethod(method) ? method : undefined;
514
- const { useCache = !!m } = options;
558
+ const { useCache = !!m, readCache = true } = options;
515
559
  signal?.throwIfAborted();
516
560
  // Method + URL only. Headers (including accept) are not part of the
517
561
  // key and there is no Vary handling — callers must not vary the
518
562
  // response representation for the same URL.
519
563
  const key = cacheKey(method, u);
520
- const buffer = useCache ?
564
+ const buffer = useCache && readCache ?
521
565
  await this.cache.fetch(key, { context: { integrity } })
522
566
  : undefined;
523
567
  const entry = buffer ? this.#decodeCached(buffer) : undefined;
@@ -602,10 +646,6 @@ export class RegistryClient {
602
646
  statusCode: response.statusCode,
603
647
  durationMs: Date.now() - requestStart,
604
648
  });
605
- // a server-sent integrity header is not evidence: only the caller's
606
- // expectation, or a body read back from the cache, is trusted. the
607
- // header is dropped so it can never be stored as the entry's hash.
608
- //
609
649
  // the check has to happen here, before the cache write below, or a
610
650
  // body that fails it is still stored under the hash it was supposed
611
651
  // to have -- and served from there, unverified, on the next run.
@@ -614,13 +654,14 @@ export class RegistryClient {
614
654
  // else is the bytes as they came off the wire and hashes as such.
615
655
  // this used to also require `isGzip`, which was a proxy for that
616
656
  // and silently exempted every artifact that is not gzip -- a
617
- // `.tar.br` among them.
618
- if (!trustIntegrity && !result.fromCache) {
619
- result.deleteHeader('integrity');
620
- // 200 only: an error body is not the artifact and was never
621
- // supposed to hash to it, and it is not what gets cached either.
622
- if (result.statusCode === 200)
623
- result.checkIntegrity({ url });
657
+ // `.tar.br` among them. 200 only: an error body is not the artifact
658
+ // and was never supposed to hash to it; it is the caller's to report
659
+ // by status. the server-sent integrity header is already gone, see
660
+ // #handleResponse.
661
+ if (!trustIntegrity &&
662
+ !result.fromCache &&
663
+ result.statusCode === 200) {
664
+ result.checkIntegrity({ url });
624
665
  }
625
666
  // same for the digest the server labels an unlabelled artifact with.
626
667
  // before the cache write below, or a rejected body would be served
@@ -643,12 +684,23 @@ export class RegistryClient {
643
684
  if (useCache && !clobbersCachedEntry) {
644
685
  // content-address an artifact the caller had no expected hash for,
645
686
  // so a later lookup by hash still finds it; packuments are not
646
- // worth hashing. integrityActual also records the hash in the
647
- // entry's headers, so it runs before encode().
687
+ // worth hashing. never a body read back from the cache -- a 304,
688
+ // or the entry a redirect's nested request() served -- which
689
+ // cache-unzip may have rewritten un-gzipped: its hash is of bytes
690
+ // only this cache holds, and recorded here it would be trusted
691
+ // as the entry's from then on. integrityActual also records the
692
+ // hash in the entry's headers, so it runs before encode().
693
+ const artifact = !result.fromCache &&
694
+ result.statusCode === 200 &&
695
+ !result.isJSON;
648
696
  const integrity = result.integrity ??
649
- (result.statusCode === 200 && !result.isJSON ?
650
- result.integrityActual
651
- : undefined);
697
+ (artifact ? result.integrityActual : undefined);
698
+ // the hash an artifact is stored under was checked or recorded
699
+ // just now, as the hash of its bytes as served. label one that
700
+ // came with no content-type to say so, see
701
+ // CacheEntry#labelArtifact.
702
+ if (artifact)
703
+ result.labelArtifact();
652
704
  const encoded = result.encode();
653
705
  const stored = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);
654
706
  this.cache.set(key, stored, { integrity });
@@ -688,6 +740,13 @@ export class RegistryClient {
688
740
  'stale-while-revalidate-factor': this.staleWhileRevalidateFactor,
689
741
  contentLength,
690
742
  });
743
+ // a server-sent integrity header is not evidence: only the caller's
744
+ // expectation, or a body read back from the cache, is trusted. the
745
+ // header is dropped before the body is read so it can never be
746
+ // stored as the entry's hash, and so a nested request() for a
747
+ // redirect hands back an entry whose recorded hash survives.
748
+ if (!trustIntegrity)
749
+ result.deleteHeader('integrity');
691
750
  if (isRedirect(result)) {
692
751
  response.body.resume();
693
752
  const [nextURL, nextOptions] = redirect(options, result, url);
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.3.3",
4
+ "version": "1.3.4",
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.3.3",
17
- "@vltpkg/cache-unzip": "1.3.3",
18
- "@vltpkg/error-cause": "1.3.3",
19
- "@vltpkg/keychain": "1.3.3",
20
- "@vltpkg/output": "1.3.3",
21
- "@vltpkg/types": "1.3.3",
22
- "@vltpkg/url-open": "1.3.3",
23
- "@vltpkg/user-agent": "1.3.3",
24
- "@vltpkg/xdg": "1.3.3",
16
+ "@vltpkg/cache": "1.3.4",
17
+ "@vltpkg/cache-unzip": "1.3.4",
18
+ "@vltpkg/error-cause": "1.3.4",
19
+ "@vltpkg/keychain": "1.3.4",
20
+ "@vltpkg/output": "1.3.4",
21
+ "@vltpkg/types": "1.3.4",
22
+ "@vltpkg/url-open": "1.3.4",
23
+ "@vltpkg/user-agent": "1.3.4",
24
+ "@vltpkg/xdg": "1.3.4",
25
25
  "cache-control-parser": "^2.0.6",
26
26
  "undici": "^7.16.0"
27
27
  },