verdaccio 6.7.4 → 6.9.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.
Files changed (180) hide show
  1. package/README.md +2 -2
  2. package/bin/verdaccio +5 -1
  3. package/build/_virtual/_rolldown/runtime.js +23 -0
  4. package/build/api/debug/index.js +23 -26
  5. package/build/api/debug/index.js.map +1 -0
  6. package/build/api/debug/index.mjs +19 -0
  7. package/build/api/debug/index.mjs.map +1 -0
  8. package/build/api/endpoint/api/dist-tags.js +62 -75
  9. package/build/api/endpoint/api/dist-tags.js.map +1 -0
  10. package/build/api/endpoint/api/dist-tags.mjs +56 -0
  11. package/build/api/endpoint/api/dist-tags.mjs.map +1 -0
  12. package/build/api/endpoint/api/package.js +91 -99
  13. package/build/api/endpoint/api/package.js.map +1 -0
  14. package/build/api/endpoint/api/package.mjs +89 -0
  15. package/build/api/endpoint/api/package.mjs.map +1 -0
  16. package/build/api/endpoint/api/ping.js +13 -11
  17. package/build/api/endpoint/api/ping.js.map +1 -0
  18. package/build/api/endpoint/api/ping.mjs +11 -0
  19. package/build/api/endpoint/api/ping.mjs.map +1 -0
  20. package/build/api/endpoint/api/publish.d.ts +2 -2
  21. package/build/api/endpoint/api/publish.js +278 -343
  22. package/build/api/endpoint/api/publish.js.map +1 -0
  23. package/build/api/endpoint/api/publish.mjs +280 -0
  24. package/build/api/endpoint/api/publish.mjs.map +1 -0
  25. package/build/api/endpoint/api/search.js +57 -105
  26. package/build/api/endpoint/api/search.js.map +1 -0
  27. package/build/api/endpoint/api/search.mjs +54 -0
  28. package/build/api/endpoint/api/search.mjs.map +1 -0
  29. package/build/api/endpoint/api/star.js +60 -71
  30. package/build/api/endpoint/api/star.js.map +1 -0
  31. package/build/api/endpoint/api/star.mjs +54 -0
  32. package/build/api/endpoint/api/star.mjs.map +1 -0
  33. package/build/api/endpoint/api/stars.js +40 -40
  34. package/build/api/endpoint/api/stars.js.map +1 -0
  35. package/build/api/endpoint/api/stars.mjs +35 -0
  36. package/build/api/endpoint/api/stars.mjs.map +1 -0
  37. package/build/api/endpoint/api/user.js +69 -82
  38. package/build/api/endpoint/api/user.js.map +1 -0
  39. package/build/api/endpoint/api/user.mjs +64 -0
  40. package/build/api/endpoint/api/user.mjs.map +1 -0
  41. package/build/api/endpoint/api/v1/profile.js +50 -67
  42. package/build/api/endpoint/api/v1/profile.js.map +1 -0
  43. package/build/api/endpoint/api/v1/profile.mjs +46 -0
  44. package/build/api/endpoint/api/v1/profile.mjs.map +1 -0
  45. package/build/api/endpoint/api/v1/search.d.ts +2 -1
  46. package/build/api/endpoint/api/v1/search.js +149 -168
  47. package/build/api/endpoint/api/v1/search.js.map +1 -0
  48. package/build/api/endpoint/api/v1/search.mjs +154 -0
  49. package/build/api/endpoint/api/v1/search.mjs.map +1 -0
  50. package/build/api/endpoint/api/v1/token.js +122 -155
  51. package/build/api/endpoint/api/v1/token.js.map +1 -0
  52. package/build/api/endpoint/api/v1/token.mjs +119 -0
  53. package/build/api/endpoint/api/v1/token.mjs.map +1 -0
  54. package/build/api/endpoint/api/whoami.js +13 -13
  55. package/build/api/endpoint/api/whoami.js.map +1 -0
  56. package/build/api/endpoint/api/whoami.mjs +11 -0
  57. package/build/api/endpoint/api/whoami.mjs.map +1 -0
  58. package/build/api/endpoint/index.js +58 -67
  59. package/build/api/endpoint/index.js.map +1 -0
  60. package/build/api/endpoint/index.mjs +54 -0
  61. package/build/api/endpoint/index.mjs.map +1 -0
  62. package/build/api/index.js +85 -106
  63. package/build/api/index.js.map +1 -0
  64. package/build/api/index.mjs +78 -0
  65. package/build/api/index.mjs.map +1 -0
  66. package/build/api/middleware.js +60 -54
  67. package/build/api/middleware.js.map +1 -0
  68. package/build/api/middleware.mjs +55 -0
  69. package/build/api/middleware.mjs.map +1 -0
  70. package/build/api/web/api/index.js +25 -29
  71. package/build/api/web/api/index.js.map +1 -0
  72. package/build/api/web/api/index.mjs +23 -0
  73. package/build/api/web/api/index.mjs.map +1 -0
  74. package/build/api/web/api/package.js +142 -161
  75. package/build/api/web/api/package.js.map +1 -0
  76. package/build/api/web/api/package.mjs +139 -0
  77. package/build/api/web/api/package.mjs.map +1 -0
  78. package/build/api/web/api/search.js +37 -50
  79. package/build/api/web/api/search.js.map +1 -0
  80. package/build/api/web/api/search.mjs +36 -0
  81. package/build/api/web/api/search.mjs.map +1 -0
  82. package/build/api/web/api/user.js +52 -73
  83. package/build/api/web/api/user.js.map +1 -0
  84. package/build/api/web/api/user.mjs +49 -0
  85. package/build/api/web/api/user.mjs.map +1 -0
  86. package/build/api/web/api/utils.js +9 -10
  87. package/build/api/web/api/utils.js.map +1 -0
  88. package/build/api/web/api/utils.mjs +11 -0
  89. package/build/api/web/api/utils.mjs.map +1 -0
  90. package/build/api/web/index.js +76 -88
  91. package/build/api/web/index.js.map +1 -0
  92. package/build/api/web/index.mjs +70 -0
  93. package/build/api/web/index.mjs.map +1 -0
  94. package/build/index.js +43 -60
  95. package/build/index.mjs +5 -0
  96. package/build/lib/auth-utils.js +12 -14
  97. package/build/lib/auth-utils.js.map +1 -0
  98. package/build/lib/auth-utils.mjs +11 -0
  99. package/build/lib/auth-utils.mjs.map +1 -0
  100. package/build/lib/bootstrap.js +125 -157
  101. package/build/lib/bootstrap.js.map +1 -0
  102. package/build/lib/bootstrap.mjs +125 -0
  103. package/build/lib/bootstrap.mjs.map +1 -0
  104. package/build/lib/cli/cli.js +22 -24
  105. package/build/lib/cli/cli.js.map +1 -0
  106. package/build/lib/cli/cli.mjs +23 -0
  107. package/build/lib/cli/cli.mjs.map +1 -0
  108. package/build/lib/cli/commands/info.js +34 -25
  109. package/build/lib/cli/commands/info.js.map +1 -0
  110. package/build/lib/cli/commands/info.mjs +32 -0
  111. package/build/lib/cli/commands/info.mjs.map +1 -0
  112. package/build/lib/cli/commands/init.js +61 -79
  113. package/build/lib/cli/commands/init.js.map +1 -0
  114. package/build/lib/cli/commands/init.mjs +70 -0
  115. package/build/lib/cli/commands/init.mjs.map +1 -0
  116. package/build/lib/cli/commands/version.js +14 -16
  117. package/build/lib/cli/commands/version.js.map +1 -0
  118. package/build/lib/cli/commands/version.mjs +14 -0
  119. package/build/lib/cli/commands/version.mjs.map +1 -0
  120. package/build/lib/cli/utils.d.ts +2 -2
  121. package/build/lib/cli/utils.js +16 -15
  122. package/build/lib/cli/utils.js.map +1 -0
  123. package/build/lib/cli/utils.mjs +14 -0
  124. package/build/lib/cli/utils.mjs.map +1 -0
  125. package/build/lib/cli.js +11 -14
  126. package/build/lib/cli.js.map +1 -0
  127. package/build/lib/cli.mjs +12 -0
  128. package/build/lib/cli.mjs.map +1 -0
  129. package/build/lib/config.js +19 -21
  130. package/build/lib/config.js.map +1 -0
  131. package/build/lib/config.mjs +16 -0
  132. package/build/lib/config.mjs.map +1 -0
  133. package/build/lib/constants.js +100 -93
  134. package/build/lib/constants.js.map +1 -0
  135. package/build/lib/constants.mjs +28 -0
  136. package/build/lib/constants.mjs.map +1 -0
  137. package/build/lib/experiments.js +19 -27
  138. package/build/lib/experiments.js.map +1 -0
  139. package/build/lib/experiments.mjs +20 -0
  140. package/build/lib/experiments.mjs.map +1 -0
  141. package/build/lib/local-storage.d.ts +5 -2
  142. package/build/lib/local-storage.js +606 -757
  143. package/build/lib/local-storage.js.map +1 -0
  144. package/build/lib/local-storage.mjs +600 -0
  145. package/build/lib/local-storage.mjs.map +1 -0
  146. package/build/lib/logger/index.js +24 -19
  147. package/build/lib/logger/index.js.map +1 -0
  148. package/build/lib/logger/index.mjs +17 -0
  149. package/build/lib/logger/index.mjs.map +1 -0
  150. package/build/lib/metadata-utils.js +24 -36
  151. package/build/lib/metadata-utils.js.map +1 -0
  152. package/build/lib/metadata-utils.mjs +23 -0
  153. package/build/lib/metadata-utils.mjs.map +1 -0
  154. package/build/lib/run-server.js +83 -114
  155. package/build/lib/run-server.js.map +1 -0
  156. package/build/lib/run-server.mjs +82 -0
  157. package/build/lib/run-server.mjs.map +1 -0
  158. package/build/lib/storage-utils.d.ts +120 -8
  159. package/build/lib/storage-utils.js +390 -251
  160. package/build/lib/storage-utils.js.map +1 -0
  161. package/build/lib/storage-utils.mjs +400 -0
  162. package/build/lib/storage-utils.mjs.map +1 -0
  163. package/build/lib/storage.d.ts +127 -57
  164. package/build/lib/storage.js +674 -681
  165. package/build/lib/storage.js.map +1 -0
  166. package/build/lib/storage.mjs +665 -0
  167. package/build/lib/storage.mjs.map +1 -0
  168. package/build/lib/up-storage.js +490 -599
  169. package/build/lib/up-storage.js.map +1 -0
  170. package/build/lib/up-storage.mjs +484 -0
  171. package/build/lib/up-storage.mjs.map +1 -0
  172. package/build/lib/uplink-util.js +21 -31
  173. package/build/lib/uplink-util.js.map +1 -0
  174. package/build/lib/uplink-util.mjs +24 -0
  175. package/build/lib/uplink-util.mjs.map +1 -0
  176. package/build/lib/utils.js +172 -231
  177. package/build/lib/utils.js.map +1 -0
  178. package/build/lib/utils.mjs +188 -0
  179. package/build/lib/utils.mjs.map +1 -0
  180. package/package.json +105 -100
