@jini-ai/plugins 0.5.1 → 0.6.10

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 (56) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/dist/host/browser-providers.d.ts +2 -9
  3. package/dist/host/browser-providers.d.ts.map +1 -1
  4. package/dist/host/browser-providers.js +34 -18
  5. package/dist/host/browser-providers.js.map +1 -1
  6. package/dist/host/contributions.d.ts +4 -1
  7. package/dist/host/contributions.d.ts.map +1 -1
  8. package/dist/host/contributions.js +19 -8
  9. package/dist/host/contributions.js.map +1 -1
  10. package/dist/host/discovery-types.d.ts +1 -1
  11. package/dist/host/discovery-types.d.ts.map +1 -1
  12. package/dist/host/hook-registry.d.ts.map +1 -1
  13. package/dist/host/hook-registry.js +7 -5
  14. package/dist/host/hook-registry.js.map +1 -1
  15. package/dist/host/manifest-types.d.ts +103 -0
  16. package/dist/host/manifest-types.d.ts.map +1 -0
  17. package/dist/host/manifest-types.js +2 -0
  18. package/dist/host/manifest-types.js.map +1 -0
  19. package/dist/host/manifest.d.ts +2 -94
  20. package/dist/host/manifest.d.ts.map +1 -1
  21. package/dist/host/manifest.js +27 -19
  22. package/dist/host/manifest.js.map +1 -1
  23. package/dist/host/node/discovery.d.ts.map +1 -1
  24. package/dist/host/node/discovery.js +23 -18
  25. package/dist/host/node/discovery.js.map +1 -1
  26. package/dist/host/node/install.d.ts.map +1 -1
  27. package/dist/host/node/install.js +252 -200
  28. package/dist/host/node/install.js.map +1 -1
  29. package/dist/host/node/loader.d.ts.map +1 -1
  30. package/dist/host/node/loader.js +84 -66
  31. package/dist/host/node/loader.js.map +1 -1
  32. package/dist/host/node/open-flags.d.ts +18 -0
  33. package/dist/host/node/open-flags.d.ts.map +1 -0
  34. package/dist/host/node/open-flags.js +14 -0
  35. package/dist/host/node/open-flags.js.map +1 -0
  36. package/dist/host/node/package-files.d.ts.map +1 -1
  37. package/dist/host/node/package-files.js +18 -12
  38. package/dist/host/node/package-files.js.map +1 -1
  39. package/dist/host/node/source-drafts.d.ts.map +1 -1
  40. package/dist/host/node/source-drafts.js +83 -56
  41. package/dist/host/node/source-drafts.js.map +1 -1
  42. package/dist/host/plugin-claims.d.ts.map +1 -1
  43. package/dist/host/plugin-claims.js +3 -1
  44. package/dist/host/plugin-claims.js.map +1 -1
  45. package/dist/host/ports.d.ts +1 -1
  46. package/dist/host/ports.d.ts.map +1 -1
  47. package/dist/host/tool-contributions.d.ts.map +1 -1
  48. package/dist/host/tool-contributions.js +3 -1
  49. package/dist/host/tool-contributions.js.map +1 -1
  50. package/dist/host/worker/protocol.d.ts.map +1 -1
  51. package/dist/host/worker/protocol.js +8 -6
  52. package/dist/host/worker/protocol.js.map +1 -1
  53. package/dist/host/worker/run-call.d.ts.map +1 -1
  54. package/dist/host/worker/run-call.js +20 -17
  55. package/dist/host/worker/run-call.js.map +1 -1
  56. package/package.json +7 -7
@@ -26,6 +26,10 @@ const MAX_TOTAL_BYTES = 64 * 1024 * 1024;
26
26
  const hash = (bytes) => `sha256-${createHash("sha256").update(bytes).digest("hex")}`;
27
27
  function fail(code, message) { throw new PluginInstallError(code, message); }
28
28
  const inside = (parent, child) => child === parent || child.startsWith(parent + path.sep);
