Skip to content

Commit f6d16b3

Browse files
committed
fix(cli)!: os plugin install and the boot loader parse the compiled manifest through ManifestSchema
One helper, readCompiledPluginManifest in @objectstack/runtime, parses an artifact's objectstack.plugin.json through ManifestSchema for both doors. os plugin install refuses an invalid manifest before unpacking as manifest_invalid with the schema's issues (for packaging: 'manifest-deps', the retirement prescription); the boot loader refuses the plugin by name with the schema's message, non-fatal, before importing anything. os plugin build's native-addon refusal now names, for a native package, the files importing it and the chain from the plugin's own source. Claude-Session: https://claude.ai/code/session_016WV4czY8bzmjKmuhj1GP9c Co-authored-by: Claude <noreply@anthropic.com>
1 parent 81d00a4 commit f6d16b3

12 files changed

Lines changed: 289 additions & 52 deletions
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@objectstack/cli': minor
3+
'@objectstack/runtime': minor
4+
---
5+
6+
fix(cli)!: `os plugin install` and the boot-time loader parse an artifact's compiled manifest through `ManifestSchema`, so a stale `.osplugin` (e.g. `packaging: 'manifest-deps'`) is refused with the schema's prescription instead of failing at boot as `import_failed`
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: narrowed
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped: `ManifestSchema` is consumed as it stands, and what changes is that two more doors hold the compiled manifest inside an artifact to it, as `os plugin build` already holds the source manifest. The refusal is the schema's own message (for `manifest-deps`, the retirement prescription), and the fix is to the source manifest and a rebuild, so there is nothing new for a metadata migration to rewrite and no tombstone. -->
12+
13+
**BREAKING** accept-set narrowing at `os plugin install` (`@objectstack/cli`) and at the boot-time loader for installed plugins (`@objectstack/runtime`'s `loadInstalledPlugins` / `verifyInstalledPlugins`, run by `os serve`, `os dev` and `os start`).
14+
15+
- **Before.** Both doors `JSON.parse`d the artifact's `objectstack.plugin.json` and read only `id` and `version` (and `runtime`, `main`, `integrity`, `permissions` by hand). An artifact built before a schema change installed: one carrying the retired `packaging: 'manifest-deps'` installed, and at boot its externalized imports failed and it was refused as `import_failed`, without the retirement prescription. Any other compiled-manifest drift (a missing `name` or `type`, an unknown key) installed the same way.
16+
- **Now.** One helper, `readCompiledPluginManifest` (exported by `@objectstack/runtime`), parses the compiled manifest through `ManifestSchema` for both doors.
17+
- `os plugin install` refuses an invalid one before anything is unpacked, as `manifest_invalid`, listing the schema's issues (`--json`: `details`). For `manifest-deps` that is the retirement prescription. Nothing is written under the plugin home and no installation is recorded.
18+
- The boot loader refuses the plugin by name as `manifest_invalid` (a new `InstalledPluginRefusalCode`), with the schema's message, before anything of it is imported. It stays non-fatal: the boot goes on and every other installed plugin loads.
19+
- `os plugin install`'s `manifest_incomplete` and `integrity_malformed` refusals are gone: a missing `id` / `version` and a malformed `integrity` map are schema issues, refused as `manifest_invalid`.
20+
- **Also.** `os plugin build`'s native-addon refusal names, for a bundled package that builds or ships a native addon, the files that import it and the chain that reaches it from the plugin's own source (`src/index.ts → ws → bufferutil`), the way the `.node`-module line already names its importers. A transitive hit now traces to the direct dependency.
21+
- **Who sees it.** Anyone installing, or booting with, an `.osplugin` whose compiled manifest `ManifestSchema` refuses: one built by an `os plugin build` from before a schema change, or one assembled by hand.
22+
23+
**The remedy.** Fix the plugin's source `objectstack.plugin.json` as the refusal says (for `manifest-deps`: delete the `packaging` key; `bundled` is the default and the only strategy) and rebuild the artifact with `os plugin build`, then sign and install it again. An artifact `os plugin build` produced from a valid manifest installs and boots unchanged.

‎packages/cli/src/commands/plugin/build.ts‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,12 +137,50 @@ function nativePackageReason(dir: string): string | undefined {
137137
return shipped ? `ships a compiled addon (${shipped})` : undefined;
138138
}
139139

140+
/**
141+
* Who reaches the package at `dir` (a {@link packageRootOf} directory): the
142+
* files outside it that import a file inside it, and the shortest chain from
143+
* the plugin's own source to it, one step per package — so a transitive hit
144+
* (`ws` → `bufferutil`) names the direct dependency that pulled it in.
145+
*/
146+
function packageImporters(metafile: Metafile, dir: string): { importers: string[]; chain: string[] } {
147+
const inputs = Object.keys(metafile.inputs);
148+
const inside = (input: string): boolean => packageRootOf(input)?.dir === dir;
149+
const importers = inputs.filter(
150+
(i) => !inside(i) && metafile.inputs[i]!.imports.some((imp) => inside(imp.path)),
151+
);
152+
// Breadth-first from the plugin's own files (outside every `node_modules`).
153+
const from = new Map<string, string | null>();
154+
const queue = inputs.filter((i) => packageRootOf(i) === undefined);
155+
for (const start of queue) from.set(start, null);
156+
let hit: string | undefined;
157+
while (queue.length > 0 && hit === undefined) {
158+
const input = queue.shift()!;
159+
for (const imp of metafile.inputs[input]?.imports ?? []) {
160+
if (from.has(imp.path) || !(imp.path in metafile.inputs)) continue;
161+
from.set(imp.path, input);
162+
if (inside(imp.path)) {
163+
hit = imp.path;
164+
break;
165+
}
166+
queue.push(imp.path);
167+
}
168+
}
169+
const chain: string[] = [];
170+
for (let at: string | undefined = hit; at; at = from.get(at) ?? undefined) {
171+
const step = packageRootOf(at)?.name ?? at;
172+
if (chain[0] !== step) chain.unshift(step);
173+
}
174+
return { importers, chain };
175+
}
176+
140177
/**
141178
* Every native addon a build would pack or load (ADR-0025 v2 §3.3), one line
142179
* each: a `.node` module the bundle reaches (named with its importers), a
143180
* bundled package that builds or ships one (its JS may be bundleable, but the
144181
* binary it locates at run time — `bindings`, `node-gyp-build` — is not in the
145-
* artifact), and a `.node` file staged from `assets/`.
182+
* artifact; named with its importers and the chain that reaches it from the
183+
* plugin's own source), and a `.node` file staged from `assets/`.
146184
*/
147185
function findNativeAddons(metafile: Metafile, cwd: string, assets: ArchiveFile[]): string[] {
148186
const found: string[] = [];
@@ -158,7 +196,13 @@ function findNativeAddons(metafile: Metafile, cwd: string, assets: ArchiveFile[]
158196
}
159197
for (const { name, dir } of packages.values()) {
160198
const reason = nativePackageReason(resolvePath(cwd, dir));
161-
if (reason) found.push(`package \`${name}\` (${dir}) ${reason}`);
199+
if (!reason) continue;
200+
const { importers, chain } = packageImporters(metafile, dir);
201+
found.push(
202+
`package \`${name}\` (${dir}) ${reason}`
203+
+ (importers.length > 0 ? `, imported by ${importers.join(', ')}` : '')
204+
+ (chain.length > 1 ? ` (reached through ${chain.join(' → ')})` : ''),
205+
);
162206
}
163207
for (const asset of assets) {
164208
if (isNativeAddonPath(asset.path)) found.push(asset.path);

‎packages/cli/src/commands/plugin/install.integration.test.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,15 +109,17 @@ const KEY_ID = 'acme-2026';
109109
const text = (t: string) => new TextEncoder().encode(t);
110110

111111
/** A `.osplugin` built as `os plugin build` builds one, its integrity map computed unless given. */
112-
function artifact(name: string, opts: { id: string; version?: string; runtime?: string; files?: ArchiveFile[]; integrity?: Record<string, string>; dir?: string }): string {
112+
function artifact(name: string, opts: { id: string; version?: string; runtime?: string; files?: ArchiveFile[]; integrity?: Record<string, string>; dir?: string; manifest?: Record<string, unknown> }): string {
113113
const files: ArchiveFile[] = opts.files ?? [{ path: 'dist/index.mjs', data: text(`export const id = ${JSON.stringify(opts.id)};\n`) }];
114114
const manifest = {
115115
id: opts.id,
116116
version: opts.version ?? '1.0.0',
117+
name: 'Acme',
117118
type: 'plugin',
118119
runtime: opts.runtime ?? 'node',
119120
packaging: 'bundled',
120121
integrity: opts.integrity ?? computeIntegrity(files),
122+
...opts.manifest,
121123
};
122124
const path = join(opts.dir ?? project, `${name}.osplugin`);
123125
writeFileSync(path, createTarGz([...files, { path: MANIFEST_FILENAME, data: text(JSON.stringify(manifest)) }]));
@@ -330,6 +332,31 @@ describe('os plugin install (ADR-0025 §3.5 M1)', () => {
330332
expect(existsSync(join(home, 'plugins', 'env_local', 'escape.txt'))).toBe(false);
331333
}, CASE_TIMEOUT_MS);
332334

335+
it("refuses a pre-retirement artifact (packaging: 'manifest-deps') with the schema's prescription, before unpacking anything", async () => {
336+
const path = artifact('retired', { id: 'com.acme.retired', manifest: { packaging: 'manifest-deps' } });
337+
sign(path);
338+
await trustPublisher();
339+
const result = await run(PluginInstall, [path, ...db(), '--json']);
340+
expectRefused(result, 'manifest_invalid', 'com.acme.retired');
341+
// The schema's own words reach the operator: the retired value and its remedy.
342+
const details = (result.payload.details as string[]).join('\n');
343+
expect(details).toMatch(/^packaging: `packaging: 'manifest-deps'` was removed/m);
344+
expect(details).toMatch(/Delete the key/);
345+
// Nothing of it was written under the plugin home.
346+
expect(existsSync(join(home, 'plugins', 'env_local', 'com.acme.retired'))).toBe(false);
347+
}, CASE_TIMEOUT_MS);
348+
349+
it('refuses a compiled manifest ManifestSchema refuses, by name, naming each issue', async () => {
350+
const path = artifact('drifted', { id: 'com.acme.drifted', manifest: { name: undefined, integrity: ['not', 'a', 'map'] } });
351+
sign(path);
352+
await trustPublisher();
353+
const result = await run(PluginInstall, [path, ...db(), '--json']);
354+
expectRefused(result, 'manifest_invalid', 'com.acme.drifted');
355+
const details = (result.payload.details as string[]).join('\n');
356+
expect(details).toMatch(/^name: /m);
357+
expect(details).toMatch(/^integrity: /m);
358+
}, CASE_TIMEOUT_MS);
359+
333360
it('refuses an unsigned artifact, and installs it only under --trust-unsigned, saying so on stderr', async () => {
334361
const path = artifact('unsigned', { id: 'com.acme.unsigned' });
335362
expectRefused(await run(PluginInstall, [path, ...db(), '--json']), 'signature_missing', 'com.acme.unsigned');

‎packages/cli/src/commands/plugin/install.ts‎

Lines changed: 29 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@
1717
* signature that does not match the bytes.
1818
* 2. Read the archive (the inflate bounded, `MAX_UNPACKED_ARTIFACT_BYTES`)
1919
* and its compiled `objectstack.plugin.json`; refuse an entry that could
20-
* land outside the install directory.
20+
* land outside the install directory, and a manifest `ManifestSchema`
21+
* refuses (`readCompiledPluginManifest`, the read the boot-time loader
22+
* makes too), with the schema's own message: an artifact built before a
23+
* value was retired (`packaging: 'manifest-deps'`) gets that value's
24+
* prescription here, before anything is unpacked.
2125
* 3. Re-verify every file against the manifest's `integrity` map; refuse a
2226
* digest mismatch, a declared file that is missing, or a file the map
2327
* does not declare.
@@ -64,6 +68,7 @@ import {
6468
loadPluginInstallations,
6569
pluginInstallDir,
6670
dispatchPluginRuntime,
71+
readCompiledPluginManifest,
6772
recordPluginInstallation,
6873
withPluginInstallationsLock,
6974
PluginInstallationsLockedError,
@@ -291,23 +296,26 @@ export default class PluginInstall extends Command {
291296
});
292297
return;
293298
}
294-
let manifest: Record<string, any>;
295-
try {
296-
const entry = files.find((f) => f.path === MANIFEST_FILENAME);
297-
if (!entry) throw new Error(`${MANIFEST_FILENAME} not found in the artifact`);
298-
const parsed = JSON.parse(Buffer.from(entry.data).toString('utf8')) as unknown;
299-
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error(`${MANIFEST_FILENAME} is not a JSON object`);
300-
manifest = parsed as Record<string, any>;
301-
} catch (error) {
302-
await refuse({ error: 'manifest_unreadable', message: `Cannot read the artifact's manifest: ${(error as Error).message}` });
303-
return;
304-
}
305-
const id = typeof manifest.id === 'string' ? manifest.id.trim() : '';
306-
const version = typeof manifest.version === 'string' ? manifest.version.trim() : '';
307-
if (!id || !version) {
308-
await refuse({ error: 'manifest_incomplete', message: 'The artifact manifest is missing `id` or `version`. Rebuild it with `os plugin build`.' });
299+
// Through `ManifestSchema`, the read the boot-time loader makes too: an
300+
// artifact built before a schema change is refused here with the
301+
// schema's own words (a retired value's prescription), not at boot.
302+
const read = readCompiledPluginManifest(files);
303+
if (!read.ok) {
304+
await refuse(
305+
read.reason === 'unreadable'
306+
? { error: 'manifest_unreadable', message: `Cannot read the artifact's manifest: ${read.message}` }
307+
: {
308+
error: 'manifest_invalid',
309+
message:
310+
`The artifact's ${MANIFEST_FILENAME} is not a valid plugin manifest, so nothing was installed. `
311+
+ 'Fix the source manifest and rebuild the artifact with `os plugin build`:',
312+
details: read.issues,
313+
},
314+
);
309315
return;
310316
}
317+
const manifest = read.manifest;
318+
const { id, version } = manifest;
311319
const environmentId = pluginEnvironmentId();
312320
let installDir: string;
313321
try {
@@ -324,19 +332,9 @@ export default class PluginInstall extends Command {
324332
);
325333
}
326334

327-
// 3. Per-file integrity, re-verified at unpack (ADR-0025 §3.2). ─────
328-
const declaredIntegrity = manifest.integrity;
329-
if (
330-
declaredIntegrity !== undefined && declaredIntegrity !== null
331-
&& (typeof declaredIntegrity !== 'object' || Array.isArray(declaredIntegrity))
332-
) {
333-
await refuse({
334-
error: 'integrity_malformed',
335-
message: 'The artifact manifest has a malformed `integrity` map (expected an object of path → digest). Rebuild it with `os plugin build`.',
336-
});
337-
return;
338-
}
339-
const integrity = verifyIntegrity(files, declaredIntegrity as Record<string, string> | undefined, {
335+
// 3. Per-file integrity, re-verified at unpack (ADR-0025 §3.2); the
336+
// map's shape is `ManifestSchema`'s, checked above. ──────────────
337+
const integrity = verifyIntegrity(files, manifest.integrity, {
340338
exempt: [MANIFEST_FILENAME, SIGNATURE_FILENAME],
341339
});
342340
if (!integrity.ok) {
@@ -394,9 +392,9 @@ export default class PluginInstall extends Command {
394392
id,
395393
version,
396394
versionId: `${id}@${version}`,
397-
runtime: typeof manifest.runtime === 'string' ? manifest.runtime : null,
395+
runtime: manifest.runtime ?? null,
398396
status: 'installed',
399-
grantedPermissions: permissions && typeof permissions === 'object' && !Array.isArray(permissions) ? permissions : null,
397+
grantedPermissions: permissions ?? null,
400398
dir: installDir,
401399
artifact: { file: INSTALLED_ARTIFACT_FILE, sha256: artifactSha },
402400
signatureFile: signature === null ? null : INSTALLED_SIGNATURE_FILE,

‎packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,7 @@ function writePluginFixture(): void {
553553
const manifest = {
554554
id: 'com.example.osf-plugin',
555555
version: '1.0.0',
556+
name: 'One-shot fixture',
556557
type: 'plugin',
557558
runtime: 'node',
558559
packaging: 'bundled',

‎packages/cli/test/json-stdout-purity.e2e.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ const PREPARE: Record<string, (dir: string, env: Record<string, string>) => Prom
197197
const manifest = {
198198
id: 'com.purity.e2e',
199199
version: '1.0.0',
200+
name: 'Purity',
200201
type: 'plugin',
201202
runtime: 'node',
202203
packaging: 'bundled',

‎packages/cli/test/plugin-build-bundled-only.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,31 @@ describe('os plugin build — a native addon is refused (ADR-0025 v2 §3.3)', ()
186186
});
187187
}
188188

189+
it('names the importer chain of a transitive native package, so it traces to the direct dependency', async () => {
190+
const dir = await project({}, {
191+
'node_modules/fake-native/package.json': JSON.stringify({ name: 'fake-native', version: '1.0.0', main: 'index.js' }),
192+
'node_modules/fake-native/binding.gyp': `{ 'targets': [] }\n`,
193+
'node_modules/fake-native/index.js': `module.exports = require('./build/Release/fake.js');\n`,
194+
'node_modules/fake-native/build/Release/fake.js': `module.exports = 'NATIVE';\n`,
195+
'node_modules/ws-like/package.json': JSON.stringify({ name: 'ws-like', version: '1.0.0', main: 'index.js' }),
196+
'node_modules/ws-like/index.js': `module.exports = require('./lib/buffer-util.js');\n`,
197+
'node_modules/ws-like/lib/buffer-util.js': `module.exports = require('fake-native');\n`,
198+
'src/index.ts': `import ws from 'ws-like';\nexport const value = ws;\n`,
199+
});
200+
201+
const { exit, printed } = await build(dir);
202+
203+
expect(exit).toBe(1);
204+
expect(refusals(printed)).toMatch(/native addon/i);
205+
expect(printed).toContain('package `fake-native` (node_modules/fake-native) declares a node-gyp build (binding.gyp)');
206+
// The file that imports it, and the chain from the plugin's own source.
207+
expect(printed).toContain('imported by node_modules/ws-like/lib/buffer-util.js');
208+
expect(printed).toContain('reached through src/index.ts → ws-like → fake-native');
209+
// `ws-like` is pure JavaScript: named on the chain, never as a native package.
210+
expect(printed).not.toContain('package `ws-like`');
211+
expect(existsSync(join(dir, ARTIFACT))).toBe(false);
212+
});
213+
189214
it('refuses a `.node` file under `assets/`, naming it', async () => {
190215
const dir = await project({}, {
191216
'assets/icon.svg': '<svg/>',

0 commit comments

Comments
 (0)