@vltpkg/registry-client 1.3.7 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth.d.ts CHANGED
@@ -29,21 +29,37 @@ export declare const setRuntimeToken: (registry: string, token: Token) => void;
29
29
  export declare const clearRuntimeTokens: () => void;
30
30
  export declare const getKC: (identity: string) => Keychain<Token>;
31
31
  export declare const isToken: (t: any) => t is Token;
32
- export declare const deleteToken: (registry: string, identity: string) => Promise<void>;
32
+ /**
33
+ * Delete the token for `registry`. With `token`, also delete every other
34
+ * key holding it: one login can save a token under many registries.
35
+ */
36
+ export declare const deleteToken: (registry: string, identity: string, token?: Token) => Promise<void>;
33
37
  export declare const setToken: (registry: string, token: Token, identity: string) => Promise<void>;
34
38
  export declare const getToken: (registry: string, identity: string) => Promise<Token | undefined>;
39
+ /** Configured registry URLs, by config option name. */
40
+ export type RegistryURLs = {
41
+ registry?: string;
42
+ registries?: Record<string, string>;
43
+ 'scoped-registries'?: Record<string, string>;
44
+ 'jsr-registries'?: Record<string, string>;
45
+ };
46
+ /**
47
+ * Normalized, deduped keys of the configured registries.
48
+ * Unparseable URLs are skipped.
49
+ */
50
+ export declare const registryKeys: (o: RegistryURLs) => string[];
35
51
  /**
36
52
  * Find the best matching token for a request URL by performing a
37
53
  * longest-prefix match against all known registry keys (runtime
38
- * tokens, env-var registries, and keychain entries). A key that
39
- * resolves no token is skipped.
54
+ * tokens, `VLT_REGISTRY`, keychain entries, and `keys`: normalized
55
+ * configured registry keys, e.g. from {@link registryKeys}). A key
56
+ * that resolves no token is skipped.
40
57
  *
41
58
  * `VLT_TOKEN_<key>` env vars are only read for a known key: their
42
59
  * names are lossy (`.`, `-`, `/` all become `_`), so probing them by
43
60
  * request URL would hand the token to lookalike hosts.
44
61
  *
45
- * This is used by `RegistryClient.request()` which only has the
46
- * full request URL — not the configured registry URL that was used
47
- * to construct it.
62
+ * Used by `RegistryClient.request()`, which has the request URL, not
63
+ * the registry URL it was built from.
48
64
  */
49
- export declare const getTokenByURL: (requestUrl: string, identity: string) => Promise<Token | undefined>;
65
+ export declare const getTokenByURL: (requestUrl: string, identity: string, keys?: readonly string[]) => Promise<Token | undefined>;
package/dist/auth.js CHANGED
@@ -45,10 +45,20 @@ export const getKC = (identity) => {
45
45
  };
46
46
  export const isToken = (t) => typeof t === 'string' &&
47
47
  (t.startsWith('Bearer ') || t.startsWith('Basic '));
