@jini-ai/plugins 0.5.0 → 0.5.2

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 (35) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/glue/capability-gate.js +1 -1
  3. package/dist/host/browser-providers.d.ts +2 -9
  4. package/dist/host/browser-providers.js +34 -18
  5. package/dist/host/capability-sdk.js +1 -1
  6. package/dist/host/claim-conflicts.d.ts +4 -4
  7. package/dist/host/claim-conflicts.js +4 -4
  8. package/dist/host/contributions.d.ts +4 -1
  9. package/dist/host/contributions.js +19 -8
  10. package/dist/host/discovery-types.d.ts +2 -2
  11. package/dist/host/hook-registry.js +7 -5
  12. package/dist/host/index.d.ts +1 -0
  13. package/dist/host/index.js +1 -0
  14. package/dist/host/manifest-types.d.ts +103 -0
  15. package/dist/host/manifest-types.js +2 -0
  16. package/dist/host/manifest.d.ts +5 -97
  17. package/dist/host/manifest.js +33 -24
  18. package/dist/host/node/discovery.js +27 -22
  19. package/dist/host/node/install.js +257 -192
  20. package/dist/host/node/loader.js +85 -67
  21. package/dist/host/node/module-snapshot.js +3 -2
  22. package/dist/host/node/open-flags.d.ts +18 -0
  23. package/dist/host/node/open-flags.js +14 -0
  24. package/dist/host/node/package-files.js +18 -12
  25. package/dist/host/node/source-drafts.d.ts +2 -0
  26. package/dist/host/node/source-drafts.js +93 -59
  27. package/dist/host/plugin-claims.js +6 -4
  28. package/dist/host/plugin-format.d.ts +14 -0
  29. package/dist/host/plugin-format.js +21 -0
  30. package/dist/host/ports.d.ts +4 -4
  31. package/dist/host/tool-contributions.js +3 -1
  32. package/dist/host/worker/protocol.js +8 -6
  33. package/dist/host/worker/run-call.d.ts +1 -1
  34. package/dist/host/worker/run-call.js +20 -17
  35. package/package.json +5 -5
@@ -11,6 +11,7 @@ import path from "node:path";
11
11
  import { createHash } from "node:crypto";
12
12
  import * as semver from "semver";
13
13
  import { validateManifest, validatePluginIdFormat } from "../manifest.js";
14
+ import { PLUGIN_MANIFEST_FILENAME as MANIFEST, PLUGIN_MANIFEST_FILENAMES, canonicalizePluginManifest } from "../plugin-format.js";
14
15
  export class PluginInstallError extends Error {
15
16
  code;
16
17
  constructor(code, message) {
@@ -19,13 +20,16 @@ export class PluginInstallError extends Error {
19
20
  this.name = "PluginInstallError";
20
21
  }
21
22
  }
22
- const MANIFEST = "tovu.plugin.json";
23
23
  const MAX_ENTRIES = 4096;
24
24
  const MAX_FILE_BYTES = 16 * 1024 * 1024;
25
25
  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, "");
