@vltpkg/registry-client 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth.d.ts CHANGED
@@ -35,7 +35,12 @@ export declare const getToken: (registry: string, identity: string) => Promise<T
35
35
  /**
36
36
  * Find the best matching token for a request URL by performing a
37
37
  * longest-prefix match against all known registry keys (runtime
38
- * tokens, env-var registries, and keychain entries).
38
+ * tokens, env-var registries, and keychain entries). A key that
39
+ * resolves no token is skipped.
40
+ *
41
+ * `VLT_TOKEN_<key>` env vars are only read for a known key: their
42
+ * names are lossy (`.`, `-`, `/` all become `_`), so probing them by
43
+ * request URL would hand the token to lookalike hosts.
39
44
  *
40
45
  * This is used by `RegistryClient.request()` which only has the
41
46
  * full request URL — not the configured registry URL that was used
package/dist/auth.js CHANGED
@@ -78,7 +78,12 @@ export const getToken = async (registry, identity) => {
78
78
  /**
79
79
  * Find the best matching token for a request URL by performing a
80
80
  * longest-prefix match against all known registry keys (runtime
81
- * tokens, env-var registries, and keychain entries).
81
+ * tokens, env-var registries, and keychain entries). A key that
82
+ * resolves no token is skipped.
83
+ *
84
+ * `VLT_TOKEN_<key>` env vars are only read for a known key: their
85
+ * names are lossy (`.`, `-`, `/` all become `_`), so probing them by
86
+ * request URL would hand the token to lookalike hosts.
82
87
  *
83
88
  * This is used by `RegistryClient.request()` which only has the
84
89
  * full request URL — not the configured registry URL that was used
@@ -97,22 +102,14 @@ export const getTokenByURL = async (requestUrl, identity) => {
97
102
  for (const k of await kc.keys()) {
98
103
  candidates.push(k);
99
104
  }
100
- // Find the longest candidate key that is a prefix of the
101
- // normalized request URL.
102
- let bestKey;
103
- let bestLen = 0;
104
- for (const candidate of candidates) {
105
- if (candidate.length > bestLen &&
106
- (normalized === candidate ||
107
- normalized.startsWith(candidate + '/'))) {
108
- bestKey = candidate;
109
- bestLen = candidate.length;
110
- }
111
- }
112
- if (bestKey) {
113
- return getToken(bestKey, identity);
105
+ // Longest candidate key that is a prefix of the normalized request
106
+ // URL and has a token (VLT_REGISTRY may have none).
107
+ const matches = candidates
108
+ .filter(c => normalized === c || normalized.startsWith(c + '/'))
109
+ .sort((a, b) => b.length - a.length);
110
+ for (const key of matches) {
111
+ const tok = await getToken(key, identity);
112
+ if (tok)
113
+ return tok;
114
114
  }
115
- // Fall back to origin-only match (handles VLT_TOKEN_* env vars
116
- // which we can't enumerate by URL).
117
- return getToken(requestUrl, identity);
118
115
  };
@@ -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';
@@ -124,7 +125,12 @@ export type RegistryClientRequestOptions = Omit<Dispatcher.RequestOptions, 'meth
124
125
  */
125
126
  forceRevalidate?: boolean;
126
127
  };
127
- export declare const userAgent: string;
128
+ /**
129
+ * The `User-Agent` header sent with every request. Re-exported from
130
+ * `@vltpkg/user-agent`, which is where the value is defined, so that
131
+ * existing importers of this package keep working.
132
+ */
133
+ export { userAgent };
128
134
  export declare class RegistryClient {
129
135
  #private;
130
136
  agent: RetryAgent;
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";
@@ -34,13 +33,12 @@ const log = (msg) => console.error(msg);
34
33
  export { assertOk, CacheEntry, clearRuntimeTokens, deleteToken, getKC, getToken, getTokenByURL, isToken, keychains, normalizeRegistryKey, oidc, registryBase, registryErrorMessage, requestError, runtimeTokens, setRuntimeToken, setToken, };
35
34
  export const isCacheableMethod = (m) => m === 'GET' || m === 'HEAD';
36
35
  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}`;
36
+ /**
37
+ * The `User-Agent` header sent with every request. Re-exported from
38
+ * `@vltpkg/user-agent`, which is where the value is defined, so that
39
+ * existing importers of this package keep working.
40
+ */
41
+ export { userAgent };
44
42
  // Agent-level knobs only. Do not spread these onto per-request options —
45
43
  // connections/pipelining/keepAlive/connect are ignored at dispatch time,
46
44
  // and bodyTimeout/headersTimeout would clobber caller overrides.
@@ -477,6 +475,7 @@ export class RegistryClient {
477
475
  const requestStart = Date.now();
478
476
  // either no cache entry, or need to revalidate before use.
479
477
  setCacheHeaders(options, entry);
478
+ const redirected = redirections.size > 0;
480
479
  redirections.add(String(url));
481
480
  // eslint-disable-next-line @typescript-eslint/no-deprecated -- deprecated for callers; this is the one place that sets it
482
481
  options.path = u.pathname.replace(/\/+$/, '') + u.search;
@@ -489,8 +488,13 @@ export class RegistryClient {
489
488
  options.headers = addHeader(options.headers, 'accept-integrity', integrity);
490
489
  }
491
490
  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));
491
+ // a same-origin redirect keeps the credential of the hop that led
492
+ // here, since path-scoped keys may not match the new path.
493
+ // redirect() strips it when the origin changes.
494
+ if (!redirected || !getHeader(options.headers, 'authorization')) {
495
+ // will remove if we don't have a token.
496
+ options.headers = addHeader(options.headers, 'authorization', await getTokenByURL(String(u), this.identity));
497
+ }
494
498
  let response = null;
495
499
  try {
496
500
  response = await this.agent.request(options);
@@ -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
@@ -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) => {
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.1.1",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/vltpkg/vltpkg.git",
@@ -13,16 +13,16 @@
13
13
  "url": "http://vlt.sh"
14
14
  },
15
15
  "dependencies": {
16
- "@vltpkg/cache": "1.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.1.1",
17
+ "@vltpkg/cache-unzip": "1.1.1",
18
+ "@vltpkg/error-cause": "1.1.1",
19
+ "@vltpkg/keychain": "1.1.1",
20
+ "@vltpkg/output": "1.1.1",
21
+ "@vltpkg/types": "1.1.1",
22
+ "@vltpkg/url-open": "1.1.1",
23
+ "@vltpkg/user-agent": "1.1.1",
24
+ "@vltpkg/xdg": "1.1.1",
24
25
  "cache-control-parser": "^2.0.6",
25
- "package-json-from-dist": "^1.0.1",
26
26
  "undici": "^7.16.0"
27
27
  },
28
28
  "devDependencies": {
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;