29
+ function assertRealDirectory(info, message) {
30
+ if (!info.isDirectory() || info.isSymbolicLink())
31
+ fail("PLUGIN_PACKAGE_UNSAFE", message);
32
+ }
29
33
  async function exists(target) {
30
34
  try {
31
35
  await lstat(target);
@@ -42,22 +46,65 @@ export async function assertPluginInstallIdle(required, _optional = {}) {
42
46
  if (await exists(path.resolve(required.installDir) + "-install-lock"))
43
47
  fail("PLUGIN_INSTALL_BUSY", "Another install is in progress.");
44
48
  }
45
- /** Retain the inspected bytes, rather than copying a mutable source after consent verification. */
46
- async function snapshot(sourceDir, limits = {}) {
49
+ /** Snapshot limits capped at the installer ceilings; a caller may only tighten them. */
50
+ function snapshotLimits(limits) {
47
51
  for (const limit of Object.values(limits)) {
48
52
  if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1))
49
53
  fail('PLUGIN_SNAPSHOT_LIMIT_INVALID', 'Snapshot limits must be positive safe integers.');
50
54
  }
51
- const maxEntries = Math.min(limits.maxEntries ?? MAX_ENTRIES, MAX_ENTRIES);
52
- const maxFileBytes = Math.min(limits.maxFileBytes ?? MAX_FILE_BYTES, MAX_FILE_BYTES);
53
- const maxTotalBytes = Math.min(limits.maxTotalBytes ?? MAX_TOTAL_BYTES, MAX_TOTAL_BYTES);
55
+ return {
56
+ maxEntries: Math.min(limits.maxEntries ?? MAX_ENTRIES, MAX_ENTRIES),
57
+ maxFileBytes: Math.min(limits.maxFileBytes ?? MAX_FILE_BYTES, MAX_FILE_BYTES),
58
+ maxTotalBytes: Math.min(limits.maxTotalBytes ?? MAX_TOTAL_BYTES, MAX_TOTAL_BYTES),
59
+ };
60
+ }
61
+ /** Reads up to `size` bytes; the caller sizes the buffer one past the stat()'d length. */
62
+ async function readUpTo(handle, size) {
63
+ const buffer = Buffer.alloc(size);
64
+ let length = 0;
65
+ while (length < buffer.length) {
66
+ const read = await handle.read(buffer, length, buffer.length - length, null);
67
+ if (read.bytesRead === 0)
68
+ break;
69
+ length += read.bytesRead;
70
+ }
71
+ return buffer.subarray(0, length);
72
+ }
73
+ function assertRetainableFile(info, maxFileBytes, remainingBytes) {
74
+ if (!info.isFile() || info.nlink !== 1)
75
+ fail("PLUGIN_PACKAGE_UNSAFE", "Only regular files without hard links are allowed.");
76
+ if (info.size > maxFileBytes || info.size > remainingBytes)
77
+ fail("PLUGIN_PACKAGE_TOO_LARGE", "Package exceeds the file or total size limit.");
78
+ }
79
+ /** One regular, unlinked file's bytes within the limits, refused if it is swapped, grows or shrinks while being read. */
80
+ async function readStableFile(required) {
81
+ const { info, maxFileBytes, remainingBytes } = required;
82
+ assertRetainableFile(info, maxFileBytes, remainingBytes);
83
+ const handle = await open(required.target, constants.O_RDONLY | constants.O_NOFOLLOW);
84
+ try {
85
+ const current = await handle.stat();
86
+ if (!current.isFile() || current.nlink !== 1 || current.ino !== info.ino || current.dev !== info.dev)
87
+ fail("PLUGIN_PACKAGE_UNSAFE", "Package changed while reading.");
88
+ // A bounded read also protects against a file growing after stat().
89
+ const bytes = await readUpTo(handle, info.size + 1);
90
+ if (bytes.length > maxFileBytes || bytes.length > remainingBytes)
91
+ fail("PLUGIN_PACKAGE_TOO_LARGE", "Package grew past its size limit.");
92
+ if (bytes.length > info.size || (await handle.stat()).size !== bytes.length)
93
+ fail("PLUGIN_PACKAGE_UNSAFE", "Package changed while reading.");
94
+ return Buffer.from(bytes);
95
+ }
96
+ finally {
97
+ await handle.close();
98
+ }
99
+ }
100
+ /** Retain the inspected bytes, rather than copying a mutable source after consent verification. */
101
+ async function snapshot(sourceDir, limits = {}) {
102
+ const { maxEntries, maxFileBytes, maxTotalBytes } = snapshotLimits(limits);
54
103
  const files = new Map();
55
104
  let entries = 0;
56
105
  let total = 0;
57
106
  async function walk(dir, prefix) {
58
- const stat = await lstat(dir);
59
- if (!stat.isDirectory() || stat.isSymbolicLink())
60
- fail("PLUGIN_PACKAGE_UNSAFE", "Package directories must not be symbolic links.");
107
+ assertRealDirectory(await lstat(dir), "Package directories must not be symbolic links.");
61
108
  for (const name of (await readdir(dir)).sort()) {
62
109
  if (++entries > maxEntries)
63
110
  fail("PLUGIN_PACKAGE_TOO_LARGE", "Package has too many entries.");
@@ -70,34 +117,9 @@ async function snapshot(sourceDir, limits = {}) {
70
117
  await walk(target, relative + "/");
71
118
  continue;
72
119
  }
73
- if (!info.isFile() || info.nlink !== 1)
74
- fail("PLUGIN_PACKAGE_UNSAFE", "Only regular files without hard links are allowed.");
75
- if (info.size > maxFileBytes || total + info.size > maxTotalBytes)
76
- fail("PLUGIN_PACKAGE_TOO_LARGE", "Package exceeds the file or total size limit.");
77
- const handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
78
- try {
79
- const current = await handle.stat();
80
- if (!current.isFile() || current.nlink !== 1 || current.ino !== info.ino || current.dev !== info.dev)
81
- fail("PLUGIN_PACKAGE_UNSAFE", "Package changed while reading.");
82
- // A bounded read also protects against a file growing after stat().
83
- const buffer = Buffer.alloc(info.size + 1);
84
- let length = 0;
85
- while (length < buffer.length) {
86
- const read = await handle.read(buffer, length, buffer.length - length, null);
87
- if (read.bytesRead === 0)
88
- break;
89
- length += read.bytesRead;
90
- }
91
- if (length > maxFileBytes || total + length > maxTotalBytes)
92
- fail("PLUGIN_PACKAGE_TOO_LARGE", "Package grew past its size limit.");
93
- if (length > info.size || (await handle.stat()).size !== length)
94
- fail("PLUGIN_PACKAGE_UNSAFE", "Package changed while reading.");
95
- total += length;
96
- files.set(relative, Buffer.from(buffer.subarray(0, length)));
97
- }
98
- finally {
99
- await handle.close();
100
- }
120
+ const bytes = await readStableFile({ target, info, maxFileBytes, remainingBytes: maxTotalBytes - total });
121
+ total += bytes.length;
122
+ files.set(relative, bytes);
101
123
  }
102
124
  }
103
125
  await walk(sourceDir, "");
@@ -126,153 +148,185 @@ function checkTierAndCode(candidate, files, tierPolicy) {
126
148
  fail("PLUGIN_MANIFEST_INVALID", "server/index.mjs is required.");
127
149
  tierPolicy.checkInstall({ manifest: candidate, files });
128
150
  }
129
- function validatePackage(files, deps) {
130
- const { builtInIds } = deps;
131
- let raw;
151
+ /** The parsed manifest JSON (current name first, then the legacy alias), or a refusal. */
152
+ function parseManifestFile(files) {
132
153
  const filename = PLUGIN_MANIFEST_FILENAMES.find(name => files.has(name)); // legacy alias
133
154
  try {
134
- raw = JSON.parse(filename === undefined ? "" : files.get(filename).toString("utf8"));
155
+ return JSON.parse(filename === undefined ? "" : files.get(filename).toString("utf8"));
135
156
  }
136
157
  catch {
137
158
  return fail("PLUGIN_MANIFEST_INVALID", `A valid ${MANIFEST} is required.`);
138
159
  }
139
- const candidate = raw;
140
- const id = typeof candidate?.id === "string" ? candidate.id : "";
160
+ }
161
+ /** Integrity must list exactly every packaged file except plugin manifests, each hash matching.
162
+ * Its shape needs no check here: `validatePackage` only calls this after `validateManifest` passed,
163
+ * which requires `integrity` and refuses anything but a plain object of sha256 strings. */
164
+ function assertIntegrity(candidate, files) {
165
+ const packaged = [...files.keys()].filter((key) => !PLUGIN_MANIFEST_FILENAMES.includes(key)).sort(); // legacy alias
166
+ if (JSON.stringify(Object.keys(candidate.integrity).sort()) !== JSON.stringify(packaged))
167
+ fail("PLUGIN_INTEGRITY_INVALID", "Integrity must list exactly every file except plugin manifests.");
168
+ for (const key of packaged)
169
+ if (candidate.integrity[key] !== hash(files.get(key)))
170
+ fail("PLUGIN_INTEGRITY_INVALID", `Integrity mismatch: ${key}`);
171
+ }
172
+ function validatePackage(files, deps) {
173
+ const { builtInIds } = deps;
174
+ const raw = parseManifestFile(files);
175
+ const id = typeof raw?.id === "string" ? raw.id : "";
141
176
  if (builtInIds.some((builtin) => builtin.toLowerCase() === id.toLowerCase()))
142
177
  fail("PLUGIN_SHADOWS_BUILT_IN", "Package id belongs to a built-in plugin.");
143
178
  const result = validateManifest({ ...deps, manifest: raw, folderName: id, builtInIds });
144
179
  // The manifest's own messages, so a refused declaration says what is wrong with it.
145
180
  if (result.errors.length)
146
181
  fail("PLUGIN_MANIFEST_INVALID", result.errors.map((error) => error.message).join("; "));
147
- // validateManifest owns the id grammar; only the version needs extra path-safety checks.
148
- if (!candidate || typeof candidate.version !== "string" || !semver.valid(candidate.version) || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(candidate.version))
149
- fail("PLUGIN_MANIFEST_INVALID", "Package manifest, id or version is invalid.");
182
+ // validateManifest owns the id grammar and the version: it refuses a non-object manifest and
183
+ // accepts only a canonical SemVer version (`isExactSemver`), whose alphabet [0-9A-Za-z.+-] starting
184
+ // with a digit is already path-safe — so the version can name an install folder as-is.
185
+ const candidate = raw;
150
186
  checkTierAndCode(candidate, files, deps.tierPolicy);
151
187
  if (typeof candidate.name !== "string" || !candidate.name.trim() || typeof candidate.sdkRange !== "string" || !semver.validRange(candidate.sdkRange))
152
188
  fail("PLUGIN_MANIFEST_INVALID", "A name and valid SDK range are required.");
153
- if (!candidate.integrity || typeof candidate.integrity !== "object" || Array.isArray(candidate.integrity))
154
- fail("PLUGIN_INTEGRITY_INVALID", "An integrity map is required.");
155
- const packaged = [...files.keys()].filter((key) => !PLUGIN_MANIFEST_FILENAMES.includes(key)).sort(); // legacy alias
156
- if (JSON.stringify(Object.keys(candidate.integrity).sort()) !== JSON.stringify(packaged))
157
- fail("PLUGIN_INTEGRITY_INVALID", "Integrity must list exactly every file except plugin manifests.");
158
- for (const key of packaged)
159
- if (candidate.integrity[key] !== hash(files.get(key)))
160
- fail("PLUGIN_INTEGRITY_INVALID", `Integrity mismatch: ${key}`);
189
+ assertIntegrity(candidate, files);
161
190
  return candidate;
162
191
  }
163
- async function checkDestination(manifest, input, deps) {
164
- const root = path.resolve(deps.installDir);
165
- const scan = deps.identityFilesystem ?? { lstat, readdir, readFile };
166
- const entries = await scan.readdir(root).catch((e) => { if (e.code === "ENOENT")
167
- return []; throw e; });
168
- const identity = readPluginIdentity({ manifest: manifest, name: manifest.id, namespace: deps.identityNamespace });
169
- const candidate = { ...identity, family: "site-runtime", localId: manifest.id };
170
- const builtIns = (deps.builtInManifests ?? []).map(builtIn => ({
171
- ...readPluginIdentity({ manifest: builtIn, name: builtIn.id, namespace: deps.identityNamespace }),
172
- family: "site-runtime", localId: builtIn.id, version: builtIn.version, enabled: false,
173
- }));
192
+ function identityOf(manifest, deps, name = manifest.id) {
193
+ return readPluginIdentity({ manifest: manifest, name, namespace: deps.identityNamespace });
194
+ }
195
+ function assertIdentityFree(candidate, installed) {
174
196
  try {
175
- assertPluginIdentityAvailable({ candidate, installed: builtIns });
197
+ assertPluginIdentityAvailable({ candidate, installed });
176
198
  }
177
199
  catch {
178
200
  fail("PLUGIN_ID_CONFLICT", "The publisher-qualified plugin id conflicts with an installed package.");
179
201
  }
180
- const warnUnavailableSlot = (localId, error) => {
181
- if (!['ENOENT', 'EACCES'].includes(error.code ?? ''))
182
- throw error;
183
- // A disappearing/unreadable neighbour is isolated; link refusals and other I/O faults remain fatal.
184
- (deps.warn ?? console.warn)(`Plugin '${localId}': installed slot is unavailable; omitted from identity admission.`);
185
- };
186
- for (const localId of entries) {
187
- const slot = path.join(root, localId);
188
- let versions;
202
+ }
203
+ function warnUnavailableSlot(deps, localId, error) {
204
+ if (!['ENOENT', 'EACCES'].includes(error.code ?? ''))
205
+ throw error;
206
+ // A disappearing/unreadable neighbour is isolated; link refusals and other I/O faults remain fatal.
207
+ (deps.warn ?? console.warn)(`Plugin '${localId}': installed slot is unavailable; omitted from identity admission.`);
208
+ }
209
+ /** Version names in one installed slot, or none when the slot is not a folder or is unavailable. */
210
+ async function scanSlotVersions(required) {
211
+ const { scan, slot } = required;
212
+ try {
213
+ const info = await scan.lstat(slot);
214
+ if (info.isSymbolicLink())
215
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin directory must not be a link.");
216
+ return info.isDirectory() ? await scan.readdir(slot) : [];
217
+ }
218
+ catch (error) {
219
+ warnUnavailableSlot(required.deps, required.localId, error);
220
+ return [];
221
+ }
222
+ }
223
+ async function isScannableVersion(required) {
224
+ try {
225
+ const versionInfo = await required.scan.lstat(required.versionDir);
226
+ if (versionInfo.isSymbolicLink())
227
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin version must not be a link.");
228
+ return versionInfo.isDirectory();
229
+ }
230
+ catch (error) {
231
+ warnUnavailableSlot(required.deps, required.localId, error);
232
+ return false;
233
+ }
234
+ }
235
+ async function findInstalledManifest(scan, versionDir) {
236
+ for (const filename of PLUGIN_MANIFEST_FILENAMES) { // legacy alias
237
+ const candidatePath = path.join(versionDir, filename);
189
238
  try {
190
- const info = await scan.lstat(slot);
191
- if (info.isSymbolicLink())
192
- fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin directory must not be a link.");
193
- if (!info.isDirectory())
194
- continue;
195
- versions = await scan.readdir(slot);
239
+ await scan.lstat(candidatePath);
240
+ return candidatePath;
196
241
  }
197
242
  catch (error) {
198
- warnUnavailableSlot(localId, error);
199
- continue;
200
- }
201
- for (const version of versions) {
202
- if (!semver.valid(version))
203
- continue;
204
- const versionDir = path.join(slot, version);
205
- try {
206
- const versionInfo = await scan.lstat(versionDir);
207
- if (versionInfo.isSymbolicLink())
208
- fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin version must not be a link.");
209
- if (!versionInfo.isDirectory())
210
- continue;
211
- }
212
- catch (error) {
213
- warnUnavailableSlot(localId, error);
214
- continue;
215
- }
216
- let installed;
217
- try {
218
- let manifestPath = path.join(versionDir, MANIFEST);
219
- for (const filename of PLUGIN_MANIFEST_FILENAMES) { // legacy alias
220
- const candidatePath = path.join(versionDir, filename);
221
- try {
222
- await scan.lstat(candidatePath);
223
- manifestPath = candidatePath;
224
- break;
225
- }
226
- catch (error) {
227
- if (error.code !== 'ENOENT')
228
- throw error;
229
- }
230
- }
231
- const manifestInfo = await scan.lstat(manifestPath);
232
- if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink())
233
- fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin manifests must not be links.");
234
- const installedManifest = JSON.parse(await scan.readFile(manifestPath, "utf8"));
235
- installed = readPluginIdentity({ manifest: installedManifest, name: localId, namespace: deps.identityNamespace });
236
- }
237
- catch (error) {
238
- if (error instanceof PluginInstallError)
239
- throw error;
240
- // Preserve link refusals while isolating one broken unrelated manifest.
241
- (deps.warn ?? console.warn)(`Plugin '${localId}': installed identity manifest is unreadable or invalid; omitted from identity admission.`);
242
- continue;
243
- }
244
- try {
245
- assertPluginIdentityAvailable({ candidate,
246
- installed: [{ ...installed, family: "site-runtime", localId, version, enabled: false }] });
247
- }
248
- catch {
249
- fail("PLUGIN_ID_CONFLICT", "The publisher-qualified plugin id conflicts with an installed package.");
250
- }
243
+ if (error.code !== 'ENOENT')
244
+ throw error;
251
245
  }
252
246
  }
253
- if (entries.some((name) => name.toLowerCase() === manifest.id.toLowerCase() && name !== manifest.id))
247
+ return path.join(versionDir, MANIFEST);
248
+ }
249
+ /** The installed version's identity, or undefined (with a warning) when its manifest is unreadable. */
250
+ async function readInstalledIdentity(required) {
251
+ const { scan, localId, deps } = required;
252
+ try {
253
+ const manifestPath = await findInstalledManifest(scan, required.versionDir);
254
+ const manifestInfo = await scan.lstat(manifestPath);
255
+ if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink())
256
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin manifests must not be links.");
257
+ const installedManifest = JSON.parse(await scan.readFile(manifestPath, "utf8"));
258
+ return readPluginIdentity({ manifest: installedManifest, name: localId, namespace: deps.identityNamespace });
259
+ }
260
+ catch (error) {
261
+ if (error instanceof PluginInstallError)
262
+ throw error;
263
+ // Preserve link refusals while isolating one broken unrelated manifest.
264
+ (deps.warn ?? console.warn)(`Plugin '${localId}': installed identity manifest is unreadable or invalid; omitted from identity admission.`);
265
+ return undefined;
266
+ }
267
+ }
268
+ /** Every installed version of one neighbour slot must not already hold the candidate's identity. */
269
+ async function assertSlotIdentityFree(required) {
270
+ const { scan, localId, deps } = required;
271
+ const slot = path.join(required.root, localId);
272
+ for (const version of await scanSlotVersions({ scan, slot, localId, deps })) {
273
+ if (!semver.valid(version))
274
+ continue;
275
+ const versionDir = path.join(slot, version);
276
+ if (!(await isScannableVersion({ scan, versionDir, localId, deps })))
277
+ continue;
278
+ const installed = await readInstalledIdentity({ scan, versionDir, localId, deps });
279
+ if (installed)
280
+ assertIdentityFree(required.candidate, [{ ...installed, family: "site-runtime", localId, version, enabled: false }]);
281
+ }
282
+ }
283
+ /** Version folder names in an installed slot, dotfiles excluded; any non-semver name is refused. */
284
+ async function readInstalledVersions(slot) {
285
+ const versions = (await readdir(slot)).filter(name => !name.startsWith('.'));
286
+ if (versions.some(version => !semver.valid(version)))
287
+ fail('PLUGIN_ID_CONFLICT', 'Existing plugin has an unrecognized version folder.');
288
+ return versions;
289
+ }
290
+ /** Case aliases, Trash entries and enabled plugins block the slot before its versions are compared. */
291
+ async function assertSlotAvailable(required) {
292
+ const { manifest, root, deps } = required;
293
+ const id = manifest.id.toLowerCase();
294
+ if (required.entries.some((name) => name.toLowerCase() === id && name !== manifest.id))
254
295
  fail("PLUGIN_ID_CONFLICT", "A plugin id differs only by letter case.");
255
296
  if (await exists(path.join(path.dirname(root), path.basename(root) + "-trash", manifest.id)))
256
297
  fail("PLUGIN_IN_TRASH", "Restore or delete this plugin in Trash first.");
257
- const slot = path.join(root, manifest.id);
258
- const versionExists = await exists(path.join(slot, manifest.version));
259
- if ((!deps.versionAppend || versionExists) && (await deps.repo.listAll()).some((row) => row.pluginId.toLowerCase() === manifest.id.toLowerCase() && row.enabled))
298
+ const versionExists = await exists(path.join(root, manifest.id, manifest.version));
299
+ if ((!deps.versionAppend || versionExists) && (await deps.repo.listAll()).some((row) => row.pluginId.toLowerCase() === id && row.enabled))
260
300
  fail("PLUGIN_ENABLED", "Turn the plugin off in every workspace first.");
301
+ }
302
+ /** The latest installed version this package upgrades from; downgrades and silent re-installs are refused. */
303
+ async function latestInstalledVersion(required) {
304
+ const { manifest, slot, deps } = required;
261
305
  if (!(await exists(slot)))
262
306
  return undefined;
263
- const stat = await lstat(slot);
264
- if (!stat.isDirectory() || stat.isSymbolicLink())
265
- fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin directory must not be a link.");
266
- const versions = (await readdir(slot)).filter(name => !name.startsWith('.'));
267
- if (versions.some((version) => !semver.valid(version)))
268
- fail("PLUGIN_ID_CONFLICT", "Existing plugin has an unrecognized version folder.");
307
+ assertRealDirectory(await lstat(slot), "Installed plugin directory must not be a link.");
308
+ const versions = await readInstalledVersions(slot);
269
309
  const latest = versions.sort(semver.rcompare)[0];
270
310
  if (latest && semver.lt(manifest.version, latest))
271
311
  fail("PLUGIN_DOWNGRADE", "Installing an older version is not allowed.");
272
- if (versions.some((version) => semver.eq(version, manifest.version)) && (deps.versionAppend || !input.replace))
312
+ if (versions.some((version) => semver.eq(version, manifest.version)) && (deps.versionAppend || !required.input.replace))
273
313
  fail("PLUGIN_VERSION_EXISTS", deps.versionAppend ? "Version append requires a new version; installed bytes are immutable." : "This version exists. Choose replace explicitly.");
274
314
  return latest;
275
315
  }
316
+ async function checkDestination(manifest, input, deps) {
317
+ const root = path.resolve(deps.installDir);
318
+ const scan = deps.identityFilesystem ?? { lstat, readdir, readFile };
319
+ const entries = await scan.readdir(root).catch((e) => { if (e.code === "ENOENT")
320
+ return []; throw e; });
321
+ const candidate = { ...identityOf(manifest, deps), family: "site-runtime", localId: manifest.id };
322
+ assertIdentityFree(candidate, (deps.builtInManifests ?? []).map(builtIn => ({
323
+ ...identityOf(builtIn, deps), family: "site-runtime", localId: builtIn.id, version: builtIn.version, enabled: false,
324
+ })));
325
+ for (const localId of entries)
326
+ await assertSlotIdentityFree({ scan, root, localId, candidate, deps });
327
+ await assertSlotAvailable({ manifest, entries, root, deps });
328
+ return latestInstalledVersion({ manifest, input, slot: path.join(root, manifest.id), deps });
329
+ }
276
330
  /** Retire obsolete immutable source releases after a successful controlled reload.
277
331
  * All workspace active pointers survive, plus the newest three versions for rollback.
278
332
  * Uses the installer's publication lock so pruning cannot overlap a package install.
@@ -285,15 +339,10 @@ export async function pruneSitePluginVersions(required, _optional = {}) {
285
339
  fail('PLUGIN_PACKAGE_UNSAFE', 'Invalid plugin id.');
286
340
  const root = path.resolve(required.installDir);
287
341
  const slot = path.join(root, required.id);
288
- for (const target of [root, slot]) {
289
- const info = await lstat(target);
290
- if (!info.isDirectory() || info.isSymbolicLink())
291
- fail('PLUGIN_PACKAGE_UNSAFE', 'Installed plugin directory must not be a link.');
292
- }
342
+ for (const target of [root, slot])
343
+ assertRealDirectory(await lstat(target), 'Installed plugin directory must not be a link.');
293
344
  return withPluginInstallLock({ root, run: async () => {
294
- const versions = (await readdir(slot)).filter(name => !name.startsWith('.'));
295
- if (versions.some(version => !semver.valid(version)))
296
- fail('PLUGIN_ID_CONFLICT', 'Existing plugin has an unrecognized version folder.');
345
+ const versions = await readInstalledVersions(slot);
297
346
  const retained = new Set(versions.sort(semver.rcompare).slice(0, 3));
298
347
  for (const row of await required.repo.listAll())
299
348
  if (row.pluginId === required.id && row.enabled)
@@ -310,7 +359,7 @@ async function inspect(input, deps) {
310
359
  const upgradeFrom = await checkDestination(manifest, input, deps);
311
360
  // Include manifest bytes: changed capabilities/name/version must invalidate human consent too.
312
361
  const digest = digestSitePluginSnapshot({ files });
313
- const identity = readPluginIdentity({ manifest: manifest, name: manifest.id, namespace: deps.identityNamespace });
362
+ const identity = identityOf(manifest, deps);
314
363
  const preview = { warnings: identity.warnings, publisherId: identity.id, provides: identity.provides, keywords: identity.keywords, id: manifest.id, name: manifest.name, version: manifest.version, tier: manifest.tier, capabilities: manifest.capabilities, hooks: manifest.hooks, hasCode: manifest.tier !== "tier-1", contentTypes: deps.declarativeContentTypes.parse({ value: manifest.contentTypes }).decls.map((decl) => decl.key), conflicts: await deps.conflicts({ manifest }), digest, ...(upgradeFrom ? { upgradeFrom } : {}) };
315
364
  return { files, manifest, preview };
316
365
  }
@@ -344,7 +393,7 @@ export async function snapshotSitePluginPackage(required, optional = {}) {
344
393
  * @returns A SHA-256 digest covering the manifest and every retained file.
345
394
  */
346
395
  export function digestSitePluginSnapshot(required, _optional = {}) {
347
- return hash(Buffer.from(JSON.stringify([...required.files].map(([key, bytes]) => [key, hash(bytes)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))));
396
+ return hash(Buffer.from(JSON.stringify([...required.files].map(([key, bytes]) => [key, hash(bytes)]).sort(([a], [b]) => a < b ? -1 : 1))));
348
397
  }
349
398
  export async function computePluginIntegrity(required, _optional = {}) {
350
399
  return Object.fromEntries([...await snapshot(required.sourceDir)].filter(([key]) => !PLUGIN_MANIFEST_FILENAMES.includes(key)).map(([key, bytes]) => [key, hash(bytes)])); // legacy alias
@@ -371,6 +420,46 @@ async function withPluginInstallLock(required, _optional = {}) {
371
420
  await rm(lock, { recursive: true, force: true });
372
421
  }
373
422
  }
423
+ /** Writes the retained bytes (manifest canonicalized) into a fresh staged version folder. */
424
+ async function writeStagedVersion(required) {
425
+ for (const [key, bytes] of canonicalizePluginManifest({ files: required.files })) { // legacy alias
426
+ const target = path.join(required.versionDir, key);
427
+ await mkdir(path.dirname(target), { recursive: true });
428
+ await writeFile(target, bytes, { flag: "wx" });
429
+ }
430
+ }
431
+ /** Swaps the staged version in; on failure the replaced copy is put back before rethrowing. */
432
+ async function swapVersion(required) {
433
+ const { versionDir, liveVersion, backup } = required;
434
+ const replaced = await exists(liveVersion);
435
+ if (replaced)
436
+ await rename(liveVersion, backup);
437
+ try {
438
+ await rename(versionDir, liveVersion);
439
+ }
440
+ catch (error) {
441
+ if (replaced)
442
+ await rename(backup, liveVersion).catch(() => fail("PLUGIN_INSTALL_RECOVERY_REQUIRED", `Restore the previous version from ${backup} before retrying.`));
443
+ throw error;
444
+ }
445
+ }
446
+ /** Publishes the staged slot: a first install renames the whole slot, an upgrade swaps one version. */
447
+ async function publishStaged(required) {
448
+ const { live, staging, manifest } = required;
449
+ const stagedSlot = path.join(staging, "new");
450
+ if (!(await exists(live))) {
451
+ await rename(stagedSlot, live);
452
+ return;
453
+ }
454
+ await swapVersion({ versionDir: path.join(stagedSlot, manifest.version), liveVersion: path.join(live, manifest.version), backup: path.join(staging, "old") });
455
+ // Publish first, retire old versions second: discovery always sees a complete upgrade.
456
+ if (required.versionAppend)
457
+ return;
458
+ for (const version of await readdir(live)) {
459
+ if (version !== manifest.version)
460
+ await rm(path.join(live, version), { recursive: true, force: true });
461
+ }
462
+ }
374
463
  /** Publication and retention use the same installer-owned cross-process lock. */
375
464
  export async function installSitePlugin(required, _optional = {}) {
376
465
  const optional = required.deps;
@@ -379,60 +468,23 @@ export async function installSitePlugin(required, _optional = {}) {
379
468
  if (preview.digest !== required.expectedDigest)
380
469
  fail("PLUGIN_CHANGED_SINCE_PREVIEW", "Package changed since preview. Review it again.");
381
470
  for (const target of [root, root + "-staging", root + "-trash"]) {
382
- if (await exists(target)) {
383
- const info = await lstat(target);
384
- if (!info.isDirectory() || info.isSymbolicLink())
385
- fail("PLUGIN_PACKAGE_UNSAFE", "Install, staging and Trash roots must be real directories.");
386
- }
471
+ if (await exists(target))
472
+ assertRealDirectory(await lstat(target), "Install, staging and Trash roots must be real directories.");
387
473
  }
388
474
  return withPluginInstallLock({ root, run: async () => {
389
475
  let staging;
390
476
  try {
391
477
  await mkdir(root + "-staging", { recursive: true });
392
478
  staging = await mkdtemp(path.join(root + "-staging", "install-"));
393
- const stagedSlot = path.join(staging, "new");
394
- const versionDir = path.join(stagedSlot, manifest.version);
395
- for (const [key, bytes] of canonicalizePluginManifest({ files })) { // legacy alias
396
- const target = path.join(versionDir, key);
397
- await mkdir(path.dirname(target), { recursive: true });
398
- await writeFile(target, bytes, { flag: "wx" });
399
- }
479
+ await writeStagedVersion({ versionDir: path.join(staging, "new", manifest.version), files });
400
480
  await checkDestination(manifest, required, optional);
401
481
  await mkdir(root, { recursive: true });
402
- const live = path.join(root, manifest.id);
403
- if (!(await exists(live))) {
404
- await rename(stagedSlot, live);
405
- }
406
- else {
407
- const liveVersion = path.join(live, manifest.version);
408
- const backup = path.join(staging, "old");
409
- const replaced = await exists(liveVersion);
410
- if (replaced)
411
- await rename(liveVersion, backup);
412
- try {
413
- await rename(versionDir, liveVersion);
414
- }
415
- catch (error) {
416
- if (replaced) {
417
- try {
418
- await rename(backup, liveVersion);
419
- }
420
- catch {
421
- // Never let cleanup erase the sole remaining copy when rollback itself fails.
422
- staging = undefined;
423
- fail("PLUGIN_INSTALL_RECOVERY_REQUIRED", `Restore the previous version from ${backup} before retrying.`);
424
- }
425
- }
426
- throw error;
427
- }
428
- // Publish first, retire old versions second: discovery always sees a complete upgrade.
429
- if (!optional.versionAppend) {
430
- for (const version of await readdir(live)) {
431
- if (version !== manifest.version)
432
- await rm(path.join(live, version), { recursive: true, force: true });
433
- }
434
- }
435
- }
482
+ await publishStaged({ live: path.join(root, manifest.id), staging, manifest, versionAppend: optional.versionAppend }).catch((error) => {
483
+ // Never let cleanup erase the sole remaining copy when rollback itself fails.
484
+ if (error instanceof PluginInstallError && error.code === "PLUGIN_INSTALL_RECOVERY_REQUIRED")
485
+ staging = undefined;
486
+ throw error;
487
+ });
436
488
  return preview;
437
489
  }
438
490
  finally {