@@ -117,7 +139,7 @@ const DECLARATIVE_DATA_FILE = /(?:^|\/)(?:LICENSE|[^/]+\.(?:json|md|txt|png|jpe?
117
139
  */
118
140
  function checkTierAndCode(candidate, files, tierPolicy) {
119
141
  if (candidate.tier === "tier-1") {
120
- const code = [...files.keys()].filter((key) => key !== MANIFEST && !DECLARATIVE_DATA_FILE.test(key));
142
+ const code = [...files.keys()].filter((key) => !PLUGIN_MANIFEST_FILENAMES.includes(key) && !DECLARATIVE_DATA_FILE.test(key)); // legacy alias
121
143
  if (code.length)
122
144
  fail("PLUGIN_MANIFEST_INVALID", `A declarative (tier-1) plugin must not ship code: ${code.join(", ")}`);
123
145
  return;
@@ -126,140 +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) {
153
+ const filename = PLUGIN_MANIFEST_FILENAMES.find(name => files.has(name)); // legacy alias
132
154
  try {
133
- raw = JSON.parse(files.get(MANIFEST)?.toString("utf8") ?? "");
155
+ return JSON.parse(filename === undefined ? "" : files.get(filename).toString("utf8"));
134
156
  }
135
157
  catch {
136
- return fail("PLUGIN_MANIFEST_INVALID", "A valid tovu.plugin.json is required.");
158
+ return fail("PLUGIN_MANIFEST_INVALID", `A valid ${MANIFEST} is required.`);
137
159
  }
138
- const candidate = raw;
139
- 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 : "";
140
176
  if (builtInIds.some((builtin) => builtin.toLowerCase() === id.toLowerCase()))
141
177
  fail("PLUGIN_SHADOWS_BUILT_IN", "Package id belongs to a built-in plugin.");
142
178
  const result = validateManifest({ ...deps, manifest: raw, folderName: id, builtInIds });
143
179
  // The manifest's own messages, so a refused declaration says what is wrong with it.
144
180
  if (result.errors.length)
145
181
  fail("PLUGIN_MANIFEST_INVALID", result.errors.map((error) => error.message).join("; "));
146
- // validateManifest owns the id grammar; only the version needs extra path-safety checks.
147
- if (!candidate || typeof candidate.version !== "string" || !semver.valid(candidate.version) || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(candidate.version))
148
- 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;
149
186
  checkTierAndCode(candidate, files, deps.tierPolicy);
150
187
  if (typeof candidate.name !== "string" || !candidate.name.trim() || typeof candidate.sdkRange !== "string" || !semver.validRange(candidate.sdkRange))
151
188
  fail("PLUGIN_MANIFEST_INVALID", "A name and valid SDK range are required.");
152
- if (!candidate.integrity || typeof candidate.integrity !== "object" || Array.isArray(candidate.integrity))
153
- fail("PLUGIN_INTEGRITY_INVALID", "An integrity map is required.");
154
- const packaged = [...files.keys()].filter((key) => key !== MANIFEST).sort();
155
- if (JSON.stringify(Object.keys(candidate.integrity).sort()) !== JSON.stringify(packaged))
156
- fail("PLUGIN_INTEGRITY_INVALID", "Integrity must list exactly every file except tovu.plugin.json.");
157
- for (const key of packaged)
158
- if (candidate.integrity[key] !== hash(files.get(key)))
159
- fail("PLUGIN_INTEGRITY_INVALID", `Integrity mismatch: ${key}`);
189
+ assertIntegrity(candidate, files);
160
190
  return candidate;
161
191
  }
162
- async function checkDestination(manifest, input, deps) {
163
- const root = path.resolve(deps.installDir);
164
- const scan = deps.identityFilesystem ?? { lstat, readdir, readFile };
165
- const entries = await scan.readdir(root).catch((e) => { if (e.code === "ENOENT")
166
- return []; throw e; });
167
- const identity = readPluginIdentity({ manifest: manifest, name: manifest.id, namespace: deps.identityNamespace ?? "tovu" });
168
- const candidate = { ...identity, family: "site-runtime", localId: manifest.id };
169
- const builtIns = (deps.builtInManifests ?? []).map(builtIn => ({
170
- ...readPluginIdentity({ manifest: builtIn, name: builtIn.id, namespace: deps.identityNamespace ?? "tovu" }),
171
- family: "site-runtime", localId: builtIn.id, version: builtIn.version, enabled: false,
172
- }));
192
+ function identityOf(manifest, deps, name = manifest.id) {
193
+ return readPluginIdentity({ manifest: manifest, name, namespace: deps.identityNamespace });
194
+ }
195
+ function assertIdentityFree(candidate, installed) {
173
196
  try {
174
- assertPluginIdentityAvailable({ candidate, installed: builtIns });
197
+ assertPluginIdentityAvailable({ candidate, installed });
175
198
  }
176
199
  catch {
177
200
  fail("PLUGIN_ID_CONFLICT", "The publisher-qualified plugin id conflicts with an installed package.");
178
201
  }
179
- const warnUnavailableSlot = (localId, error) => {
180
- if (!['ENOENT', 'EACCES'].includes(error.code ?? ''))
181
- throw error;
182
- // A disappearing/unreadable neighbour is isolated; link refusals and other I/O faults remain fatal.
183
- (deps.warn ?? console.warn)(`Plugin '${localId}': installed slot is unavailable; omitted from identity admission.`);
184
- };
185
- for (const localId of entries) {
186
- const slot = path.join(root, localId);
187
- 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);
188
238
  try {
189
- const info = await scan.lstat(slot);
190
- if (info.isSymbolicLink())
191
- fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin directory must not be a link.");
192
- if (!info.isDirectory())
193
- continue;
194
- versions = await scan.readdir(slot);
239
+ await scan.lstat(candidatePath);
240
+ return candidatePath;
195
241
  }
196
242
  catch (error) {
197
- warnUnavailableSlot(localId, error);
198
- continue;
199
- }
200
- for (const version of versions) {
201
- if (!semver.valid(version))
202
- continue;
203
- const versionDir = path.join(slot, version);
204
- try {
205
- const versionInfo = await scan.lstat(versionDir);
206
- if (versionInfo.isSymbolicLink())
207
- fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin version must not be a link.");
208
- if (!versionInfo.isDirectory())
209
- continue;
210
- }
211
- catch (error) {
212
- warnUnavailableSlot(localId, error);
213
- continue;
214
- }
215
- const manifestPath = path.join(versionDir, MANIFEST);
216
- let installed;
217
- try {
218
- const manifestInfo = await scan.lstat(manifestPath);
219
- if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink())
220
- fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin manifests must not be links.");
221
- const installedManifest = JSON.parse(await scan.readFile(manifestPath, "utf8"));
222
- installed = readPluginIdentity({ manifest: installedManifest, name: localId, namespace: deps.identityNamespace ?? "tovu" });
223
- }
224
- catch (error) {
225
- if (error instanceof PluginInstallError)
226
- throw error;
227
- // Preserve link refusals while isolating one broken unrelated manifest.
228
- (deps.warn ?? console.warn)(`Plugin '${localId}': installed identity manifest is unreadable or invalid; omitted from identity admission.`);
229
- continue;
230
- }
231
- try {
232
- assertPluginIdentityAvailable({ candidate,
233
- installed: [{ ...installed, family: "site-runtime", localId, version, enabled: false }] });
234
- }
235
- catch {
236
- fail("PLUGIN_ID_CONFLICT", "The publisher-qualified plugin id conflicts with an installed package.");
237
- }
243
+ if (error.code !== 'ENOENT')
244
+ throw error;
238
245
  }
239
246
  }
240
- 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))
241
295
  fail("PLUGIN_ID_CONFLICT", "A plugin id differs only by letter case.");
242
296
  if (await exists(path.join(path.dirname(root), path.basename(root) + "-trash", manifest.id)))
243
297
  fail("PLUGIN_IN_TRASH", "Restore or delete this plugin in Trash first.");
244
- const slot = path.join(root, manifest.id);
245
- const versionExists = await exists(path.join(slot, manifest.version));
246
- 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))
247
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;
248
305
  if (!(await exists(slot)))