48
- export const deleteToken = async (registry, identity) => {
48
+ /**
49
+ * Delete the token for `registry`. With `token`, also delete every other
50
+ * key holding it: one login can save a token under many registries.
51
+ */
52
+ export const deleteToken = async (registry, identity, token) => {
49
53
  const kc = getKC(identity);
50
54
  await kc.load();
51
55
  kc.delete(normalizeRegistryKey(registry));
56
+ if (token) {
57
+ for (const key of kc.keysSync()) {
58
+ if (kc.getSync(key) === token)
59
+ kc.delete(key);
60
+ }
61
+ }
52
62
  await kc.save();
53
63
  };
54
64
  export const setToken = async (registry, token, identity) => {
@@ -75,24 +85,38 @@ export const getToken = async (registry, identity) => {
75
85
  return `Bearer ${tok}`;
76
86
  return kc.get(key);
77
87
  };
88
+ /**
89
+ * Normalized, deduped keys of the configured registries.
90
+ * Unparseable URLs are skipped.
91
+ */
92
+ export const registryKeys = (o) => [
93
+ ...new Set([
94
+ o.registry,
95
+ ...Object.values(o.registries ?? {}),
96
+ ...Object.values(o['scoped-registries'] ?? {}),
97
+ ...Object.values(o['jsr-registries'] ?? {}),
98
+ ]
99
+ .filter((u) => !!u && URL.canParse(u))
100
+ .map(normalizeRegistryKey)),
101
+ ];
78
102
  /**
79
103
  * Find the best matching token for a request URL by performing a
80
104
  * longest-prefix match against all known registry keys (runtime
81
- * tokens, env-var registries, and keychain entries). A key that
82
- * resolves no token is skipped.
105
+ * tokens, `VLT_REGISTRY`, keychain entries, and `keys`: normalized
106
+ * configured registry keys, e.g. from {@link registryKeys}). A key
107
+ * that resolves no token is skipped.
83
108
  *
84
109
  * `VLT_TOKEN_<key>` env vars are only read for a known key: their
85
110
  * names are lossy (`.`, `-`, `/` all become `_`), so probing them by
86
111
  * request URL would hand the token to lookalike hosts.
87
112
  *
88
- * This is used by `RegistryClient.request()` which only has the
89
- * full request URL — not the configured registry URL that was used
90
- * to construct it.
113
+ * Used by `RegistryClient.request()`, which has the request URL, not
114
+ * the registry URL it was built from.
91
115
  */
92
- export const getTokenByURL = async (requestUrl, identity) => {
116
+ export const getTokenByURL = async (requestUrl, identity, keys = []) => {
93
117
  const normalized = normalizeRegistryKey(requestUrl);
94
118
  // Collect all known registry keys.
95
- const candidates = [...runtimeTokens.keys()];
119
+ const candidates = [...runtimeTokens.keys(), ...keys];
96
120
  const envReg = process.env.VLT_REGISTRY;
97
121
  if (envReg) {
98
122
  candidates.push(normalizeRegistryKey(envReg));
package/dist/index.d.ts CHANGED
@@ -4,8 +4,8 @@ import type { Readable } from 'node:stream';
4
4
  import type { Dispatcher } from 'undici';
5
5
  import { RetryAgent } from 'undici';
6
6
  import { userAgent } from '@vltpkg/user-agent';
7
- import type { Token } from './auth.ts';
8
- import { clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, registryBase, runtimeTokens, setRuntimeToken, setToken } from './auth.ts';
7
+ import type { RegistryURLs, Token } from './auth.ts';
8
+ import { clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, registryBase, registryKeys, runtimeTokens, setRuntimeToken, setToken } from './auth.ts';
9
9
  import type { JSONObj } from './cache-entry.ts';
10
10
  import { CacheEntry } from './cache-entry.ts';
11
11
  import { assertOk, registryErrorMessage, requestError } from './registry-error.ts';
@@ -15,7 +15,7 @@ import type { WebAuthChallenge } from './web-auth-challenge.ts';
15
15
  import { storeRoot } from './store-root.ts';
16
16
  import { oidc } from './oidc.ts';
17
17
  import type { OidcOptions } from './oidc.ts';
18
- 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, };
18
+ export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, registryKeys, requestError, runtimeTokens, setRuntimeToken, setToken, storeRoot, type ErrorResponse, type JSONObj, type OidcOptions, type RegistryURLs, type Token, type TokenResponse, type WebAuthChallenge, };
19
19
  /** A response body read straight out of the cache file. */
20
20
  export type CachedBody = {
21
21
  /** the cache file it came from */
@@ -32,7 +32,7 @@ export type CachedBody = {
32
32
  export type CacheableMethod = 'GET' | 'HEAD';
33
33
  export declare const isCacheableMethod: (m: unknown) => m is CacheableMethod;
34
34
  export declare const cacheKey: (method: string, url: URL | string) => string;
35
- export type RegistryClientOptions = {
35
+ export type RegistryClientOptions = RegistryURLs & {
36
36
  /**
37
37
  * Path on disk where the cache should be stored
38
38
  *
@@ -70,6 +70,8 @@ export type RegistryClientOptions = {
70
70
  * explicitly allowed by the server's `cache-control` header.
71
71
  */
72
72
  'stale-while-revalidate-factor'?: number;
73
+ /** aborts every request this client makes */
74
+ signal?: AbortSignal;
73
75
  };
74
76
  export type RegistryClientRequestOptions = Omit<Dispatcher.RequestOptions, 'method' | 'path'> & {
75
77
  /**
@@ -167,6 +169,8 @@ export declare class RegistryClient {
167
169
  agent: RetryAgent;
168
170
  cache: Cache;
169
171
  identity: string;
172
+ /** configured registry keys; `VLT_TOKEN_<key>` applies under each */
173
+ readonly registryKeys: readonly string[];
170
174
  staleWhileRevalidateFactor: number;
171
175
  constructor(options: RegistryClientOptions);
172
176
  /**
@@ -256,5 +260,10 @@ export declare class RegistryClient {
256
260
  statusCode: number;
257
261
  body: Readable;
258
262
  }>;
263
+ /**
264
+ * Settle in-flight requests and their cache writes. Await before
265
+ * removing the cache dir.
266
+ */
267
+ drain(): Promise<void>;
259
268
  request(url: URL | string, options?: RegistryClientRequestOptions): Promise<CacheEntry>;
260
269
  }
package/dist/index.js CHANGED
@@ -9,13 +9,14 @@ 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 { setMaxListeners } from 'node:events';
12
13
  import { pipeline } from 'node:stream';
13
14
  import { setTimeout } from 'node:timers/promises';
14
15
  import { createGunzip } from 'node:zlib';
15
16
  import { RetryAgent } from 'undici';
16
17
  import { userAgent } from '@vltpkg/user-agent';
17
18
  import { addHeader } from "./add-header.js";
18
- import { clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, registryBase, runtimeTokens, setRuntimeToken, setToken, } from "./auth.js";
19
+ import { clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, registryBase, registryKeys, runtimeTokens, setRuntimeToken, setToken, } from "./auth.js";
19
20
  import { CacheEntry } from "./cache-entry.js";
20
21
  import { register } from "./cache-revalidate.js";
21
22
  import { getHeader } from "./get-header.js";
@@ -28,11 +29,12 @@ import { setCacheHeaders } from "./set-cache-headers.js";
28
29
  import { getTokenResponse } from "./token-response.js";
29
30
  import { getWebAuthChallenge } from "./web-auth-challenge.js";
30
31
  import { collectHeaders, readBody } from "./response.js";
32
+ import { retry } from "./retry.js";
31
33
  import { storeRoot } from "./store-root.js";
32
34
  import { oidc } from "./oidc.js";
33
35
  // eslint-disable-next-line no-console
34
36
  const log = (msg) => console.error(msg);
35
- export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, requestError, runtimeTokens, setRuntimeToken, setToken, storeRoot, };
37
+ export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, registryKeys, requestError, runtimeTokens, setRuntimeToken, setToken, storeRoot, };
36
38
  export const isCacheableMethod = (m) => m === 'GET' || m === 'HEAD';
37
39
  // A head is about a kilobyte. This limit exists only so that a corrupt
38
40
  // length cannot make us allocate something enormous.
@@ -88,13 +90,30 @@ export class RegistryClient {
88
90
  agent;
89
91
  cache;
90
92
  identity;
93
+ /** configured registry keys; `VLT_TOKEN_<key>` applies under each */
94
+ registryKeys;
91
95
  staleWhileRevalidateFactor;
92
96
  #session = randomUUID();
93
97
  #decoded = new WeakMap();
98
+ // request() calls not settled yet, awaited by drain()
99
+ #inFlight = new Set();
100
+ #signal;
101
+ /** the request's own signal joined with the client's */
102
+ #withSignal(own) {
103
+ const c = this.#signal;
104
+ return !c || own === c || !(own instanceof AbortSignal) ?
105
+ (own ?? c)
106
+ : AbortSignal.any([own, c]);
107
+ }
94
108
  constructor(options) {
109
+ this.#signal = options.signal;
110
+ // undici adds a listener per request in flight
111
+ if (options.signal)
112
+ setMaxListeners(0, options.signal);
95
113
  const { cache = xdg.cache(), 'fetch-retry-factor': timeoutFactor = 2, 'fetch-retry-mintimeout': minTimeout = 0, 'fetch-retry-maxtimeout': maxTimeout = 30_000, 'fetch-retries': maxRetries = 3, identity = '', 'stale-while-revalidate-factor': staleWhileRevalidateFactor = 576, // 48h for a 5min cache
96
114
  } = options;
97
115
  this.identity = identity;
116
+ this.registryKeys = registryKeys(options);
98
117
  this.staleWhileRevalidateFactor = staleWhileRevalidateFactor;
99
118
  const path = resolve(cache, 'registry-client');
100
119
  const store = options.storeRoot ?? storeRoot(cache);
@@ -116,6 +135,7 @@ export class RegistryClient {
116
135
  minTimeout,
117
136
  maxTimeout,
118
137
  retryAfter: true,
138
+ retry,
119
139
  errorCodes: [
120
140
  'ECONNREFUSED',
121
141
  'ECONNRESET',
@@ -240,7 +260,7 @@ export class RegistryClient {
240
260
  }
241
261
  }
242
262
  finally {
243
- await deleteToken(registry, this.identity);
263
+ await deleteToken(registry, this.identity, tok);
244
264
  }
245
265
  }
246
266
  /**
@@ -524,12 +544,13 @@ export class RegistryClient {
524
544
  const u = typeof url === 'string' ? new URL(url) : url;
525
545
  const o = {
526
546
  ...options,
547
+ signal: this.#withSignal(options.signal),
527
548
  method: options.method ?? 'GET',
528
549
  path: u.pathname.replace(/\/+$/, '') + u.search,
529
550
  origin: u.origin,
530
551
  headers: addHeader(addHeader(addHeader(options.headers, 'accept-encoding', 'gzip;q=1.0, identity;q=0.5'), 'user-agent', userAgent), 'npm-session', this.#session),
531
552
  };
532
- o.headers = addHeader(o.headers, 'authorization', await getTokenByURL(String(u), this.identity));
553
+ o.headers = addHeader(o.headers, 'authorization', await getTokenByURL(String(u), this.identity, this.registryKeys));
533
554
  logRequest(url, 'start', { method: o.method });
534
555
  const requestStart = Date.now();
535
556
  const response = await this.agent.request(o);
@@ -550,7 +571,34 @@ export class RegistryClient {
550
571
  }
551
572
  return { statusCode: response.statusCode, body };
552
573
  }
574
+ /**
575
+ * Settle in-flight requests and their cache writes. Await before
576
+ * removing the cache dir.
577
+ */
578
+ async drain() {
579
+ do {
580
+ await Promise.all(this.#inFlight);
581
+ await this.cache.promise();
582
+ } while (this.#inFlight.size);
583
+ }
553
584
  async request(url, options = {}) {
585
+ options.signal = this.#withSignal(options.signal);
586
+ // tracked apart from the #request() promise: a second reaction on
587
+ // that one would make V8 drop the caller's async frames from the
588
+ // stack of any error #request() throws. redirect and otp hops call
589
+ // #request() directly, this call already tracks them
590
+ let settle;
591
+ const tracked = new Promise(res => (settle = res));
592
+ this.#inFlight.add(tracked);
593
+ try {
594
+ return await this.#request(url, options);
595
+ }
596
+ finally {
597
+ this.#inFlight.delete(tracked);
598
+ settle();
599
+ }
600
+ }
601
+ async #request(url, options) {
554
602
  const u = typeof url === 'string' ? new URL(url) : url;
555
603
  const { method = 'GET', integrity, redirections = new Set(), signal, otp = (process.env.VLT_OTP ?? '').trim(), staleWhileRevalidate = true, forceRevalidate = false, } = options;
556
604
  const { trustIntegrity, verifyDigest } = options;
@@ -612,7 +660,7 @@ export class RegistryClient {
612
660
  // redirect() strips it when the origin changes.
613
661
  if (!redirected || !getHeader(options.headers, 'authorization')) {
614
662
  // will remove if we don't have a token.
615
- options.headers = addHeader(options.headers, 'authorization', await getTokenByURL(String(u), this.identity));
663
+ options.headers = addHeader(options.headers, 'authorization', await getTokenByURL(String(u), this.identity, this.registryKeys));
616
664
  }
617
665
  let response = null;
618
666
  try {
@@ -717,7 +765,7 @@ export class RegistryClient {
717
765
  if (response.statusCode === 401) {
718
766
  const otpResult = await otplease(this, options, response);
719
767
  if (otpResult && 'retry' in otpResult) {
720
- return await this.request(url, otpResult.retry);
768
+ return await this.#request(url, otpResult.retry);
721
769
  }
722
770
  if (otpResult && 'bodyConsumed' in otpResult) {
723
771
  consumedBody = otpResult.bodyConsumed;
@@ -751,7 +799,7 @@ export class RegistryClient {
751
799
  response.body.resume();
752
800
  const [nextURL, nextOptions] = redirect(options, result, url);
753
801
  if (nextOptions && nextURL) {
754
- return await this.request(nextURL, nextOptions);
802
+ return await this.#request(nextURL, nextOptions);
755
803
  }
756
804
  return result;
757
805
  }
@@ -0,0 +1,6 @@
1
+ import type { RetryHandler } from 'undici';
2
+ /**
3
+ * undici's default retry policy, but aborting the request ends the wait
4
+ * between attempts, so a long Retry-After can't keep the process alive
5
+ */
6
+ export declare const retry: RetryHandler.RetryCallback;
package/dist/retry.js ADDED
@@ -0,0 +1,30 @@
1
+ import { setTimeout } from 'node:timers/promises';
2
+ /**
3
+ * undici's default retry policy, but aborting the request ends the wait
4
+ * between attempts, so a long Retry-After can't keep the process alive
5
+ */
6
+ export const retry = (err, { state: { counter }, opts }, cb) => {
7
+ const { code, statusCode, headers } = err;
8
+ const { method } = opts;
9
+ // request options, which the dispatch options type leaves out
10
+ const { signal } = opts;
11
+ // undici fills in every default
12
+ const { maxRetries, minTimeout, maxTimeout, timeoutFactor, methods, statusCodes, errorCodes, } = opts.retryOptions;
13
+ if ((code &&
14
+ code !== 'UND_ERR_REQ_RETRY' &&
15
+ !errorCodes.includes(code)) ||
16
+ !methods.includes(method) ||
17
+ (typeof statusCode === 'number' &&
18
+ !statusCodes.includes(statusCode)) ||
19
+ counter > maxRetries) {
20
+ cb(err);
21
+ return;
22
+ }
23
+ const ra = String(headers?.['retry-after'] ?? '');
24
+ const secs = Number(ra);
25
+ const after = Number.isNaN(secs) ? Date.parse(ra) - Date.now() : secs * 1000;
26
+ const wait = Math.min(after > 0 ? after : minTimeout * timeoutFactor ** (counter - 1), maxTimeout);
27
+ setTimeout(wait, null, {
28
+ signal: signal instanceof AbortSignal ? signal : undefined,
29
+ }).then(() => cb(null), (er) => cb(er));
30
+ };
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.7",
4
+ "version": "1.4.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.3.7",
17
- "@vltpkg/cache-unzip": "1.3.7",
18
- "@vltpkg/error-cause": "1.3.7",
19
- "@vltpkg/keychain": "1.3.7",
20
- "@vltpkg/output": "1.3.7",
21
- "@vltpkg/types": "1.3.7",
22
- "@vltpkg/url-open": "1.3.7",
23
- "@vltpkg/user-agent": "1.3.7",
24
- "@vltpkg/xdg": "1.3.7",
16
+ "@vltpkg/cache": "1.4.0",
17
+ "@vltpkg/cache-unzip": "1.4.0",
18
+ "@vltpkg/error-cause": "1.4.0",
19
+ "@vltpkg/keychain": "1.4.0",
20
+ "@vltpkg/output": "1.4.0",
21
+ "@vltpkg/types": "1.4.0",
22
+ "@vltpkg/url-open": "1.4.0",
23
+ "@vltpkg/user-agent": "1.4.0",
24
+ "@vltpkg/xdg": "1.4.0",
25
25
  "cache-control-parser": "^2.0.6",
26
26
  "undici": "^7.16.0"
27
27
  },