@@ -0,0 +1,665 @@
1
+ import { API_ERROR, DIST_TAGS, HTTP_STATUS } from "./constants.mjs";
2
+ import { logger } from "./logger/index.mjs";
3
+ import { ErrorCode, hasTarball, isObject, normalizeDistTags } from "./utils.mjs";
4
+ import { checkPackageLocal, checkPackageRemote, cleanUpLinksRef, convertAbbreviatedManifest, generatePackageTemplate, lookupDistFile, mergeUplinkTimeIntoLocal, publishPackage } from "./storage-utils.mjs";
5
+ import LocalStorage from "./local-storage.mjs";
6
+ import { mergeVersions } from "./metadata-utils.mjs";
7
+ import ProxyStorage from "./up-storage.mjs";
8
+ import { setupUpLinks, updateVersionsHiddenUpLink } from "./uplink-util.mjs";
9
+ import _ from "lodash";
10
+ import { PLUGIN_CATEGORY, validationUtils } from "@verdaccio/core";
11
+ import createDebug from "debug";
12
+ import { hasProxyTo } from "@verdaccio/config";
13
+ import { SearchMemoryIndexer } from "@verdaccio/search-indexer";
14
+ import { asyncLoadPlugin } from "@verdaccio/loaders";
15
+ import assert from "assert";
16
+ import async from "async";
17
+ import Stream from "stream";
18
+ import LocalDatabasePluginModule from "@verdaccio/local-storage-legacy";
19
+ import { ReadTarball } from "@verdaccio/streams";
20
+ //#region src/lib/storage.ts
21
+ var debug = createDebug("verdaccio:storage");
22
+ var Storage = class {
23
+ localStorage;
24
+ config;
25
+ logger;
26
+ uplinks;
27
+ filters;
28
+ constructor(config) {
29
+ this.config = config;
30
+ this.uplinks = setupUpLinks(config);
31
+ this.logger = logger;
32
+ this.localStorage = null;
33
+ }
34
+ /**
35
+ * Initialize the storage: load the storage plugin (or the default
36
+ * local storage) and the filter plugins. Safe to call once; subsequent
37
+ * calls only reload missing filters.
38
+ * @param {Config} config verdaccio configuration
39
+ * @param {IPluginFilters} filters preloaded filter plugins; when omitted they are loaded from the configuration
40
+ */
41
+ async init(config, filters) {
42
+ if (this.localStorage === null) {
43
+ this.filters = filters;
44
+ const storageInstance = await this.loadStorage(config, this.logger);
45
+ this.localStorage = new LocalStorage(this.config, logger, storageInstance);
46
+ await this.localStorage.getSecret(config);
47
+ debug("initialization completed");
48
+ } else debug("storage has been already initialized");
49
+ if (!this.filters) {
50
+ this.filters = await asyncLoadPlugin(this.config.filters, {
51
+ config: this.config,
52
+ logger: this.logger
53
+ }, (plugin) => {
54
+ return typeof plugin.filter_metadata !== "undefined";
55
+ }, true, this.config?.serverSettings?.pluginPrefix, PLUGIN_CATEGORY.FILTER);
56
+ debug("filters available %o", this.filters.length);
57
+ }
58
+ }
59
+ /**
60
+ * Resolve the storage backend: a configured storage plugin when available,
61
+ * otherwise the default `@verdaccio/local-storage` on the configured path.
62
+ * @return {Promise<StoragePlugin>} the storage plugin instance
63
+ */
64
+ async loadStorage(config, logger) {
65
+ const Storage = await this.loadStorePlugin();
66
+ if (_.isNil(Storage)) {
67
+ assert(this.config.storage, "CONFIG: storage path not defined");
68
+ debug("no custom storage found, loading default storage @verdaccio/local-storage");
69
+ const localStorage = new (LocalDatabasePluginModule.default ?? LocalDatabasePluginModule)(config, logger);
70
+ logger.info({
71
+ name: "@verdaccio/local-storage",
72
+ pluginCategory: PLUGIN_CATEGORY.STORAGE
73
+ }, "plugin @{name} successfully loaded (@{pluginCategory})");
74
+ return localStorage;
75
+ }
76
+ return Storage;
77
+ }
78
+ /**
79
+ * Load the storage plugins declared under `store` in the configuration.
80
+ * Only one storage is supported: with several plugins configured the
81
+ * first loaded one wins and a warning is logged.
82
+ * @return {Promise<StoragePluginLegacy<Config> | undefined>} the selected plugin, or undefined when none is configured
83
+ */
84
+ async loadStorePlugin() {
85
+ const plugins = await asyncLoadPlugin(this.config.store, {
86
+ config: this.config,
87
+ logger: this.logger
88
+ }, (plugin) => {
89
+ return typeof plugin.getPackageStorage !== "undefined";
90
+ }, true, this.config?.serverSettings?.pluginPrefix, PLUGIN_CATEGORY.STORAGE);
91
+ if (plugins.length > 1) this.logger.warn("more than one storage plugins has been detected, multiple storage are not supported, one will be selected automatically");
92
+ return _.head(plugins);
93
+ }
94
+ /**
95
+ * Add a package to the system (publish flow).
96
+ * Verifies the package does not exist locally nor on any uplink before
97
+ * creating it locally; uplinks being offline rejects the publish unless
98
+ * `publish.allow_offline` is enabled.
99
+ * Used storages: local (write) && uplinks
100
+ * @param {String} name package name
101
+ * @param {Object} metadata package manifest to publish
102
+ * @param {Function} callback invoked with an error when the publish is rejected
103
+ */
104
+ async addPackage(name, metadata, callback) {
105
+ debug("add package %o", name);
106
+ try {
107
+ await checkPackageLocal(name, this.localStorage);
108
+ await checkPackageRemote(name, this._isAllowPublishOffline(), this._syncUplinksMetadata.bind(this));
109
+ await publishPackage(name, metadata, this.localStorage);
110
+ callback();
111
+ } catch (err) {
112
+ callback(err);
113
+ }
114
+ }
115
+ /**
116
+ * Whether `publish.allow_offline` is enabled in the configuration.
117
+ * @return {Boolean} true when publishing with unreachable uplinks is allowed
118
+ */
119
+ _isAllowPublishOffline() {
120
+ return typeof this.config.publish !== "undefined" && _.isBoolean(this.config.publish.allow_offline) && this.config.publish.allow_offline;
121
+ }
122
+ /**
123
+ * Read the npm tokens matching the filter from the token storage.
124
+ * Used storages: local (read)
125
+ */
126
+ readTokens(filter) {
127
+ return this.localStorage.readTokens(filter);
128
+ }
129
+ /**
130
+ * Save an npm token to the token storage.
131
+ * Used storages: local (write)
132
+ */
133
+ saveToken(token) {
134
+ return this.localStorage.saveToken(token);
135
+ }
136
+ /**
137
+ * Delete an npm token from the token storage.
138
+ * Used storages: local (write)
139
+ */
140
+ deleteToken(user, tokenKey) {
141
+ return this.localStorage.deleteToken(user, tokenKey);
142
+ }
143
+ /**
144
+ * Add a new version of a package to the system.
145
+ * Used storages: local (write)
146
+ * @param {String} name package name
147
+ * @param {String} version version id, eg. 1.0.0
148
+ * @param {Version} metadata version metadata
149
+ * @param {String} tag dist-tag pointing to the version
150
+ * @param {Function} callback
151
+ */
152
+ addVersion(name, version, metadata, tag, callback) {
153
+ debug("add version %s package for %s", version, name);
154
+ this.localStorage.addVersion(name, version, metadata, tag, callback);
155
+ }
156
+ /**
157
+ * Tag package versions with the provided dist-tags.
158
+ * Used storages: local (write)
159
+ * @param {String} name package name
160
+ * @param {MergeTags} tagHash dist-tag to version mapping to merge
161
+ * @param {Function} callback
162
+ */
163
+ mergeTags(name, tagHash, callback) {
164
+ debug("merge tags for %o", name);
165
+ this.localStorage.mergeTags(name, tagHash, callback);
166
+ }
167
+ /**
168
+ * Change an existing package (eg. unpublish one version).
169
+ * Used storages: local (write)
170
+ * @param {String} name package name
171
+ * @param {Manifest} metadata updated package manifest
172
+ * @param {String} revision expected revision of the stored manifest
173
+ * @param {Function} callback
174
+ */
175
+ changePackage(name, metadata, revision, callback) {
176
+ debug("change existing package for package %o revision %o", name, revision);
177
+ this.localStorage.changePackage(name, metadata, revision, callback);
178
+ }
179
+ /**
180
+ * Remove a package from the local storage and the search indexer.
181
+ * Used storages: local (write)
182
+ * @param {String} name package name
183
+ * @param {Function} callback
184
+ */
185
+ removePackage(name, callback) {
186
+ debug("remove package %o", name);
187
+ this.localStorage.removePackage(name, callback);
188
+ SearchMemoryIndexer.remove(name).catch((reason) => {
189
+ debug("indexer has failed on remove item %o", reason);
190
+ logger.error("indexer has failed on remove item");
191
+ });
192
+ }
193
+ /**
194
+ * Remove a tarball from the local storage. The tarball must not be
195
+ * linked by any existing version, ie. the version should be
196
+ * unpublished first.
197
+ * Used storages: local (write)
198
+ * @param {String} name package name
199
+ * @param {String} filename tarball file name
200
+ * @param {String} revision expected revision of the stored manifest
201
+ * @param {Function} callback
202
+ */
203
+ removeTarball(name, filename, revision, callback) {
204
+ debug("remove tarball %s for %s", filename, name);
205
+ this.localStorage.removeTarball(name, filename, revision, callback);
206
+ }
207
+ /**
208
+ * Upload a tarball (publish flow). Synchronous, returns a writable
209
+ * stream the tarball body is piped into.
210
+ * Used storages: local (write)
211
+ * @param {String} name package name
212
+ * @param {String} filename tarball file name
213
+ * @return {Stream} writable upload stream
214
+ */
215
+ addTarball(name, filename) {
216
+ debug("add a tarball for %o", name);
217
+ return this.localStorage.addTarball(name, filename);
218
+ }
219
+ /**
220
+ * Whether a tarball exists in the local storage, without reading it
221
+ * (the stream is aborted as soon as it opens).
222
+ * Used storages: local (read)
223
+ * @param {String} name package name
224
+ * @param {String} filename tarball file name
225
+ * @return {Promise<Boolean>} true when the tarball is stored locally
226
+ */
227
+ hasLocalTarball(name, filename) {
228
+ const self = this;
229
+ return new Promise((resolve, reject) => {
230
+ let localStream = self.localStorage.getTarball(name, filename);
231
+ let isOpen = false;
232
+ localStream.on("error", (err) => {
233
+ if (isOpen || err.status !== HTTP_STATUS.NOT_FOUND) reject(err);
234
+ if (localStream) {
235
+ localStream.abort();
236
+ localStream = null;
237
+ }
238
+ resolve(false);
239
+ });
240
+ localStream.on("open", function() {
241
+ isOpen = true;
242
+ localStream.abort();
243
+ localStream = null;
244
+ resolve(true);
245
+ });
246
+ });
247
+ }
248
+ /**
249
+ * Get a tarball. Synchronous, returns a readable stream.
250
+ * The tarball is read locally first; on a local miss the distfile record
251
+ * is resolved from the package metadata (see lookupDistFile), syncing the
252
+ * uplinks when the local metadata does not know the file, and the tarball
253
+ * is then fetched from the uplink that serves the distfile url.
254
+ * Used storages: local || uplink (just one)
255
+ * @param {String} name package name
256
+ * @param {String} filename tarball file name
257
+ * @return {Stream} readable tarball stream
258
+ */
259
+ getTarball(name, filename) {
260
+ debug("get tarball for package %o filename %o", name, filename);
261
+ const readStream = new ReadTarball({});
262
+ readStream.abort = function() {};
263
+ const self = this;
264
+ this._isTarballAllowedByFilters(name, filename).then(async (allowed) => {
265
+ if (!allowed) {
266
+ readStream.emit("error", ErrorCode.getNotFound(API_ERROR.NO_PACKAGE));
267
+ return;
268
+ }
269
+ let localStream = self.localStorage.getTarball(name, filename);
270
+ let isOpen = false;
271
+ localStream.on("error", (err) => {
272
+ if (isOpen || err.status !== HTTP_STATUS.NOT_FOUND) return readStream.emit("error", err);
273
+ const err404 = err;
274
+ localStream.abort();
275
+ localStream = null;
276
+ const lookupFromUplinks = (info) => {
277
+ self._syncUplinksMetadata(name, info, {}, (syncErr, syncInfo) => {
278
+ if (_.isNil(syncErr) === false) return readStream.emit("error", syncErr);
279
+ if (self.filters?.length && !hasTarball(syncInfo, filename)) return readStream.emit("error", err404);
280
+ const distFile = lookupDistFile(syncInfo, filename);
281
+ if (_.isNil(distFile)) {
282
+ debug("remote tarball not found");
283
+ return readStream.emit("error", err404);
284
+ }
285
+ debug("dist file found, using it %o", distFile.url);
286
+ serveFile(distFile);
287
+ });
288
+ };
289
+ self.localStorage.getPackageMetadataAsync(name).then((info) => {
290
+ const distFile = lookupDistFile(info, filename);
291
+ if (_.isNil(distFile) === false) {
292
+ debug("dist file found, using it %o", distFile.url);
293
+ serveFile(distFile);
294
+ } else {
295
+ debug("dist file not found, proceed update upstream");
296
+ lookupFromUplinks(info);
297
+ }
298
+ }, () => {
299
+ lookupFromUplinks(null);
300
+ });
301
+ });
302
+ localStream.on("content-length", function(v) {
303
+ readStream.emit("content-length", v);
304
+ });
305
+ localStream.on("open", function() {
306
+ isOpen = true;
307
+ localStream.pipe(readStream);
308
+ });
309
+ });
310
+ return readStream;
311
+ /**
312
+ * Stream the tarball from the uplink serving the distfile, caching it
313
+ * locally (and restoring the distfile record) when the uplink has the
314
+ * cache enabled.
315
+ * @param {DistFile} file distfile record resolved for the tarball
316
+ */
317
+ function serveFile(file) {
318
+ let uplink = null;
319
+ if (file.registry && self.uplinks[file.registry]) {
320
+ uplink = self.uplinks[file.registry];
321
+ debug("tarball %o is served by the recorded uplink %o", filename, file.registry);
322
+ } else {
323
+ const candidates = [];
324
+ for (const uplinkId in self.uplinks) if (hasProxyTo(name, uplinkId, self.config.packages)) candidates.push(self.uplinks[uplinkId]);
325
+ debug("tarball %o has %o candidate uplinks", filename, candidates.length);
326
+ for (const candidate of candidates) if (candidate.isUplinkValid(file.url)) uplink = candidate;
327
+ if (uplink !== null) debug("uplink %o url matches tarball %o", uplink.upname, file.url);
328
+ else if (candidates.length === 1) {
329
+ uplink = candidates[0];
330
+ debug("using the single configured uplink %o for tarball %o hosted elsewhere", uplink.upname, file.url);
331
+ }
332
+ }
333
+ if (uplink == null) {
334
+ debug("upstream not found, creating one for %o", name);
335
+ uplink = new ProxyStorage({
336
+ url: file.url,
337
+ cache: true,
338
+ _autogenerated: true
339
+ }, self.config);
340
+ }
341
+ let savestream = null;
342
+ if (uplink.config.cache) {
343
+ debug("cache remote tarball enabled");
344
+ let distFile = file;
345
+ if (!file.registry && uplink.upname) {
346
+ debug("recording uplink %o on the persisted distfile for %o", uplink.upname, filename);
347
+ distFile = {
348
+ ...file,
349
+ registry: uplink.upname
350
+ };
351
+ }
352
+ savestream = self.localStorage.addTarball(name, filename, distFile);
353
+ } else debug("cache remote tarball disabled");
354
+ let on_open = function() {
355
+ on_open = function() {};
356
+ const rstream2 = uplink.fetchTarball(file.url);
357
+ rstream2.on("error", function(err) {
358
+ if (savestream) savestream.abort();
359
+ savestream = null;
360
+ readStream.emit("error", err);
361
+ });
362
+ rstream2.on("end", function() {
363
+ if (savestream) savestream.done();
364
+ });
365
+ rstream2.on("content-length", function(v) {
366
+ readStream.emit("content-length", v);
367
+ if (savestream) savestream.emit("content-length", v);
368
+ });
369
+ rstream2.pipe(readStream);
370
+ if (savestream) rstream2.pipe(savestream);
371
+ };
372
+ if (savestream) {
373
+ savestream.on("open", function() {
374
+ on_open();
375
+ });
376
+ savestream.on("error", function(err) {
377
+ self.logger.warn({
378
+ err,
379
+ fileName: file
380
+ }, "error saving file @{fileName}: @{err.message}\n@{err.stack}");
381
+ if (savestream) savestream.abort();
382
+ savestream = null;
383
+ on_open();
384
+ });
385
+ } else on_open();
386
+ }
387
+ }
388
+ /**
389
+ * Retrieve the package metadata: the local manifest merged with the
390
+ * manifest of every uplink with proxy access to the package.
391
+ * Used storages: local && uplink (proxy_access)
392
+ * @param {Object} options
393
+ * @property {String} options.name package name
394
+ * @property {Object} options.req Express `req` object
395
+ * @property {Boolean} options.keepUpLinkData keep the uplink info (last update, etc.) in the package metadata
396
+ * @property {Boolean} options.abbreviated serve the abbreviated manifest (npm install)
397
+ * @property {Function} options.callback invoked with the merged manifest and any uplink errors
398
+ */
399
+ getPackage(options) {
400
+ debug("get package for %o", options.name);
401
+ this.localStorage.getPackageMetadata(options.name, (err, data) => {
402
+ if (err && (!err.status || err.status >= HTTP_STATUS.INTERNAL_ERROR)) return options.callback(err);
403
+ this._syncUplinksMetadata(options.name, data, {
404
+ req: options.req,
405
+ uplinksLook: options.uplinksLook
406
+ }, function getPackageSynUpLinksCallback(err, result, uplinkErrors) {
407
+ if (err) return options.callback(err);
408
+ normalizeDistTags(cleanUpLinksRef(options.keepUpLinkData, result));
409
+ result._attachments = {};
410
+ if (options.abbreviated === true) {
411
+ debug("get abbreviated manifest");
412
+ options.callback(null, convertAbbreviatedManifest(result), uplinkErrors);
413
+ } else {
414
+ debug("get full package manifest");
415
+ options.callback(null, result, uplinkErrors);
416
+ }
417
+ });
418
+ });
419
+ }
420
+ /**
421
+ * Retrieve remote and local packages more recent than the start key.
422
+ * All uplinks are streamed first, then the local packages; local
423
+ * packages can override registry ones just because they appear in the
424
+ * JSON last — a trade-off made to avoid memory issues.
425
+ * Used storages: local && uplink (proxy_access)
426
+ * @param {String} startkey timestamp to search from
427
+ * @param {Object} options request options; `local=1` in the query skips the uplinks
428
+ * @return {Stream} object stream of search results
429
+ */
430
+ search(startkey, options) {
431
+ const self = this;
432
+ const searchStream = new Stream.PassThrough({ objectMode: true });
433
+ async.eachSeries(Object.keys(this.uplinks), function(up_name, cb) {
434
+ if (options.req?.query?.local !== void 0) return cb();
435
+ logger.info(`search for uplink ${up_name}`);
436
+ const uplinkStream = self.uplinks[up_name].search(options);
437
+ uplinkStream.pipe(searchStream, { end: false });
438
+ uplinkStream.on("error", function(err) {
439
+ self.logger.error({ err }, "uplink error: @{err.message}");
440
+ cb();
441
+ cb = function() {};
442
+ });
443
+ uplinkStream.on("end", function() {
444
+ cb();
445
+ cb = function() {};
446
+ });
447
+ searchStream.abort = function() {
448
+ if (uplinkStream.abort) uplinkStream.abort();
449
+ cb();
450
+ cb = function() {};
451
+ };
452
+ }, function() {
453
+ const localSearchStream = self.localStorage.search(startkey, options);
454
+ searchStream.abort = function() {
455
+ localSearchStream.abort();
456
+ };
457
+ localSearchStream.pipe(searchStream, { end: true });
458
+ localSearchStream.on("error", function(err) {
459
+ self.logger.error({ err }, "search error: @{err.message}");
460
+ searchStream.end();
461
+ });
462
+ });
463
+ return searchStream;
464
+ }
465
+ /**
466
+ * Retrieve only private local packages, as the latest version of each.
467
+ * Used storages: local (read)
468
+ * @param {Function} callback invoked with the list of latest versions
469
+ */
470
+ getLocalDatabase(callback) {
471
+ this.localStorage.storagePlugin.get((err, locals) => {
472
+ if (err) return callback(err);
473
+ this._collectLocalPackages(locals).then((packages) => callback(null, packages), (err) => callback(err));
474
+ });
475
+ }
476
+ /**
477
+ * Read each local package name, apply filters, and collect the latest version.
478
+ */
479
+ async _collectLocalPackages(locals) {
480
+ const packages = [];
481
+ for (const name of locals) try {
482
+ const pkgMetadata = await this.localStorage.getPackageMetadataAsync(name);
483
+ const { filteredPackage } = await this._applyFilters(pkgMetadata);
484
+ const latest = filteredPackage[DIST_TAGS]?.latest;
485
+ if (latest && filteredPackage.versions[latest]) {
486
+ const version = filteredPackage.versions[latest];
487
+ version.time = filteredPackage.time[latest];
488
+ version.users = filteredPackage.users;
489
+ packages.push(version);
490
+ } else this.logger.warn({ package: name }, "package @{package} does not have a \"latest\" tag?");
491
+ } catch (err) {
492
+ this.logger.error({
493
+ err,
494
+ package: name
495
+ }, "error reading package @{package}");
496
+ }
497
+ return packages;
498
+ }
499
+ /**
500
+ * Fetch the package metadata from every uplink with proxy access and
501
+ * synchronize it with the local data; filter plugins are applied to the
502
+ * merged result.
503
+ * @param {String} name package name
504
+ * @param {Manifest} packageInfo local manifest; MUST be provided when the package exists locally
505
+ * @param {ISyncUplinks} options uplink request options
506
+ * @param {Function} callback invoked with (err, mergedManifest, uplinkErrors)
507
+ */
508
+ _syncUplinksMetadata(name, packageInfo, options, callback) {
509
+ let found = true;
510
+ const self = this;
511
+ const upLinks = [];
512
+ const hasToLookIntoUplinks = _.isNil(options.uplinksLook) || options.uplinksLook;
513
+ debug("sync uplinks for %o", name);
514
+ debug("is sync uplink enabled %o", hasToLookIntoUplinks);
515
+ if (!packageInfo) {
516
+ debug("local package %s not found", name);
517
+ found = false;
518
+ packageInfo = generatePackageTemplate(name);
519
+ }
520
+ for (const uplink in this.uplinks) if (hasProxyTo(name, uplink, this.config.packages) && hasToLookIntoUplinks) upLinks.push(this.uplinks[uplink]);
521
+ debug("uplinks found for %o: %o", name, upLinks.length);
522
+ async.map(upLinks, (upLink, cb) => {
523
+ const _options = Object.assign({}, options);
524
+ const upLinkMeta = packageInfo._uplinks[upLink.upname];
525
+ if (isObject(upLinkMeta)) {
526
+ const fetched = upLinkMeta.fetched;
527
+ if (fetched && Date.now() - fetched < upLink.maxage) {
528
+ debug("returning cached manifest for %o", upLink.upname);
529
+ return cb();
530
+ }
531
+ _options.etag = upLinkMeta.etag;
532
+ }
533
+ upLink.getRemoteMetadata(name, _options, (err, upLinkResponse, eTag) => {
534
+ if (err && err.remoteStatus === 304) {
535
+ debug("uplink %o responded 304 for %o, cache is up to date", upLink.upname, name);
536
+ upLinkMeta.fetched = Date.now();
537
+ }
538
+ if (err || !upLinkResponse) {
539
+ debug("error captured on uplink %o for %o: %o", upLink.upname, name, err?.message);
540
+ return cb(null, [err || ErrorCode.getInternalError("no data")]);
541
+ }
542
+ try {
543
+ upLinkResponse = validationUtils.normalizeMetadata(upLinkResponse, name);
544
+ } catch (err) {
545
+ self.logger.error({
546
+ sub: "out",
547
+ err
548
+ }, "package.json validating error @{!err.message}\n@{err.stack}");
549
+ return cb(null, [err]);
550
+ }
551
+ packageInfo._uplinks[upLink.upname] = {
552
+ etag: eTag,
553
+ fetched: Date.now()
554
+ };
555
+ packageInfo = mergeUplinkTimeIntoLocal(packageInfo, upLinkResponse);
556
+ updateVersionsHiddenUpLink(upLinkResponse.versions, upLink);
557
+ try {
558
+ mergeVersions(packageInfo, upLinkResponse);
559
+ } catch (err) {
560
+ self.logger.error({
561
+ sub: "out",
562
+ err
563
+ }, "package.json parsing error @{!err.message}\n@{err.stack}");
564
+ return cb(null, [err]);
565
+ }
566
+ debug("syncing on uplink %o", upLink.upname);
567
+ found = true;
568
+ cb();
569
+ });
570
+ }, async (err, upLinksErrors) => {
571
+ assert(!err && Array.isArray(upLinksErrors));
572
+ if (!found) {
573
+ let uplinkTimeoutError;
574
+ for (let i = 0; i < upLinksErrors.length; i++) if (upLinksErrors[i]) {
575
+ for (let j = 0; j < upLinksErrors[i].length; j++) if (upLinksErrors[i][j]) {
576
+ const code = upLinksErrors[i][j].code;
577
+ if (code === "ETIMEDOUT" || code === "ESOCKETTIMEDOUT" || code === "ECONNRESET") {
578
+ uplinkTimeoutError = true;
579
+ break;
580
+ }
581
+ }
582
+ }
583
+ if (uplinkTimeoutError) {
584
+ debug("uplinks sync failed with timeout error");
585
+ return callback(ErrorCode.getServiceUnavailable(), null, upLinksErrors);
586
+ }
587
+ debug("uplinks sync failed with no package found");
588
+ return callback(ErrorCode.getNotFound(API_ERROR.NO_PACKAGE), null, upLinksErrors);
589
+ }
590
+ if (upLinks.length === 0) {
591
+ debug("no uplinks found for %o, upstream update aborted", name);
592
+ const { filteredPackage, filterErrors } = await self._applyFilters(packageInfo);
593
+ return callback(null, filteredPackage, filterErrors);
594
+ }
595
+ try {
596
+ const packageJsonLocal = await self.localStorage.updateVersionsAsync(name, packageInfo);
597
+ const { filteredPackage, filterErrors } = await self._applyFilters(packageJsonLocal);
598
+ callback(null, filteredPackage, _.concat(upLinksErrors, filterErrors));
599
+ } catch (err) {
600
+ callback(err);
601
+ }
602
+ });
603
+ }
604
+ /**
605
+ * Apply all configured filter plugins to a package manifest sequentially.
606
+ * Each filter's output is passed as input to the next filter.
607
+ * Returns the filtered manifest and any errors that occurred.
608
+ */
609
+ async _applyFilters(packageInfo) {
610
+ const filterErrors = [];
611
+ let filteredPackage = packageInfo;
612
+ for (const filter of this.filters ?? []) try {
613
+ filteredPackage = await filter.filter_metadata(filteredPackage);
614
+ } catch (err) {
615
+ debug("filter plugin has failed on %o: %o", packageInfo.name, err?.message);
616
+ filterErrors.push(err);
617
+ }
618
+ return {
619
+ filteredPackage,
620
+ filterErrors
621
+ };
622
+ }
623
+ /**
624
+ * Check if a tarball should be served based on filter plugins, using only
625
+ * local metadata. Returns true (defer) when the version isn't cached locally
626
+ * — the uplink-sync path in getTarball re-checks filters after sync, which
627
+ * avoids a redundant uplink round-trip and double filter application.
628
+ */
629
+ async _isTarballAllowedByFilters(name, filename) {
630
+ if (!this.filters?.length) return true;
631
+ try {
632
+ const pkgMetadata = await this.localStorage.getPackageMetadataAsync(name);
633
+ if (!hasTarball(pkgMetadata, filename)) return true;
634
+ const { filteredPackage } = await this._applyFilters(pkgMetadata);
635
+ const allowed = hasTarball(filteredPackage, filename);
636
+ if (allowed === false) debug("tarball %o of %o is blocked by a filter plugin", filename, name);
637
+ return allowed;
638
+ } catch (err) {
639
+ if (err?.status === HTTP_STATUS.NOT_FOUND) return true;
640
+ this.logger.error({
641
+ package: name,
642
+ fileName: filename,
643
+ err
644
+ }, "error checking filters for tarball @{fileName} of package @{package}: @{err.message}");
645
+ return true;
646
+ }
647
+ }
648
+ /**
649
+ * Tag each version with the uplink it was fetched from, under a hidden
650
+ * (symbol) key. The local storage uses the tag to record the registry
651
+ * on the distfile records it creates.
652
+ * @param {Versions} versions versions fetched from the uplink
653
+ * @param {ProxyStorage} upLink uplink the versions were fetched from
654
+ */
655
+ _updateVersionsHiddenUpLink(versions, upLink) {
656
+ for (const i in versions) if (Object.prototype.hasOwnProperty.call(versions, i)) {
657
+ const version = versions[i];
658
+ version[Symbol.for("__verdaccio_uplink")] = upLink.upname;
659
+ }
660
+ }
661
+ };
662
+ //#endregion
663
+ export { Storage as default };
664
+
665
+ //# sourceMappingURL=storage.mjs.map