249
306
  return undefined;
250
- const stat = await lstat(slot);
251
- if (!stat.isDirectory() || stat.isSymbolicLink())
252
- fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin directory must not be a link.");
253
- const versions = (await readdir(slot)).filter(name => !name.startsWith('.'));
254
- if (versions.some((version) => !semver.valid(version)))
255
- 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);
256
309
  const latest = versions.sort(semver.rcompare)[0];
257
310
  if (latest && semver.lt(manifest.version, latest))
258
311
  fail("PLUGIN_DOWNGRADE", "Installing an older version is not allowed.");
259
- 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))
260
313
  fail("PLUGIN_VERSION_EXISTS", deps.versionAppend ? "Version append requires a new version; installed bytes are immutable." : "This version exists. Choose replace explicitly.");
261
314
  return latest;
262
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
+ }
263
330
  /** Retire obsolete immutable source releases after a successful controlled reload.
264
331
  * All workspace active pointers survive, plus the newest three versions for rollback.
265
332
  * Uses the installer's publication lock so pruning cannot overlap a package install.
@@ -272,15 +339,10 @@ export async function pruneSitePluginVersions(required, _optional = {}) {
272
339
  fail('PLUGIN_PACKAGE_UNSAFE', 'Invalid plugin id.');
273
340
  const root = path.resolve(required.installDir);
274
341
  const slot = path.join(root, required.id);
275
- for (const target of [root, slot]) {
276
- const info = await lstat(target);
277
- if (!info.isDirectory() || info.isSymbolicLink())
278
- fail('PLUGIN_PACKAGE_UNSAFE', 'Installed plugin directory must not be a link.');
279
- }
342
+ for (const target of [root, slot])
343
+ assertRealDirectory(await lstat(target), 'Installed plugin directory must not be a link.');
280
344
  return withPluginInstallLock({ root, run: async () => {
281
- const versions = (await readdir(slot)).filter(name => !name.startsWith('.'));
282
- if (versions.some(version => !semver.valid(version)))
283
- fail('PLUGIN_ID_CONFLICT', 'Existing plugin has an unrecognized version folder.');
345
+ const versions = await readInstalledVersions(slot);
284
346
  const retained = new Set(versions.sort(semver.rcompare).slice(0, 3));
285
347
  for (const row of await required.repo.listAll())
286
348
  if (row.pluginId === required.id && row.enabled)
@@ -297,7 +359,7 @@ async function inspect(input, deps) {
297
359
  const upgradeFrom = await checkDestination(manifest, input, deps);
298
360
  // Include manifest bytes: changed capabilities/name/version must invalidate human consent too.
299
361
  const digest = digestSitePluginSnapshot({ files });
300
- const identity = readPluginIdentity({ manifest: manifest, name: manifest.id, namespace: deps.identityNamespace ?? "tovu" });
362
+ const identity = identityOf(manifest, deps);
301
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 } : {}) };
302
364
  return { files, manifest, preview };
303
365
  }
@@ -331,10 +393,10 @@ export async function snapshotSitePluginPackage(required, optional = {}) {
331
393
  * @returns A SHA-256 digest covering the manifest and every retained file.
332
394
  */
333
395
  export function digestSitePluginSnapshot(required, _optional = {}) {
334
- 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))));
335
397
  }
336
398
  export async function computePluginIntegrity(required, _optional = {}) {
337
- return Object.fromEntries([...await snapshot(required.sourceDir)].filter(([key]) => key !== MANIFEST).map(([key, bytes]) => [key, hash(bytes)]));
399
+ return Object.fromEntries([...await snapshot(required.sourceDir)].filter(([key]) => !PLUGIN_MANIFEST_FILENAMES.includes(key)).map(([key, bytes]) => [key, hash(bytes)])); // legacy alias
338
400
  }
339
401
  export async function previewSitePluginInstall(required, _optional = {}) {
340
402
  return (await inspect(required, required.deps)).preview;
@@ -358,6 +420,46 @@ async function withPluginInstallLock(required, _optional = {}) {
358
420
  await rm(lock, { recursive: true, force: true });
359
421
  }
360
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
+ }
361
463
  /** Publication and retention use the same installer-owned cross-process lock. */
362
464
  export async function installSitePlugin(required, _optional = {}) {
363
465
  const optional = required.deps;
@@ -366,60 +468,23 @@ export async function installSitePlugin(required, _optional = {}) {
366
468
  if (preview.digest !== required.expectedDigest)
367
469
  fail("PLUGIN_CHANGED_SINCE_PREVIEW", "Package changed since preview. Review it again.");
368
470
  for (const target of [root, root + "-staging", root + "-trash"]) {
369
- if (await exists(target)) {
370
- const info = await lstat(target);
371
- if (!info.isDirectory() || info.isSymbolicLink())
372
- fail("PLUGIN_PACKAGE_UNSAFE", "Install, staging and Trash roots must be real directories.");
373
- }
471
+ if (await exists(target))
472
+ assertRealDirectory(await lstat(target), "Install, staging and Trash roots must be real directories.");
374
473
  }
375
474
  return withPluginInstallLock({ root, run: async () => {
376
475
  let staging;
377
476
  try {
378
477
  await mkdir(root + "-staging", { recursive: true });
379
478
  staging = await mkdtemp(path.join(root + "-staging", "install-"));
380
- const stagedSlot = path.join(staging, "new");
381
- const versionDir = path.join(stagedSlot, manifest.version);
382
- for (const [key, bytes] of files) {
383
- const target = path.join(versionDir, key);
384
- await mkdir(path.dirname(target), { recursive: true });
385
- await writeFile(target, bytes, { flag: "wx" });
386
- }
479
+ await writeStagedVersion({ versionDir: path.join(staging, "new", manifest.version), files });
387
480
  await checkDestination(manifest, required, optional);
388
481
  await mkdir(root, { recursive: true });
389
- const live = path.join(root, manifest.id);
390
- if (!(await exists(live))) {
391
- await rename(stagedSlot, live);
392
- }
393
- else {
394
- const liveVersion = path.join(live, manifest.version);
395
- const backup = path.join(staging, "old");
396
- const replaced = await exists(liveVersion);
397
- if (replaced)
398
- await rename(liveVersion, backup);
399
- try {
400
- await rename(versionDir, liveVersion);
401
- }
402
- catch (error) {
403
- if (replaced) {
404
- try {
405
- await rename(backup, liveVersion);
406
- }
407
- catch {
408
- // Never let cleanup erase the sole remaining copy when rollback itself fails.
409
- staging = undefined;
410
- fail("PLUGIN_INSTALL_RECOVERY_REQUIRED", `Restore the previous version from ${backup} before retrying.`);
411
- }
412
- }
413
- throw error;
414
- }
415
- // Publish first, retire old versions second: discovery always sees a complete upgrade.
416
- if (!optional.versionAppend) {
417
- for (const version of await readdir(live)) {
418
- if (version !== manifest.version)
419
- await rm(path.join(live, version), { recursive: true, force: true });
420
- }
421
- }
422
- }
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
+ });
423
488
  return preview;
424
489
  }
425
490
  finally {