Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/packages-read-door-writable-verdict.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
---
"@objectstack/runtime": patch
"@objectstack/metadata-protocol": patch
---

feat(packages): `GET /packages` and `GET /packages/:id` rows carry the server's own `writable` verdict (#14375)

ADR-0130 Consequences row 6, server half. Every package row served by the two
read doors now carries `writable: boolean`, computed by the SAME predicate the
authoring and lifecycle gates already enforce — `isWritablePackage` (ADR-0070
D2) — so a client no longer has to guess it.

- **Why.** Studio's package switcher derived "writable" client-side from
`manifest.scope` alone (`scope !== 'project'`). That is not the server's
rule: `isWritablePackage` reads `engine.manifests` FIRST, so a package booted
from an artifact through `registerApp` is read-only whatever its scope says —
and a scope-less `type: module` carried by a multi-package artifact lands
there too. A scope-less Studio-created database base is writable. The client
cannot see `engine.manifests`, so it cannot tell those two apart; the server
can, and now says so (#8146: one answer to "is this package writable?").
- **Where.** The runtime dispatcher door (`handlePackagesRequest`, list and
detail) decorates its read of the registry records; the metadata protocol's
`getMetaItems({ type: 'package' })` — the producer the REST `GET /packages`
door spreads its registry half from — decorates the same records the same
way. Both are spread COPIES: the registry's own records are never mutated and
the verdict is never stored.
- **Additive.** No existing key changes; no accept/reject surface moves. A REST
row that has no registry presence (durable-only) carries no verdict, and the
REST detail door's database-first row does not either — the registry item is
the only carrier, by design.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,7 +160,7 @@ The largest single consumer — **20 of the 109 sites**.
| 49 | Action `requiredPermissions` bypassed | runtime | Get: engine self-invocation runs any action | `action-execution.ts:399` |
| 50 | `manage_metadata` bypassed on metadata writes | runtime, rest | Get: schema writes without the capability | `domains/meta.ts:471`, `:874`, `rest-server.ts:4629`, `:5992`, `:6240`, `:6671`, `:6864` |
| 51 | The shared metadata-write verdict itself returns `allowed` | metadata-core | Get: the one function all of row 50's doors consult answers yes before any capability is examined | `meta-write-capability.ts:134` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:246`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:276`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `domains/mcp.ts:61` |
| 54 | Package REST route capability gate bypassed | rest | Get: package read/write over REST without `manage_metadata` / `studio.access` / `setup.access` | `package-routes.ts:102` |
| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `domains/packages.ts:95`, `:128` |
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `getMetaItems({ type: 'package' })` stamps the server's OWN writability
* verdict on every package item (#14375, ADR-0130 Consequences row 6 — the
* producer the REST `GET /packages` door spreads its registry half from).
*
* The verdict is `isWritablePackage` (ADR-0070 D2), the same predicate the
* authoring (`saveMetaItem`) and lifecycle (`DELETE` / `disable`) gates already
* enforce — #8146's "one answer to 'is this package writable?'" applied to the
* read side. It reads `engine.manifests` FIRST: a package booted from an
* artifact through `registerApp` is read-only whatever its scope says, and a
* scope-less `type: module` carried by a multi-package artifact lands there
* too, while a scope-less Studio-created base does not. Only the server holds
* `engine.manifests`, which is why the client could never derive this.
*
* The engine is the same shape `meta-overlay-cache.test.ts` drives: the
* registry surface this method touches, a `find` that answers the overlay
* query with nothing, and — the subject here — a `manifests` map.
*/

import { describe, it, expect } from 'vitest';
import { ObjectStackProtocolImplementation } from './protocol.js';

/** Booted code package, explicit `scope: 'project'`. */
const CODE_PROJECT = 'app.acme.crm';
/** Booted, SCOPE-LESS module — the multi-package-artifact sub-package. */
const CODE_MODULE = 'app.acme.crm.billing';
/** Platform / marketplace delivered. */
const SYSTEM_SCOPED = 'com.objectstack.platform';
const CLOUD_SCOPED = 'com.objectstack.cloudpack';
/** Studio-created database base: installed, never booted, scope-less. */
const DB_BASE = 'com.acme.mybase';

type Row = { manifest: Record<string, unknown>; status: string; enabled: boolean };

function row(id: string, extra: Record<string, unknown> = {}): Row {
return { manifest: { id, name: id, version: '1.0.0', ...extra }, status: 'installed', enabled: true };
}

function make() {
const records: Row[] = [
row(CODE_PROJECT, { scope: 'project', type: 'app' }),
row(CODE_MODULE, { type: 'module' }),
row(SYSTEM_SCOPED, { scope: 'system' }),
row(CLOUD_SCOPED, { scope: 'cloud' }),
row(DB_BASE),
];
const byId = new Map(records.map((r) => [r.manifest.id as string, r]));
// What `ObjectQL.registerApp` records for every package of a loaded artifact.
const manifests = new Map<string, unknown>([
[CODE_PROJECT, byId.get(CODE_PROJECT)!.manifest],
[CODE_MODULE, byId.get(CODE_MODULE)!.manifest],
]);
const engine: any = {
manifests,
find: async () => [],
registry: {
listItems: (type: string) => (type === 'package' ? records : []),
getPackage: (id: string) => byId.get(id),
getItem: () => undefined,
getObject: () => undefined,
getArtifactItem: () => undefined,
isPackageDisabled: () => false,
applyNavContributions: (app: unknown) => app,
},
};
const protocol = new ObjectStackProtocolImplementation(engine, () => new Map());
return { protocol, records };
}

async function listPackages(protocol: ObjectStackProtocolImplementation) {
const res = await protocol.getMetaItems({ type: 'package' });
return res.items as Array<Row & { writable?: boolean }>;
}

const pick = (items: Array<Row & { writable?: boolean }>, id: string) => {
const it = items.find((p) => p.manifest.id === id);
if (!it) throw new Error(`item ${id} missing`);
return it;
};

describe('getMetaItems({ type: "package" }) carries the writable verdict (#14375)', () => {
it('pin 1: a booted code package with scope "project" is writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_PROJECT).writable).toBe(false);
});

it('pin 2: a booted, SCOPE-LESS module is writable: false — the row itself carries no scope', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, CODE_MODULE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(false);
});

it('pin 3: system- and cloud-scoped packages are writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, SYSTEM_SCOPED).writable).toBe(false);
expect(pick(items, CLOUD_SCOPED).writable).toBe(false);
});

it('pin 4: a SCOPE-LESS database base (never booted) is writable: true', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, DB_BASE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(true);
});

it('pins 2 + 4: the two scope-less rows differ ONLY in the verdict — the scope cannot tell them apart', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_MODULE).manifest.scope).toBe(pick(items, DB_BASE).manifest.scope);
expect(pick(items, CODE_MODULE).writable).toBe(false);
expect(pick(items, DB_BASE).writable).toBe(true);
});

it('pin 5: additive and computed — the served row minus `writable` equals the registry record, which is never mutated', async () => {
const { protocol, records } = make();
const items = await listPackages(protocol);
expect(items).toHaveLength(records.length);
for (const record of records) {
const { writable, ...rest } = pick(items, record.manifest.id as string);
expect(typeof writable).toBe('boolean');
expect(rest).toEqual(record);
expect('writable' in record).toBe(false);
}
});

it('does not leak onto other types: an `app` listing gains no `writable` key', async () => {
const { protocol } = make();
const res = await protocol.getMetaItems({ type: 'app' });
for (const it_ of res.items as Array<Record<string, unknown>>) {
expect('writable' in it_).toBe(false);
}
});
});
22 changes: 22 additions & 0 deletions packages/metadata-protocol/src/protocol.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7198,6 +7198,28 @@ export class ObjectStackProtocolImplementation implements
items = (items as any[]).map((app) => this.engine.registry.applyNavContributions(app));
}

// [#14375 / ADR-0130 Consequences row 6] A package row carries the
// server's OWN writability verdict. The REST `GET /packages` door is
// this producer with the durable rows spread over it, and Studio's
// package switcher reads that list; it used to derive "writable"
// client-side from `manifest.scope` alone, which is not this server's
// rule — ADR-0070 D2 (`isWritablePackage`) reads `engine.manifests`
// FIRST, so a scope-less module booted from a multi-package artifact is
// read-only while a scope-less Studio-created base is writable, and only
// the server can tell the two apart. Same predicate the authoring and
// lifecycle gates use (#8146: one answer), computed on a spread COPY:
// the registry record is never mutated and the verdict is never stored.
// The runtime dispatcher door decorates its own read of the same
// records the same way (`withWritableVerdict` in
// `packages/runtime/src/domains/packages.ts`).
if (request.type === 'package' || request.type === 'packages') {
items = (items as any[]).map((pkg) => {
const manifestId = pkg?.manifest?.id;
const id = typeof manifestId === 'string' ? manifestId : (typeof pkg?.id === 'string' ? pkg.id : undefined);
return { ...pkg, writable: this.isWritablePackage(id) };
});
}

return {
type: request.type,
items: decorateMetadataItems(
Expand Down
115 changes: 115 additions & 0 deletions packages/rest/src/package-list-writable-carry.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* REST `GET /packages` CARRIES the producer's `writable` verdict (#14375).
*
* The REST list door does not compute writability itself — it must not: this
* package has no runtime dependency on `@objectstack/metadata-protocol`, and
* the verdict has one definition (`isWritablePackage`, ADR-0070 D2) that the
* protocol's `getMetaItems({ type: 'package' })` now stamps on every registry
* item. What THIS door owns is the merge: the durable (`PackageService.list()`)
* row is spread OVER the registry item, so a durable row that carries no
* `writable` key must leave the registry item's verdict standing, and a
* durable-only row (no registry presence) carries no verdict at all. Both are
* pinned here, because the spread order is the one place this file could lose
* the field.
*/

import { describe, it, expect } from 'vitest';
import type { RouteHandler } from '@objectstack/spec/contracts';
import { registerPackageRoutes } from './package-routes.js';

type Captured = { status: number; body: any };

function mount(svc: any, protocol: any) {
const routes = new Map<string, RouteHandler>();
const server = {
get: (p: string, h: RouteHandler) => { routes.set(`GET:${p}`, h); },
post: (p: string, h: RouteHandler) => { routes.set(`POST:${p}`, h); },
put: () => {},
delete: (p: string, h: RouteHandler) => { routes.set(`DELETE:${p}`, h); },
patch: () => {},
use: () => {},
listen: async () => {},
close: async () => {},
} as any;
// The authorization gate (#7033 / #7023) is not this file's subject.
registerPackageRoutes(server, () => svc, '/api/v1', {
resolveExecutionContext: async () => ({
userId: 'u_pkg', systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'],
}),
protocol,
});
return routes;
}

async function drive(routes: Map<string, RouteHandler>, method: string, path: string, req: Record<string, any> = {}): Promise<Captured> {
const handler = routes.get(`${method}:${path}`);
if (!handler) throw new Error(`no handler for ${method} ${path}`);
const captured: Captured = { status: 200, body: undefined };
const res: any = {
json(data: any) { captured.body = data; },
send() {},
status(code: number) { captured.status = code; return res; },
header() { return res; },
};
await handler({ params: {}, query: {}, body: undefined, headers: {}, method, path, ...req } as any, res);
return captured;
}

/** The scope-less booted module — the producer says read-only. */
const MODULE = 'app.acme.crm.billing';
/** A scope-less Studio base — the producer says writable; it also has a durable row. */
const BASE = 'com.acme.mybase';
/** A durable-only row: published, never registered on this process. */
const DURABLE_ONLY = 'com.acme.published-elsewhere';

const registryItems = [
{ manifest: { id: MODULE, name: MODULE, version: '1.0.0', type: 'module' }, status: 'installed', enabled: true, writable: false },
{ manifest: { id: BASE, name: BASE, version: '1.0.0' }, status: 'installed', enabled: true, writable: true },
];
const protocol = { getMetaItems: async () => ({ type: 'package', items: registryItems }) };
const svc = {
list: async () => [
// The durable row for BASE has NO `writable` key — a durable copy is not
// where the verdict lives.
{ id: BASE, version: '1.0.0', manifest: { id: BASE, name: BASE, version: '1.0.0' } },
{ id: DURABLE_ONLY, version: '3.0.0', manifest: { id: DURABLE_ONLY, version: '3.0.0' } },
],
};

const rowOf = (body: any, id: string) => body.data.packages.find((p: any) => (p.manifest?.id ?? p.id) === id);

describe('REST GET /packages carries the producer\'s writable verdict through the merge (#14375)', () => {
it('a registry-only row keeps the producer\'s verdict', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.status).toBe(200);
const row = rowOf(r.body, MODULE);
expect(row.source).toBe('registry');
expect(row.writable).toBe(false);
});

it('a durable row spread over a registry item does NOT erase the verdict (spread order)', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, BASE);
expect(row.source).toBe('both');
// The durable row carried no `writable`; the registry item's stands.
expect(row.writable).toBe(true);
});

it('a durable-only row carries no verdict — the registry item is the only carrier', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, DURABLE_ONLY);
expect(row.source).toBe('database');
expect('writable' in row).toBe(false);
});

it('is additive: nothing else about the merged rows changed', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.body.data.total).toBe(3);
const { writable, ...rest } = rowOf(r.body, MODULE);
expect(writable).toBe(false);
const { writable: _producerVerdict, ...producerItem } = registryItems[0];
expect(rest).toEqual({ ...producerItem, source: 'registry' });
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/packages-read-door-writable-verdict.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
---
"@objectstack/runtime": patch
"@objectstack/metadata-protocol": patch
---

feat(packages): `GET /packages` and `GET /packages/:id` rows carry the server's own `writable` verdict (#14375)

ADR-0130 Consequences row 6, server half. Every package row served by the two
read doors now carries `writable: boolean`, computed by the SAME predicate the
authoring and lifecycle gates already enforce — `isWritablePackage` (ADR-0070
D2) — so a client no longer has to guess it.

- **Why.** Studio's package switcher derived "writable" client-side from
`manifest.scope` alone (`scope !== 'project'`). That is not the server's
rule: `isWritablePackage` reads `engine.manifests` FIRST, so a package booted
from an artifact through `registerApp` is read-only whatever its scope says —
and a scope-less `type: module` carried by a multi-package artifact lands
there too. A scope-less Studio-created database base is writable. The client
cannot see `engine.manifests`, so it cannot tell those two apart; the server
can, and now says so (#8146: one answer to "is this package writable?").
- **Where.** The runtime dispatcher door (`handlePackagesRequest`, list and
detail) decorates its read of the registry records; the metadata protocol's
`getMetaItems({ type: 'package' })` — the producer the REST `GET /packages`
door spreads its registry half from — decorates the same records the same
way. Both are spread COPIES: the registry's own records are never mutated and
the verdict is never stored.
- **Additive.** No existing key changes; no accept/reject surface moves. A REST
row that has no registry presence (durable-only) carries no verdict, and the
REST detail door's database-first row does not either — the registry item is
the only carrier, by design.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,7 +160,7 @@ The largest single consumer — **20 of the 109 sites**.
| 49 | Action `requiredPermissions` bypassed | runtime | Get: engine self-invocation runs any action | `action-execution.ts:399` |
| 50 | `manage_metadata` bypassed on metadata writes | runtime, rest | Get: schema writes without the capability | `domains/meta.ts:471`, `:874`, `rest-server.ts:4629`, `:5992`, `:6240`, `:6671`, `:6864` |
| 51 | The shared metadata-write verdict itself returns `allowed` | metadata-core | Get: the one function all of row 50's doors consult answers yes before any capability is examined | `meta-write-capability.ts:134` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:246`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:276`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `domains/mcp.ts:61` |
| 54 | Package REST route capability gate bypassed | rest | Get: package read/write over REST without `manage_metadata` / `studio.access` / `setup.access` | `package-routes.ts:102` |
| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `domains/packages.ts:95`, `:128` |
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `getMetaItems({ type: 'package' })` stamps the server's OWN writability
* verdict on every package item (#14375, ADR-0130 Consequences row 6 — the
* producer the REST `GET /packages` door spreads its registry half from).
*
* The verdict is `isWritablePackage` (ADR-0070 D2), the same predicate the
* authoring (`saveMetaItem`) and lifecycle (`DELETE` / `disable`) gates already
* enforce — #8146's "one answer to 'is this package writable?'" applied to the
* read side. It reads `engine.manifests` FIRST: a package booted from an
* artifact through `registerApp` is read-only whatever its scope says, and a
* scope-less `type: module` carried by a multi-package artifact lands there
* too, while a scope-less Studio-created base does not. Only the server holds
* `engine.manifests`, which is why the client could never derive this.
*
* The engine is the same shape `meta-overlay-cache.test.ts` drives: the
* registry surface this method touches, a `find` that answers the overlay
* query with nothing, and — the subject here — a `manifests` map.
*/

import { describe, it, expect } from 'vitest';
import { ObjectStackProtocolImplementation } from './protocol.js';

/** Booted code package, explicit `scope: 'project'`. */
const CODE_PROJECT = 'app.acme.crm';
/** Booted, SCOPE-LESS module — the multi-package-artifact sub-package. */
const CODE_MODULE = 'app.acme.crm.billing';
/** Platform / marketplace delivered. */
const SYSTEM_SCOPED = 'com.objectstack.platform';
const CLOUD_SCOPED = 'com.objectstack.cloudpack';
/** Studio-created database base: installed, never booted, scope-less. */
const DB_BASE = 'com.acme.mybase';

type Row = { manifest: Record<string, unknown>; status: string; enabled: boolean };

function row(id: string, extra: Record<string, unknown> = {}): Row {
return { manifest: { id, name: id, version: '1.0.0', ...extra }, status: 'installed', enabled: true };
}

function make() {
const records: Row[] = [
row(CODE_PROJECT, { scope: 'project', type: 'app' }),
row(CODE_MODULE, { type: 'module' }),
row(SYSTEM_SCOPED, { scope: 'system' }),
row(CLOUD_SCOPED, { scope: 'cloud' }),
row(DB_BASE),
];
const byId = new Map(records.map((r) => [r.manifest.id as string, r]));
// What `ObjectQL.registerApp` records for every package of a loaded artifact.
const manifests = new Map<string, unknown>([
[CODE_PROJECT, byId.get(CODE_PROJECT)!.manifest],
[CODE_MODULE, byId.get(CODE_MODULE)!.manifest],
]);
const engine: any = {
manifests,
find: async () => [],
registry: {
listItems: (type: string) => (type === 'package' ? records : []),
getPackage: (id: string) => byId.get(id),
getItem: () => undefined,
getObject: () => undefined,
getArtifactItem: () => undefined,
isPackageDisabled: () => false,
applyNavContributions: (app: unknown) => app,
},
};
const protocol = new ObjectStackProtocolImplementation(engine, () => new Map());
return { protocol, records };
}

async function listPackages(protocol: ObjectStackProtocolImplementation) {
const res = await protocol.getMetaItems({ type: 'package' });
return res.items as Array<Row & { writable?: boolean }>;
}

const pick = (items: Array<Row & { writable?: boolean }>, id: string) => {
const it = items.find((p) => p.manifest.id === id);
if (!it) throw new Error(`item ${id} missing`);
return it;
};

describe('getMetaItems({ type: "package" }) carries the writable verdict (#14375)', () => {
it('pin 1: a booted code package with scope "project" is writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_PROJECT).writable).toBe(false);
});

it('pin 2: a booted, SCOPE-LESS module is writable: false — the row itself carries no scope', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, CODE_MODULE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(false);
});

it('pin 3: system- and cloud-scoped packages are writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, SYSTEM_SCOPED).writable).toBe(false);
expect(pick(items, CLOUD_SCOPED).writable).toBe(false);
});

it('pin 4: a SCOPE-LESS database base (never booted) is writable: true', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, DB_BASE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(true);
});

it('pins 2 + 4: the two scope-less rows differ ONLY in the verdict — the scope cannot tell them apart', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_MODULE).manifest.scope).toBe(pick(items, DB_BASE).manifest.scope);
expect(pick(items, CODE_MODULE).writable).toBe(false);
expect(pick(items, DB_BASE).writable).toBe(true);
});

it('pin 5: additive and computed — the served row minus `writable` equals the registry record, which is never mutated', async () => {
const { protocol, records } = make();
const items = await listPackages(protocol);
expect(items).toHaveLength(records.length);
for (const record of records) {
const { writable, ...rest } = pick(items, record.manifest.id as string);
expect(typeof writable).toBe('boolean');
expect(rest).toEqual(record);
expect('writable' in record).toBe(false);
}
});

it('does not leak onto other types: an `app` listing gains no `writable` key', async () => {
const { protocol } = make();
const res = await protocol.getMetaItems({ type: 'app' });
for (const it_ of res.items as Array<Record<string, unknown>>) {
expect('writable' in it_).toBe(false);
}
});
});
22 changes: 22 additions & 0 deletions packages/metadata-protocol/src/protocol.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7198,6 +7198,28 @@ export class ObjectStackProtocolImplementation implements
items = (items as any[]).map((app) => this.engine.registry.applyNavContributions(app));
}

// [#14375 / ADR-0130 Consequences row 6] A package row carries the
// server's OWN writability verdict. The REST `GET /packages` door is
// this producer with the durable rows spread over it, and Studio's
// package switcher reads that list; it used to derive "writable"
// client-side from `manifest.scope` alone, which is not this server's
// rule — ADR-0070 D2 (`isWritablePackage`) reads `engine.manifests`
// FIRST, so a scope-less module booted from a multi-package artifact is
// read-only while a scope-less Studio-created base is writable, and only
// the server can tell the two apart. Same predicate the authoring and
// lifecycle gates use (#8146: one answer), computed on a spread COPY:
// the registry record is never mutated and the verdict is never stored.
// The runtime dispatcher door decorates its own read of the same
// records the same way (`withWritableVerdict` in
// `packages/runtime/src/domains/packages.ts`).
if (request.type === 'package' || request.type === 'packages') {
items = (items as any[]).map((pkg) => {
const manifestId = pkg?.manifest?.id;
const id = typeof manifestId === 'string' ? manifestId : (typeof pkg?.id === 'string' ? pkg.id : undefined);
return { ...pkg, writable: this.isWritablePackage(id) };
});
}

return {
type: request.type,
items: decorateMetadataItems(
Expand Down
115 changes: 115 additions & 0 deletions packages/rest/src/package-list-writable-carry.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* REST `GET /packages` CARRIES the producer's `writable` verdict (#14375).
*
* The REST list door does not compute writability itself — it must not: this
* package has no runtime dependency on `@objectstack/metadata-protocol`, and
* the verdict has one definition (`isWritablePackage`, ADR-0070 D2) that the
* protocol's `getMetaItems({ type: 'package' })` now stamps on every registry
* item. What THIS door owns is the merge: the durable (`PackageService.list()`)
* row is spread OVER the registry item, so a durable row that carries no
* `writable` key must leave the registry item's verdict standing, and a
* durable-only row (no registry presence) carries no verdict at all. Both are
* pinned here, because the spread order is the one place this file could lose
* the field.
*/

import { describe, it, expect } from 'vitest';
import type { RouteHandler } from '@objectstack/spec/contracts';
import { registerPackageRoutes } from './package-routes.js';

type Captured = { status: number; body: any };

function mount(svc: any, protocol: any) {
const routes = new Map<string, RouteHandler>();
const server = {
get: (p: string, h: RouteHandler) => { routes.set(`GET:${p}`, h); },
post: (p: string, h: RouteHandler) => { routes.set(`POST:${p}`, h); },
put: () => {},
delete: (p: string, h: RouteHandler) => { routes.set(`DELETE:${p}`, h); },
patch: () => {},
use: () => {},
listen: async () => {},
close: async () => {},
} as any;
// The authorization gate (#7033 / #7023) is not this file's subject.
registerPackageRoutes(server, () => svc, '/api/v1', {
resolveExecutionContext: async () => ({
userId: 'u_pkg', systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'],
}),
protocol,
});
return routes;
}

async function drive(routes: Map<string, RouteHandler>, method: string, path: string, req: Record<string, any> = {}): Promise<Captured> {
const handler = routes.get(`${method}:${path}`);
if (!handler) throw new Error(`no handler for ${method} ${path}`);
const captured: Captured = { status: 200, body: undefined };
const res: any = {
json(data: any) { captured.body = data; },
send() {},
status(code: number) { captured.status = code; return res; },
header() { return res; },
};
await handler({ params: {}, query: {}, body: undefined, headers: {}, method, path, ...req } as any, res);
return captured;
}

/** The scope-less booted module — the producer says read-only. */
const MODULE = 'app.acme.crm.billing';
/** A scope-less Studio base — the producer says writable; it also has a durable row. */
const BASE = 'com.acme.mybase';
/** A durable-only row: published, never registered on this process. */
const DURABLE_ONLY = 'com.acme.published-elsewhere';

const registryItems = [
{ manifest: { id: MODULE, name: MODULE, version: '1.0.0', type: 'module' }, status: 'installed', enabled: true, writable: false },
{ manifest: { id: BASE, name: BASE, version: '1.0.0' }, status: 'installed', enabled: true, writable: true },
];
const protocol = { getMetaItems: async () => ({ type: 'package', items: registryItems }) };
const svc = {
list: async () => [
// The durable row for BASE has NO `writable` key — a durable copy is not
// where the verdict lives.
{ id: BASE, version: '1.0.0', manifest: { id: BASE, name: BASE, version: '1.0.0' } },
{ id: DURABLE_ONLY, version: '3.0.0', manifest: { id: DURABLE_ONLY, version: '3.0.0' } },
],
};

const rowOf = (body: any, id: string) => body.data.packages.find((p: any) => (p.manifest?.id ?? p.id) === id);

describe('REST GET /packages carries the producer\'s writable verdict through the merge (#14375)', () => {
it('a registry-only row keeps the producer\'s verdict', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.status).toBe(200);
const row = rowOf(r.body, MODULE);
expect(row.source).toBe('registry');
expect(row.writable).toBe(false);
});

it('a durable row spread over a registry item does NOT erase the verdict (spread order)', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, BASE);
expect(row.source).toBe('both');
// The durable row carried no `writable`; the registry item's stands.
expect(row.writable).toBe(true);
});

it('a durable-only row carries no verdict — the registry item is the only carrier', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, DURABLE_ONLY);
expect(row.source).toBe('database');
expect('writable' in row).toBe(false);
});

it('is additive: nothing else about the merged rows changed', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.body.data.total).toBe(3);
const { writable, ...rest } = rowOf(r.body, MODULE);
expect(writable).toBe(false);
const { writable: _producerVerdict, ...producerItem } = registryItems[0];
expect(rest).toEqual({ ...producerItem, source: 'registry' });
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/packages-read-door-writable-verdict.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
---
"@objectstack/runtime": patch
"@objectstack/metadata-protocol": patch
---

feat(packages): `GET /packages` and `GET /packages/:id` rows carry the server's own `writable` verdict (#14375)

ADR-0130 Consequences row 6, server half. Every package row served by the two
read doors now carries `writable: boolean`, computed by the SAME predicate the
authoring and lifecycle gates already enforce — `isWritablePackage` (ADR-0070
D2) — so a client no longer has to guess it.

- **Why.** Studio's package switcher derived "writable" client-side from
`manifest.scope` alone (`scope !== 'project'`). That is not the server's
rule: `isWritablePackage` reads `engine.manifests` FIRST, so a package booted
from an artifact through `registerApp` is read-only whatever its scope says —
and a scope-less `type: module` carried by a multi-package artifact lands
there too. A scope-less Studio-created database base is writable. The client
cannot see `engine.manifests`, so it cannot tell those two apart; the server
can, and now says so (#8146: one answer to "is this package writable?").
- **Where.** The runtime dispatcher door (`handlePackagesRequest`, list and
detail) decorates its read of the registry records; the metadata protocol's
`getMetaItems({ type: 'package' })` — the producer the REST `GET /packages`
door spreads its registry half from — decorates the same records the same
way. Both are spread COPIES: the registry's own records are never mutated and
the verdict is never stored.
- **Additive.** No existing key changes; no accept/reject surface moves. A REST
row that has no registry presence (durable-only) carries no verdict, and the
REST detail door's database-first row does not either — the registry item is
the only carrier, by design.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,7 +160,7 @@ The largest single consumer — **20 of the 109 sites**.
| 49 | Action `requiredPermissions` bypassed | runtime | Get: engine self-invocation runs any action | `action-execution.ts:399` |
| 50 | `manage_metadata` bypassed on metadata writes | runtime, rest | Get: schema writes without the capability | `domains/meta.ts:471`, `:874`, `rest-server.ts:4629`, `:5992`, `:6240`, `:6671`, `:6864` |
| 51 | The shared metadata-write verdict itself returns `allowed` | metadata-core | Get: the one function all of row 50's doors consult answers yes before any capability is examined | `meta-write-capability.ts:134` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:246`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:276`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `domains/mcp.ts:61` |
| 54 | Package REST route capability gate bypassed | rest | Get: package read/write over REST without `manage_metadata` / `studio.access` / `setup.access` | `package-routes.ts:102` |
| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `domains/packages.ts:95`, `:128` |
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `getMetaItems({ type: 'package' })` stamps the server's OWN writability
* verdict on every package item (#14375, ADR-0130 Consequences row 6 — the
* producer the REST `GET /packages` door spreads its registry half from).
*
* The verdict is `isWritablePackage` (ADR-0070 D2), the same predicate the
* authoring (`saveMetaItem`) and lifecycle (`DELETE` / `disable`) gates already
* enforce — #8146's "one answer to 'is this package writable?'" applied to the
* read side. It reads `engine.manifests` FIRST: a package booted from an
* artifact through `registerApp` is read-only whatever its scope says, and a
* scope-less `type: module` carried by a multi-package artifact lands there
* too, while a scope-less Studio-created base does not. Only the server holds
* `engine.manifests`, which is why the client could never derive this.
*
* The engine is the same shape `meta-overlay-cache.test.ts` drives: the
* registry surface this method touches, a `find` that answers the overlay
* query with nothing, and — the subject here — a `manifests` map.
*/

import { describe, it, expect } from 'vitest';
import { ObjectStackProtocolImplementation } from './protocol.js';

/** Booted code package, explicit `scope: 'project'`. */
const CODE_PROJECT = 'app.acme.crm';
/** Booted, SCOPE-LESS module — the multi-package-artifact sub-package. */
const CODE_MODULE = 'app.acme.crm.billing';
/** Platform / marketplace delivered. */
const SYSTEM_SCOPED = 'com.objectstack.platform';
const CLOUD_SCOPED = 'com.objectstack.cloudpack';
/** Studio-created database base: installed, never booted, scope-less. */
const DB_BASE = 'com.acme.mybase';

type Row = { manifest: Record<string, unknown>; status: string; enabled: boolean };

function row(id: string, extra: Record<string, unknown> = {}): Row {
return { manifest: { id, name: id, version: '1.0.0', ...extra }, status: 'installed', enabled: true };
}

function make() {
const records: Row[] = [
row(CODE_PROJECT, { scope: 'project', type: 'app' }),
row(CODE_MODULE, { type: 'module' }),
row(SYSTEM_SCOPED, { scope: 'system' }),
row(CLOUD_SCOPED, { scope: 'cloud' }),
row(DB_BASE),
];
const byId = new Map(records.map((r) => [r.manifest.id as string, r]));
// What `ObjectQL.registerApp` records for every package of a loaded artifact.
const manifests = new Map<string, unknown>([
[CODE_PROJECT, byId.get(CODE_PROJECT)!.manifest],
[CODE_MODULE, byId.get(CODE_MODULE)!.manifest],
]);
const engine: any = {
manifests,
find: async () => [],
registry: {
listItems: (type: string) => (type === 'package' ? records : []),
getPackage: (id: string) => byId.get(id),
getItem: () => undefined,
getObject: () => undefined,
getArtifactItem: () => undefined,
isPackageDisabled: () => false,
applyNavContributions: (app: unknown) => app,
},
};
const protocol = new ObjectStackProtocolImplementation(engine, () => new Map());
return { protocol, records };
}

async function listPackages(protocol: ObjectStackProtocolImplementation) {
const res = await protocol.getMetaItems({ type: 'package' });
return res.items as Array<Row & { writable?: boolean }>;
}

const pick = (items: Array<Row & { writable?: boolean }>, id: string) => {
const it = items.find((p) => p.manifest.id === id);
if (!it) throw new Error(`item ${id} missing`);
return it;
};

describe('getMetaItems({ type: "package" }) carries the writable verdict (#14375)', () => {
it('pin 1: a booted code package with scope "project" is writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_PROJECT).writable).toBe(false);
});

it('pin 2: a booted, SCOPE-LESS module is writable: false — the row itself carries no scope', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, CODE_MODULE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(false);
});

it('pin 3: system- and cloud-scoped packages are writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, SYSTEM_SCOPED).writable).toBe(false);
expect(pick(items, CLOUD_SCOPED).writable).toBe(false);
});

it('pin 4: a SCOPE-LESS database base (never booted) is writable: true', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, DB_BASE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(true);
});

it('pins 2 + 4: the two scope-less rows differ ONLY in the verdict — the scope cannot tell them apart', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_MODULE).manifest.scope).toBe(pick(items, DB_BASE).manifest.scope);
expect(pick(items, CODE_MODULE).writable).toBe(false);
expect(pick(items, DB_BASE).writable).toBe(true);
});

it('pin 5: additive and computed — the served row minus `writable` equals the registry record, which is never mutated', async () => {
const { protocol, records } = make();
const items = await listPackages(protocol);
expect(items).toHaveLength(records.length);
for (const record of records) {
const { writable, ...rest } = pick(items, record.manifest.id as string);
expect(typeof writable).toBe('boolean');
expect(rest).toEqual(record);
expect('writable' in record).toBe(false);
}
});

it('does not leak onto other types: an `app` listing gains no `writable` key', async () => {
const { protocol } = make();
const res = await protocol.getMetaItems({ type: 'app' });
for (const it_ of res.items as Array<Record<string, unknown>>) {
expect('writable' in it_).toBe(false);
}
});
});
22 changes: 22 additions & 0 deletions packages/metadata-protocol/src/protocol.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7198,6 +7198,28 @@ export class ObjectStackProtocolImplementation implements
items = (items as any[]).map((app) => this.engine.registry.applyNavContributions(app));
}

// [#14375 / ADR-0130 Consequences row 6] A package row carries the
// server's OWN writability verdict. The REST `GET /packages` door is
// this producer with the durable rows spread over it, and Studio's
// package switcher reads that list; it used to derive "writable"
// client-side from `manifest.scope` alone, which is not this server's
// rule — ADR-0070 D2 (`isWritablePackage`) reads `engine.manifests`
// FIRST, so a scope-less module booted from a multi-package artifact is
// read-only while a scope-less Studio-created base is writable, and only
// the server can tell the two apart. Same predicate the authoring and
// lifecycle gates use (#8146: one answer), computed on a spread COPY:
// the registry record is never mutated and the verdict is never stored.
// The runtime dispatcher door decorates its own read of the same
// records the same way (`withWritableVerdict` in
// `packages/runtime/src/domains/packages.ts`).
if (request.type === 'package' || request.type === 'packages') {
items = (items as any[]).map((pkg) => {
const manifestId = pkg?.manifest?.id;
const id = typeof manifestId === 'string' ? manifestId : (typeof pkg?.id === 'string' ? pkg.id : undefined);
return { ...pkg, writable: this.isWritablePackage(id) };
});
}

return {
type: request.type,
items: decorateMetadataItems(
Expand Down
115 changes: 115 additions & 0 deletions packages/rest/src/package-list-writable-carry.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* REST `GET /packages` CARRIES the producer's `writable` verdict (#14375).
*
* The REST list door does not compute writability itself — it must not: this
* package has no runtime dependency on `@objectstack/metadata-protocol`, and
* the verdict has one definition (`isWritablePackage`, ADR-0070 D2) that the
* protocol's `getMetaItems({ type: 'package' })` now stamps on every registry
* item. What THIS door owns is the merge: the durable (`PackageService.list()`)
* row is spread OVER the registry item, so a durable row that carries no
* `writable` key must leave the registry item's verdict standing, and a
* durable-only row (no registry presence) carries no verdict at all. Both are
* pinned here, because the spread order is the one place this file could lose
* the field.
*/

import { describe, it, expect } from 'vitest';
import type { RouteHandler } from '@objectstack/spec/contracts';
import { registerPackageRoutes } from './package-routes.js';

type Captured = { status: number; body: any };

function mount(svc: any, protocol: any) {
const routes = new Map<string, RouteHandler>();
const server = {
get: (p: string, h: RouteHandler) => { routes.set(`GET:${p}`, h); },
post: (p: string, h: RouteHandler) => { routes.set(`POST:${p}`, h); },
put: () => {},
delete: (p: string, h: RouteHandler) => { routes.set(`DELETE:${p}`, h); },
patch: () => {},
use: () => {},
listen: async () => {},
close: async () => {},
} as any;
// The authorization gate (#7033 / #7023) is not this file's subject.
registerPackageRoutes(server, () => svc, '/api/v1', {
resolveExecutionContext: async () => ({
userId: 'u_pkg', systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'],
}),
protocol,
});
return routes;
}

async function drive(routes: Map<string, RouteHandler>, method: string, path: string, req: Record<string, any> = {}): Promise<Captured> {
const handler = routes.get(`${method}:${path}`);
if (!handler) throw new Error(`no handler for ${method} ${path}`);
const captured: Captured = { status: 200, body: undefined };
const res: any = {
json(data: any) { captured.body = data; },
send() {},
status(code: number) { captured.status = code; return res; },
header() { return res; },
};
await handler({ params: {}, query: {}, body: undefined, headers: {}, method, path, ...req } as any, res);
return captured;
}

/** The scope-less booted module — the producer says read-only. */
const MODULE = 'app.acme.crm.billing';
/** A scope-less Studio base — the producer says writable; it also has a durable row. */
const BASE = 'com.acme.mybase';
/** A durable-only row: published, never registered on this process. */
const DURABLE_ONLY = 'com.acme.published-elsewhere';

const registryItems = [
{ manifest: { id: MODULE, name: MODULE, version: '1.0.0', type: 'module' }, status: 'installed', enabled: true, writable: false },
{ manifest: { id: BASE, name: BASE, version: '1.0.0' }, status: 'installed', enabled: true, writable: true },
];
const protocol = { getMetaItems: async () => ({ type: 'package', items: registryItems }) };
const svc = {
list: async () => [
// The durable row for BASE has NO `writable` key — a durable copy is not
// where the verdict lives.
{ id: BASE, version: '1.0.0', manifest: { id: BASE, name: BASE, version: '1.0.0' } },
{ id: DURABLE_ONLY, version: '3.0.0', manifest: { id: DURABLE_ONLY, version: '3.0.0' } },
],
};

const rowOf = (body: any, id: string) => body.data.packages.find((p: any) => (p.manifest?.id ?? p.id) === id);

describe('REST GET /packages carries the producer\'s writable verdict through the merge (#14375)', () => {
it('a registry-only row keeps the producer\'s verdict', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.status).toBe(200);
const row = rowOf(r.body, MODULE);
expect(row.source).toBe('registry');
expect(row.writable).toBe(false);
});

it('a durable row spread over a registry item does NOT erase the verdict (spread order)', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, BASE);
expect(row.source).toBe('both');
// The durable row carried no `writable`; the registry item's stands.
expect(row.writable).toBe(true);
});

it('a durable-only row carries no verdict — the registry item is the only carrier', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, DURABLE_ONLY);
expect(row.source).toBe('database');
expect('writable' in row).toBe(false);
});

it('is additive: nothing else about the merged rows changed', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.body.data.total).toBe(3);
const { writable, ...rest } = rowOf(r.body, MODULE);
expect(writable).toBe(false);
const { writable: _producerVerdict, ...producerItem } = registryItems[0];
expect(rest).toEqual({ ...producerItem, source: 'registry' });
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/packages-read-door-writable-verdict.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
---
"@objectstack/runtime": patch
"@objectstack/metadata-protocol": patch
---

feat(packages): `GET /packages` and `GET /packages/:id` rows carry the server's own `writable` verdict (#14375)

ADR-0130 Consequences row 6, server half. Every package row served by the two
read doors now carries `writable: boolean`, computed by the SAME predicate the
authoring and lifecycle gates already enforce — `isWritablePackage` (ADR-0070
D2) — so a client no longer has to guess it.

- **Why.** Studio's package switcher derived "writable" client-side from
`manifest.scope` alone (`scope !== 'project'`). That is not the server's
rule: `isWritablePackage` reads `engine.manifests` FIRST, so a package booted
from an artifact through `registerApp` is read-only whatever its scope says —
and a scope-less `type: module` carried by a multi-package artifact lands
there too. A scope-less Studio-created database base is writable. The client
cannot see `engine.manifests`, so it cannot tell those two apart; the server
can, and now says so (#8146: one answer to "is this package writable?").
- **Where.** The runtime dispatcher door (`handlePackagesRequest`, list and
detail) decorates its read of the registry records; the metadata protocol's
`getMetaItems({ type: 'package' })` — the producer the REST `GET /packages`
door spreads its registry half from — decorates the same records the same
way. Both are spread COPIES: the registry's own records are never mutated and
the verdict is never stored.
- **Additive.** No existing key changes; no accept/reject surface moves. A REST
row that has no registry presence (durable-only) carries no verdict, and the
REST detail door's database-first row does not either — the registry item is
the only carrier, by design.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,7 +160,7 @@ The largest single consumer — **20 of the 109 sites**.
| 49 | Action `requiredPermissions` bypassed | runtime | Get: engine self-invocation runs any action | `action-execution.ts:399` |
| 50 | `manage_metadata` bypassed on metadata writes | runtime, rest | Get: schema writes without the capability | `domains/meta.ts:471`, `:874`, `rest-server.ts:4629`, `:5992`, `:6240`, `:6671`, `:6864` |
| 51 | The shared metadata-write verdict itself returns `allowed` | metadata-core | Get: the one function all of row 50's doors consult answers yes before any capability is examined | `meta-write-capability.ts:134` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:246`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:276`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `domains/mcp.ts:61` |
| 54 | Package REST route capability gate bypassed | rest | Get: package read/write over REST without `manage_metadata` / `studio.access` / `setup.access` | `package-routes.ts:102` |
| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `domains/packages.ts:95`, `:128` |
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `getMetaItems({ type: 'package' })` stamps the server's OWN writability
* verdict on every package item (#14375, ADR-0130 Consequences row 6 — the
* producer the REST `GET /packages` door spreads its registry half from).
*
* The verdict is `isWritablePackage` (ADR-0070 D2), the same predicate the
* authoring (`saveMetaItem`) and lifecycle (`DELETE` / `disable`) gates already
* enforce — #8146's "one answer to 'is this package writable?'" applied to the
* read side. It reads `engine.manifests` FIRST: a package booted from an
* artifact through `registerApp` is read-only whatever its scope says, and a
* scope-less `type: module` carried by a multi-package artifact lands there
* too, while a scope-less Studio-created base does not. Only the server holds
* `engine.manifests`, which is why the client could never derive this.
*
* The engine is the same shape `meta-overlay-cache.test.ts` drives: the
* registry surface this method touches, a `find` that answers the overlay
* query with nothing, and — the subject here — a `manifests` map.
*/

import { describe, it, expect } from 'vitest';
import { ObjectStackProtocolImplementation } from './protocol.js';

/** Booted code package, explicit `scope: 'project'`. */
const CODE_PROJECT = 'app.acme.crm';
/** Booted, SCOPE-LESS module — the multi-package-artifact sub-package. */
const CODE_MODULE = 'app.acme.crm.billing';
/** Platform / marketplace delivered. */
const SYSTEM_SCOPED = 'com.objectstack.platform';
const CLOUD_SCOPED = 'com.objectstack.cloudpack';
/** Studio-created database base: installed, never booted, scope-less. */
const DB_BASE = 'com.acme.mybase';

type Row = { manifest: Record<string, unknown>; status: string; enabled: boolean };

function row(id: string, extra: Record<string, unknown> = {}): Row {
return { manifest: { id, name: id, version: '1.0.0', ...extra }, status: 'installed', enabled: true };
}

function make() {
const records: Row[] = [
row(CODE_PROJECT, { scope: 'project', type: 'app' }),
row(CODE_MODULE, { type: 'module' }),
row(SYSTEM_SCOPED, { scope: 'system' }),
row(CLOUD_SCOPED, { scope: 'cloud' }),
row(DB_BASE),
];
const byId = new Map(records.map((r) => [r.manifest.id as string, r]));
// What `ObjectQL.registerApp` records for every package of a loaded artifact.
const manifests = new Map<string, unknown>([
[CODE_PROJECT, byId.get(CODE_PROJECT)!.manifest],
[CODE_MODULE, byId.get(CODE_MODULE)!.manifest],
]);
const engine: any = {
manifests,
find: async () => [],
registry: {
listItems: (type: string) => (type === 'package' ? records : []),
getPackage: (id: string) => byId.get(id),
getItem: () => undefined,
getObject: () => undefined,
getArtifactItem: () => undefined,
isPackageDisabled: () => false,
applyNavContributions: (app: unknown) => app,
},
};
const protocol = new ObjectStackProtocolImplementation(engine, () => new Map());
return { protocol, records };
}

async function listPackages(protocol: ObjectStackProtocolImplementation) {
const res = await protocol.getMetaItems({ type: 'package' });
return res.items as Array<Row & { writable?: boolean }>;
}

const pick = (items: Array<Row & { writable?: boolean }>, id: string) => {
const it = items.find((p) => p.manifest.id === id);
if (!it) throw new Error(`item ${id} missing`);
return it;
};

describe('getMetaItems({ type: "package" }) carries the writable verdict (#14375)', () => {
it('pin 1: a booted code package with scope "project" is writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_PROJECT).writable).toBe(false);
});

it('pin 2: a booted, SCOPE-LESS module is writable: false — the row itself carries no scope', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, CODE_MODULE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(false);
});

it('pin 3: system- and cloud-scoped packages are writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, SYSTEM_SCOPED).writable).toBe(false);
expect(pick(items, CLOUD_SCOPED).writable).toBe(false);
});

it('pin 4: a SCOPE-LESS database base (never booted) is writable: true', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, DB_BASE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(true);
});

it('pins 2 + 4: the two scope-less rows differ ONLY in the verdict — the scope cannot tell them apart', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_MODULE).manifest.scope).toBe(pick(items, DB_BASE).manifest.scope);
expect(pick(items, CODE_MODULE).writable).toBe(false);
expect(pick(items, DB_BASE).writable).toBe(true);
});

it('pin 5: additive and computed — the served row minus `writable` equals the registry record, which is never mutated', async () => {
const { protocol, records } = make();
const items = await listPackages(protocol);
expect(items).toHaveLength(records.length);
for (const record of records) {
const { writable, ...rest } = pick(items, record.manifest.id as string);
expect(typeof writable).toBe('boolean');
expect(rest).toEqual(record);
expect('writable' in record).toBe(false);
}
});

it('does not leak onto other types: an `app` listing gains no `writable` key', async () => {
const { protocol } = make();
const res = await protocol.getMetaItems({ type: 'app' });
for (const it_ of res.items as Array<Record<string, unknown>>) {
expect('writable' in it_).toBe(false);
}
});
});
22 changes: 22 additions & 0 deletions packages/metadata-protocol/src/protocol.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7198,6 +7198,28 @@ export class ObjectStackProtocolImplementation implements
items = (items as any[]).map((app) => this.engine.registry.applyNavContributions(app));
}

// [#14375 / ADR-0130 Consequences row 6] A package row carries the
// server's OWN writability verdict. The REST `GET /packages` door is
// this producer with the durable rows spread over it, and Studio's
// package switcher reads that list; it used to derive "writable"
// client-side from `manifest.scope` alone, which is not this server's
// rule — ADR-0070 D2 (`isWritablePackage`) reads `engine.manifests`
// FIRST, so a scope-less module booted from a multi-package artifact is
// read-only while a scope-less Studio-created base is writable, and only
// the server can tell the two apart. Same predicate the authoring and
// lifecycle gates use (#8146: one answer), computed on a spread COPY:
// the registry record is never mutated and the verdict is never stored.
// The runtime dispatcher door decorates its own read of the same
// records the same way (`withWritableVerdict` in
// `packages/runtime/src/domains/packages.ts`).
if (request.type === 'package' || request.type === 'packages') {
items = (items as any[]).map((pkg) => {
const manifestId = pkg?.manifest?.id;
const id = typeof manifestId === 'string' ? manifestId : (typeof pkg?.id === 'string' ? pkg.id : undefined);
return { ...pkg, writable: this.isWritablePackage(id) };
});
}

return {
type: request.type,
items: decorateMetadataItems(
Expand Down
115 changes: 115 additions & 0 deletions packages/rest/src/package-list-writable-carry.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* REST `GET /packages` CARRIES the producer's `writable` verdict (#14375).
*
* The REST list door does not compute writability itself — it must not: this
* package has no runtime dependency on `@objectstack/metadata-protocol`, and
* the verdict has one definition (`isWritablePackage`, ADR-0070 D2) that the
* protocol's `getMetaItems({ type: 'package' })` now stamps on every registry
* item. What THIS door owns is the merge: the durable (`PackageService.list()`)
* row is spread OVER the registry item, so a durable row that carries no
* `writable` key must leave the registry item's verdict standing, and a
* durable-only row (no registry presence) carries no verdict at all. Both are
* pinned here, because the spread order is the one place this file could lose
* the field.
*/

import { describe, it, expect } from 'vitest';
import type { RouteHandler } from '@objectstack/spec/contracts';
import { registerPackageRoutes } from './package-routes.js';

type Captured = { status: number; body: any };

function mount(svc: any, protocol: any) {
const routes = new Map<string, RouteHandler>();
const server = {
get: (p: string, h: RouteHandler) => { routes.set(`GET:${p}`, h); },
post: (p: string, h: RouteHandler) => { routes.set(`POST:${p}`, h); },
put: () => {},
delete: (p: string, h: RouteHandler) => { routes.set(`DELETE:${p}`, h); },
patch: () => {},
use: () => {},
listen: async () => {},
close: async () => {},
} as any;
// The authorization gate (#7033 / #7023) is not this file's subject.
registerPackageRoutes(server, () => svc, '/api/v1', {
resolveExecutionContext: async () => ({
userId: 'u_pkg', systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'],
}),
protocol,
});
return routes;
}

async function drive(routes: Map<string, RouteHandler>, method: string, path: string, req: Record<string, any> = {}): Promise<Captured> {
const handler = routes.get(`${method}:${path}`);
if (!handler) throw new Error(`no handler for ${method} ${path}`);
const captured: Captured = { status: 200, body: undefined };
const res: any = {
json(data: any) { captured.body = data; },
send() {},
status(code: number) { captured.status = code; return res; },
header() { return res; },
};
await handler({ params: {}, query: {}, body: undefined, headers: {}, method, path, ...req } as any, res);
return captured;
}

/** The scope-less booted module — the producer says read-only. */
const MODULE = 'app.acme.crm.billing';
/** A scope-less Studio base — the producer says writable; it also has a durable row. */
const BASE = 'com.acme.mybase';
/** A durable-only row: published, never registered on this process. */
const DURABLE_ONLY = 'com.acme.published-elsewhere';

const registryItems = [
{ manifest: { id: MODULE, name: MODULE, version: '1.0.0', type: 'module' }, status: 'installed', enabled: true, writable: false },
{ manifest: { id: BASE, name: BASE, version: '1.0.0' }, status: 'installed', enabled: true, writable: true },
];
const protocol = { getMetaItems: async () => ({ type: 'package', items: registryItems }) };
const svc = {
list: async () => [
// The durable row for BASE has NO `writable` key — a durable copy is not
// where the verdict lives.
{ id: BASE, version: '1.0.0', manifest: { id: BASE, name: BASE, version: '1.0.0' } },
{ id: DURABLE_ONLY, version: '3.0.0', manifest: { id: DURABLE_ONLY, version: '3.0.0' } },
],
};

const rowOf = (body: any, id: string) => body.data.packages.find((p: any) => (p.manifest?.id ?? p.id) === id);

describe('REST GET /packages carries the producer\'s writable verdict through the merge (#14375)', () => {
it('a registry-only row keeps the producer\'s verdict', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.status).toBe(200);
const row = rowOf(r.body, MODULE);
expect(row.source).toBe('registry');
expect(row.writable).toBe(false);
});

it('a durable row spread over a registry item does NOT erase the verdict (spread order)', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, BASE);
expect(row.source).toBe('both');
// The durable row carried no `writable`; the registry item's stands.
expect(row.writable).toBe(true);
});

it('a durable-only row carries no verdict — the registry item is the only carrier', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, DURABLE_ONLY);
expect(row.source).toBe('database');
expect('writable' in row).toBe(false);
});

it('is additive: nothing else about the merged rows changed', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.body.data.total).toBe(3);
const { writable, ...rest } = rowOf(r.body, MODULE);
expect(writable).toBe(false);
const { writable: _producerVerdict, ...producerItem } = registryItems[0];
expect(rest).toEqual({ ...producerItem, source: 'registry' });
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/packages-read-door-writable-verdict.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
---
"@objectstack/runtime": patch
"@objectstack/metadata-protocol": patch
---

feat(packages): `GET /packages` and `GET /packages/:id` rows carry the server's own `writable` verdict (#14375)

ADR-0130 Consequences row 6, server half. Every package row served by the two
read doors now carries `writable: boolean`, computed by the SAME predicate the
authoring and lifecycle gates already enforce — `isWritablePackage` (ADR-0070
D2) — so a client no longer has to guess it.

- **Why.** Studio's package switcher derived "writable" client-side from
`manifest.scope` alone (`scope !== 'project'`). That is not the server's
rule: `isWritablePackage` reads `engine.manifests` FIRST, so a package booted
from an artifact through `registerApp` is read-only whatever its scope says —
and a scope-less `type: module` carried by a multi-package artifact lands
there too. A scope-less Studio-created database base is writable. The client
cannot see `engine.manifests`, so it cannot tell those two apart; the server
can, and now says so (#8146: one answer to "is this package writable?").
- **Where.** The runtime dispatcher door (`handlePackagesRequest`, list and
detail) decorates its read of the registry records; the metadata protocol's
`getMetaItems({ type: 'package' })` — the producer the REST `GET /packages`
door spreads its registry half from — decorates the same records the same
way. Both are spread COPIES: the registry's own records are never mutated and
the verdict is never stored.
- **Additive.** No existing key changes; no accept/reject surface moves. A REST
row that has no registry presence (durable-only) carries no verdict, and the
REST detail door's database-first row does not either — the registry item is
the only carrier, by design.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,7 +160,7 @@ The largest single consumer — **20 of the 109 sites**.
| 49 | Action `requiredPermissions` bypassed | runtime | Get: engine self-invocation runs any action | `action-execution.ts:399` |
| 50 | `manage_metadata` bypassed on metadata writes | runtime, rest | Get: schema writes without the capability | `domains/meta.ts:471`, `:874`, `rest-server.ts:4629`, `:5992`, `:6240`, `:6671`, `:6864` |
| 51 | The shared metadata-write verdict itself returns `allowed` | metadata-core | Get: the one function all of row 50's doors consult answers yes before any capability is examined | `meta-write-capability.ts:134` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:246`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:276`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `domains/mcp.ts:61` |
| 54 | Package REST route capability gate bypassed | rest | Get: package read/write over REST without `manage_metadata` / `studio.access` / `setup.access` | `package-routes.ts:102` |
| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `domains/packages.ts:95`, `:128` |
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `getMetaItems({ type: 'package' })` stamps the server's OWN writability
* verdict on every package item (#14375, ADR-0130 Consequences row 6 — the
* producer the REST `GET /packages` door spreads its registry half from).
*
* The verdict is `isWritablePackage` (ADR-0070 D2), the same predicate the
* authoring (`saveMetaItem`) and lifecycle (`DELETE` / `disable`) gates already
* enforce — #8146's "one answer to 'is this package writable?'" applied to the
* read side. It reads `engine.manifests` FIRST: a package booted from an
* artifact through `registerApp` is read-only whatever its scope says, and a
* scope-less `type: module` carried by a multi-package artifact lands there
* too, while a scope-less Studio-created base does not. Only the server holds
* `engine.manifests`, which is why the client could never derive this.
*
* The engine is the same shape `meta-overlay-cache.test.ts` drives: the
* registry surface this method touches, a `find` that answers the overlay
* query with nothing, and — the subject here — a `manifests` map.
*/

import { describe, it, expect } from 'vitest';
import { ObjectStackProtocolImplementation } from './protocol.js';

/** Booted code package, explicit `scope: 'project'`. */
const CODE_PROJECT = 'app.acme.crm';
/** Booted, SCOPE-LESS module — the multi-package-artifact sub-package. */
const CODE_MODULE = 'app.acme.crm.billing';
/** Platform / marketplace delivered. */
const SYSTEM_SCOPED = 'com.objectstack.platform';
const CLOUD_SCOPED = 'com.objectstack.cloudpack';
/** Studio-created database base: installed, never booted, scope-less. */
const DB_BASE = 'com.acme.mybase';

type Row = { manifest: Record<string, unknown>; status: string; enabled: boolean };

function row(id: string, extra: Record<string, unknown> = {}): Row {
return { manifest: { id, name: id, version: '1.0.0', ...extra }, status: 'installed', enabled: true };
}

function make() {
const records: Row[] = [
row(CODE_PROJECT, { scope: 'project', type: 'app' }),
row(CODE_MODULE, { type: 'module' }),
row(SYSTEM_SCOPED, { scope: 'system' }),
row(CLOUD_SCOPED, { scope: 'cloud' }),
row(DB_BASE),
];
const byId = new Map(records.map((r) => [r.manifest.id as string, r]));
// What `ObjectQL.registerApp` records for every package of a loaded artifact.
const manifests = new Map<string, unknown>([
[CODE_PROJECT, byId.get(CODE_PROJECT)!.manifest],
[CODE_MODULE, byId.get(CODE_MODULE)!.manifest],
]);
const engine: any = {
manifests,
find: async () => [],
registry: {
listItems: (type: string) => (type === 'package' ? records : []),
getPackage: (id: string) => byId.get(id),
getItem: () => undefined,
getObject: () => undefined,
getArtifactItem: () => undefined,
isPackageDisabled: () => false,
applyNavContributions: (app: unknown) => app,
},
};
const protocol = new ObjectStackProtocolImplementation(engine, () => new Map());
return { protocol, records };
}

async function listPackages(protocol: ObjectStackProtocolImplementation) {
const res = await protocol.getMetaItems({ type: 'package' });
return res.items as Array<Row & { writable?: boolean }>;
}

const pick = (items: Array<Row & { writable?: boolean }>, id: string) => {
const it = items.find((p) => p.manifest.id === id);
if (!it) throw new Error(`item ${id} missing`);
return it;
};

describe('getMetaItems({ type: "package" }) carries the writable verdict (#14375)', () => {
it('pin 1: a booted code package with scope "project" is writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_PROJECT).writable).toBe(false);
});

it('pin 2: a booted, SCOPE-LESS module is writable: false — the row itself carries no scope', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, CODE_MODULE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(false);
});

it('pin 3: system- and cloud-scoped packages are writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, SYSTEM_SCOPED).writable).toBe(false);
expect(pick(items, CLOUD_SCOPED).writable).toBe(false);
});

it('pin 4: a SCOPE-LESS database base (never booted) is writable: true', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, DB_BASE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(true);
});

it('pins 2 + 4: the two scope-less rows differ ONLY in the verdict — the scope cannot tell them apart', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_MODULE).manifest.scope).toBe(pick(items, DB_BASE).manifest.scope);
expect(pick(items, CODE_MODULE).writable).toBe(false);
expect(pick(items, DB_BASE).writable).toBe(true);
});

it('pin 5: additive and computed — the served row minus `writable` equals the registry record, which is never mutated', async () => {
const { protocol, records } = make();
const items = await listPackages(protocol);
expect(items).toHaveLength(records.length);
for (const record of records) {
const { writable, ...rest } = pick(items, record.manifest.id as string);
expect(typeof writable).toBe('boolean');
expect(rest).toEqual(record);
expect('writable' in record).toBe(false);
}
});

it('does not leak onto other types: an `app` listing gains no `writable` key', async () => {
const { protocol } = make();
const res = await protocol.getMetaItems({ type: 'app' });
for (const it_ of res.items as Array<Record<string, unknown>>) {
expect('writable' in it_).toBe(false);
}
});
});
22 changes: 22 additions & 0 deletions packages/metadata-protocol/src/protocol.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7198,6 +7198,28 @@ export class ObjectStackProtocolImplementation implements
items = (items as any[]).map((app) => this.engine.registry.applyNavContributions(app));
}

// [#14375 / ADR-0130 Consequences row 6] A package row carries the
// server's OWN writability verdict. The REST `GET /packages` door is
// this producer with the durable rows spread over it, and Studio's
// package switcher reads that list; it used to derive "writable"
// client-side from `manifest.scope` alone, which is not this server's
// rule — ADR-0070 D2 (`isWritablePackage`) reads `engine.manifests`
// FIRST, so a scope-less module booted from a multi-package artifact is
// read-only while a scope-less Studio-created base is writable, and only
// the server can tell the two apart. Same predicate the authoring and
// lifecycle gates use (#8146: one answer), computed on a spread COPY:
// the registry record is never mutated and the verdict is never stored.
// The runtime dispatcher door decorates its own read of the same
// records the same way (`withWritableVerdict` in
// `packages/runtime/src/domains/packages.ts`).
if (request.type === 'package' || request.type === 'packages') {
items = (items as any[]).map((pkg) => {
const manifestId = pkg?.manifest?.id;
const id = typeof manifestId === 'string' ? manifestId : (typeof pkg?.id === 'string' ? pkg.id : undefined);
return { ...pkg, writable: this.isWritablePackage(id) };
});
}

return {
type: request.type,
items: decorateMetadataItems(
Expand Down
115 changes: 115 additions & 0 deletions packages/rest/src/package-list-writable-carry.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* REST `GET /packages` CARRIES the producer's `writable` verdict (#14375).
*
* The REST list door does not compute writability itself — it must not: this
* package has no runtime dependency on `@objectstack/metadata-protocol`, and
* the verdict has one definition (`isWritablePackage`, ADR-0070 D2) that the
* protocol's `getMetaItems({ type: 'package' })` now stamps on every registry
* item. What THIS door owns is the merge: the durable (`PackageService.list()`)
* row is spread OVER the registry item, so a durable row that carries no
* `writable` key must leave the registry item's verdict standing, and a
* durable-only row (no registry presence) carries no verdict at all. Both are
* pinned here, because the spread order is the one place this file could lose
* the field.
*/

import { describe, it, expect } from 'vitest';
import type { RouteHandler } from '@objectstack/spec/contracts';
import { registerPackageRoutes } from './package-routes.js';

type Captured = { status: number; body: any };

function mount(svc: any, protocol: any) {
const routes = new Map<string, RouteHandler>();
const server = {
get: (p: string, h: RouteHandler) => { routes.set(`GET:${p}`, h); },
post: (p: string, h: RouteHandler) => { routes.set(`POST:${p}`, h); },
put: () => {},
delete: (p: string, h: RouteHandler) => { routes.set(`DELETE:${p}`, h); },
patch: () => {},
use: () => {},
listen: async () => {},
close: async () => {},
} as any;
// The authorization gate (#7033 / #7023) is not this file's subject.
registerPackageRoutes(server, () => svc, '/api/v1', {
resolveExecutionContext: async () => ({
userId: 'u_pkg', systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'],
}),
protocol,
});
return routes;
}

async function drive(routes: Map<string, RouteHandler>, method: string, path: string, req: Record<string, any> = {}): Promise<Captured> {
const handler = routes.get(`${method}:${path}`);
if (!handler) throw new Error(`no handler for ${method} ${path}`);
const captured: Captured = { status: 200, body: undefined };
const res: any = {
json(data: any) { captured.body = data; },
send() {},
status(code: number) { captured.status = code; return res; },
header() { return res; },
};
await handler({ params: {}, query: {}, body: undefined, headers: {}, method, path, ...req } as any, res);
return captured;
}

/** The scope-less booted module — the producer says read-only. */
const MODULE = 'app.acme.crm.billing';
/** A scope-less Studio base — the producer says writable; it also has a durable row. */
const BASE = 'com.acme.mybase';
/** A durable-only row: published, never registered on this process. */
const DURABLE_ONLY = 'com.acme.published-elsewhere';

const registryItems = [
{ manifest: { id: MODULE, name: MODULE, version: '1.0.0', type: 'module' }, status: 'installed', enabled: true, writable: false },
{ manifest: { id: BASE, name: BASE, version: '1.0.0' }, status: 'installed', enabled: true, writable: true },
];
const protocol = { getMetaItems: async () => ({ type: 'package', items: registryItems }) };
const svc = {
list: async () => [
// The durable row for BASE has NO `writable` key — a durable copy is not
// where the verdict lives.
{ id: BASE, version: '1.0.0', manifest: { id: BASE, name: BASE, version: '1.0.0' } },
{ id: DURABLE_ONLY, version: '3.0.0', manifest: { id: DURABLE_ONLY, version: '3.0.0' } },
],
};

const rowOf = (body: any, id: string) => body.data.packages.find((p: any) => (p.manifest?.id ?? p.id) === id);

describe('REST GET /packages carries the producer\'s writable verdict through the merge (#14375)', () => {
it('a registry-only row keeps the producer\'s verdict', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.status).toBe(200);
const row = rowOf(r.body, MODULE);
expect(row.source).toBe('registry');
expect(row.writable).toBe(false);
});

it('a durable row spread over a registry item does NOT erase the verdict (spread order)', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, BASE);
expect(row.source).toBe('both');
// The durable row carried no `writable`; the registry item's stands.
expect(row.writable).toBe(true);
});

it('a durable-only row carries no verdict — the registry item is the only carrier', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, DURABLE_ONLY);
expect(row.source).toBe('database');
expect('writable' in row).toBe(false);
});

it('is additive: nothing else about the merged rows changed', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.body.data.total).toBe(3);
const { writable, ...rest } = rowOf(r.body, MODULE);
expect(writable).toBe(false);
const { writable: _producerVerdict, ...producerItem } = registryItems[0];
expect(rest).toEqual({ ...producerItem, source: 'registry' });
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/packages-read-door-writable-verdict.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
---
"@objectstack/runtime": patch
"@objectstack/metadata-protocol": patch
---

feat(packages): `GET /packages` and `GET /packages/:id` rows carry the server's own `writable` verdict (#14375)

ADR-0130 Consequences row 6, server half. Every package row served by the two
read doors now carries `writable: boolean`, computed by the SAME predicate the
authoring and lifecycle gates already enforce — `isWritablePackage` (ADR-0070
D2) — so a client no longer has to guess it.

- **Why.** Studio's package switcher derived "writable" client-side from
`manifest.scope` alone (`scope !== 'project'`). That is not the server's
rule: `isWritablePackage` reads `engine.manifests` FIRST, so a package booted
from an artifact through `registerApp` is read-only whatever its scope says —
and a scope-less `type: module` carried by a multi-package artifact lands
there too. A scope-less Studio-created database base is writable. The client
cannot see `engine.manifests`, so it cannot tell those two apart; the server
can, and now says so (#8146: one answer to "is this package writable?").
- **Where.** The runtime dispatcher door (`handlePackagesRequest`, list and
detail) decorates its read of the registry records; the metadata protocol's
`getMetaItems({ type: 'package' })` — the producer the REST `GET /packages`
door spreads its registry half from — decorates the same records the same
way. Both are spread COPIES: the registry's own records are never mutated and
the verdict is never stored.
- **Additive.** No existing key changes; no accept/reject surface moves. A REST
row that has no registry presence (durable-only) carries no verdict, and the
REST detail door's database-first row does not either — the registry item is
the only carrier, by design.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,7 +160,7 @@ The largest single consumer — **20 of the 109 sites**.
| 49 | Action `requiredPermissions` bypassed | runtime | Get: engine self-invocation runs any action | `action-execution.ts:399` |
| 50 | `manage_metadata` bypassed on metadata writes | runtime, rest | Get: schema writes without the capability | `domains/meta.ts:471`, `:874`, `rest-server.ts:4629`, `:5992`, `:6240`, `:6671`, `:6864` |
| 51 | The shared metadata-write verdict itself returns `allowed` | metadata-core | Get: the one function all of row 50's doors consult answers yes before any capability is examined | `meta-write-capability.ts:134` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:246`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:276`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `domains/mcp.ts:61` |
| 54 | Package REST route capability gate bypassed | rest | Get: package read/write over REST without `manage_metadata` / `studio.access` / `setup.access` | `package-routes.ts:102` |
| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `domains/packages.ts:95`, `:128` |
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `getMetaItems({ type: 'package' })` stamps the server's OWN writability
* verdict on every package item (#14375, ADR-0130 Consequences row 6 — the
* producer the REST `GET /packages` door spreads its registry half from).
*
* The verdict is `isWritablePackage` (ADR-0070 D2), the same predicate the
* authoring (`saveMetaItem`) and lifecycle (`DELETE` / `disable`) gates already
* enforce — #8146's "one answer to 'is this package writable?'" applied to the
* read side. It reads `engine.manifests` FIRST: a package booted from an
* artifact through `registerApp` is read-only whatever its scope says, and a
* scope-less `type: module` carried by a multi-package artifact lands there
* too, while a scope-less Studio-created base does not. Only the server holds
* `engine.manifests`, which is why the client could never derive this.
*
* The engine is the same shape `meta-overlay-cache.test.ts` drives: the
* registry surface this method touches, a `find` that answers the overlay
* query with nothing, and — the subject here — a `manifests` map.
*/

import { describe, it, expect } from 'vitest';
import { ObjectStackProtocolImplementation } from './protocol.js';

/** Booted code package, explicit `scope: 'project'`. */
const CODE_PROJECT = 'app.acme.crm';
/** Booted, SCOPE-LESS module — the multi-package-artifact sub-package. */
const CODE_MODULE = 'app.acme.crm.billing';
/** Platform / marketplace delivered. */
const SYSTEM_SCOPED = 'com.objectstack.platform';
const CLOUD_SCOPED = 'com.objectstack.cloudpack';
/** Studio-created database base: installed, never booted, scope-less. */
const DB_BASE = 'com.acme.mybase';

type Row = { manifest: Record<string, unknown>; status: string; enabled: boolean };

function row(id: string, extra: Record<string, unknown> = {}): Row {
return { manifest: { id, name: id, version: '1.0.0', ...extra }, status: 'installed', enabled: true };
}

function make() {
const records: Row[] = [
row(CODE_PROJECT, { scope: 'project', type: 'app' }),
row(CODE_MODULE, { type: 'module' }),
row(SYSTEM_SCOPED, { scope: 'system' }),
row(CLOUD_SCOPED, { scope: 'cloud' }),
row(DB_BASE),
];
const byId = new Map(records.map((r) => [r.manifest.id as string, r]));
// What `ObjectQL.registerApp` records for every package of a loaded artifact.
const manifests = new Map<string, unknown>([
[CODE_PROJECT, byId.get(CODE_PROJECT)!.manifest],
[CODE_MODULE, byId.get(CODE_MODULE)!.manifest],
]);
const engine: any = {
manifests,
find: async () => [],
registry: {
listItems: (type: string) => (type === 'package' ? records : []),
getPackage: (id: string) => byId.get(id),
getItem: () => undefined,
getObject: () => undefined,
getArtifactItem: () => undefined,
isPackageDisabled: () => false,
applyNavContributions: (app: unknown) => app,
},
};
const protocol = new ObjectStackProtocolImplementation(engine, () => new Map());
return { protocol, records };
}

async function listPackages(protocol: ObjectStackProtocolImplementation) {
const res = await protocol.getMetaItems({ type: 'package' });
return res.items as Array<Row & { writable?: boolean }>;
}

const pick = (items: Array<Row & { writable?: boolean }>, id: string) => {
const it = items.find((p) => p.manifest.id === id);
if (!it) throw new Error(`item ${id} missing`);
return it;
};

describe('getMetaItems({ type: "package" }) carries the writable verdict (#14375)', () => {
it('pin 1: a booted code package with scope "project" is writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_PROJECT).writable).toBe(false);
});

it('pin 2: a booted, SCOPE-LESS module is writable: false — the row itself carries no scope', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, CODE_MODULE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(false);
});

it('pin 3: system- and cloud-scoped packages are writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, SYSTEM_SCOPED).writable).toBe(false);
expect(pick(items, CLOUD_SCOPED).writable).toBe(false);
});

it('pin 4: a SCOPE-LESS database base (never booted) is writable: true', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, DB_BASE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(true);
});

it('pins 2 + 4: the two scope-less rows differ ONLY in the verdict — the scope cannot tell them apart', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_MODULE).manifest.scope).toBe(pick(items, DB_BASE).manifest.scope);
expect(pick(items, CODE_MODULE).writable).toBe(false);
expect(pick(items, DB_BASE).writable).toBe(true);
});

it('pin 5: additive and computed — the served row minus `writable` equals the registry record, which is never mutated', async () => {
const { protocol, records } = make();
const items = await listPackages(protocol);
expect(items).toHaveLength(records.length);
for (const record of records) {
const { writable, ...rest } = pick(items, record.manifest.id as string);
expect(typeof writable).toBe('boolean');
expect(rest).toEqual(record);
expect('writable' in record).toBe(false);
}
});

it('does not leak onto other types: an `app` listing gains no `writable` key', async () => {
const { protocol } = make();
const res = await protocol.getMetaItems({ type: 'app' });
for (const it_ of res.items as Array<Record<string, unknown>>) {
expect('writable' in it_).toBe(false);
}
});
});
22 changes: 22 additions & 0 deletions packages/metadata-protocol/src/protocol.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7198,6 +7198,28 @@ export class ObjectStackProtocolImplementation implements
items = (items as any[]).map((app) => this.engine.registry.applyNavContributions(app));
}

// [#14375 / ADR-0130 Consequences row 6] A package row carries the
// server's OWN writability verdict. The REST `GET /packages` door is
// this producer with the durable rows spread over it, and Studio's
// package switcher reads that list; it used to derive "writable"
// client-side from `manifest.scope` alone, which is not this server's
// rule — ADR-0070 D2 (`isWritablePackage`) reads `engine.manifests`
// FIRST, so a scope-less module booted from a multi-package artifact is
// read-only while a scope-less Studio-created base is writable, and only
// the server can tell the two apart. Same predicate the authoring and
// lifecycle gates use (#8146: one answer), computed on a spread COPY:
// the registry record is never mutated and the verdict is never stored.
// The runtime dispatcher door decorates its own read of the same
// records the same way (`withWritableVerdict` in
// `packages/runtime/src/domains/packages.ts`).
if (request.type === 'package' || request.type === 'packages') {
items = (items as any[]).map((pkg) => {
const manifestId = pkg?.manifest?.id;
const id = typeof manifestId === 'string' ? manifestId : (typeof pkg?.id === 'string' ? pkg.id : undefined);
return { ...pkg, writable: this.isWritablePackage(id) };
});
}

return {
type: request.type,
items: decorateMetadataItems(
Expand Down
115 changes: 115 additions & 0 deletions packages/rest/src/package-list-writable-carry.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* REST `GET /packages` CARRIES the producer's `writable` verdict (#14375).
*
* The REST list door does not compute writability itself — it must not: this
* package has no runtime dependency on `@objectstack/metadata-protocol`, and
* the verdict has one definition (`isWritablePackage`, ADR-0070 D2) that the
* protocol's `getMetaItems({ type: 'package' })` now stamps on every registry
* item. What THIS door owns is the merge: the durable (`PackageService.list()`)
* row is spread OVER the registry item, so a durable row that carries no
* `writable` key must leave the registry item's verdict standing, and a
* durable-only row (no registry presence) carries no verdict at all. Both are
* pinned here, because the spread order is the one place this file could lose
* the field.
*/

import { describe, it, expect } from 'vitest';
import type { RouteHandler } from '@objectstack/spec/contracts';
import { registerPackageRoutes } from './package-routes.js';

type Captured = { status: number; body: any };

function mount(svc: any, protocol: any) {
const routes = new Map<string, RouteHandler>();
const server = {
get: (p: string, h: RouteHandler) => { routes.set(`GET:${p}`, h); },
post: (p: string, h: RouteHandler) => { routes.set(`POST:${p}`, h); },
put: () => {},
delete: (p: string, h: RouteHandler) => { routes.set(`DELETE:${p}`, h); },
patch: () => {},
use: () => {},
listen: async () => {},
close: async () => {},
} as any;
// The authorization gate (#7033 / #7023) is not this file's subject.
registerPackageRoutes(server, () => svc, '/api/v1', {
resolveExecutionContext: async () => ({
userId: 'u_pkg', systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'],
}),
protocol,
});
return routes;
}

async function drive(routes: Map<string, RouteHandler>, method: string, path: string, req: Record<string, any> = {}): Promise<Captured> {
const handler = routes.get(`${method}:${path}`);
if (!handler) throw new Error(`no handler for ${method} ${path}`);
const captured: Captured = { status: 200, body: undefined };
const res: any = {
json(data: any) { captured.body = data; },
send() {},
status(code: number) { captured.status = code; return res; },
header() { return res; },
};
await handler({ params: {}, query: {}, body: undefined, headers: {}, method, path, ...req } as any, res);
return captured;
}

/** The scope-less booted module — the producer says read-only. */
const MODULE = 'app.acme.crm.billing';
/** A scope-less Studio base — the producer says writable; it also has a durable row. */
const BASE = 'com.acme.mybase';
/** A durable-only row: published, never registered on this process. */
const DURABLE_ONLY = 'com.acme.published-elsewhere';

const registryItems = [
{ manifest: { id: MODULE, name: MODULE, version: '1.0.0', type: 'module' }, status: 'installed', enabled: true, writable: false },
{ manifest: { id: BASE, name: BASE, version: '1.0.0' }, status: 'installed', enabled: true, writable: true },
];
const protocol = { getMetaItems: async () => ({ type: 'package', items: registryItems }) };
const svc = {
list: async () => [
// The durable row for BASE has NO `writable` key — a durable copy is not
// where the verdict lives.
{ id: BASE, version: '1.0.0', manifest: { id: BASE, name: BASE, version: '1.0.0' } },
{ id: DURABLE_ONLY, version: '3.0.0', manifest: { id: DURABLE_ONLY, version: '3.0.0' } },
],
};

const rowOf = (body: any, id: string) => body.data.packages.find((p: any) => (p.manifest?.id ?? p.id) === id);

describe('REST GET /packages carries the producer\'s writable verdict through the merge (#14375)', () => {
it('a registry-only row keeps the producer\'s verdict', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.status).toBe(200);
const row = rowOf(r.body, MODULE);
expect(row.source).toBe('registry');
expect(row.writable).toBe(false);
});

it('a durable row spread over a registry item does NOT erase the verdict (spread order)', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, BASE);
expect(row.source).toBe('both');
// The durable row carried no `writable`; the registry item's stands.
expect(row.writable).toBe(true);
});

it('a durable-only row carries no verdict — the registry item is the only carrier', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, DURABLE_ONLY);
expect(row.source).toBe('database');
expect('writable' in row).toBe(false);
});

it('is additive: nothing else about the merged rows changed', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.body.data.total).toBe(3);
const { writable, ...rest } = rowOf(r.body, MODULE);
expect(writable).toBe(false);
const { writable: _producerVerdict, ...producerItem } = registryItems[0];
expect(rest).toEqual({ ...producerItem, source: 'registry' });
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/packages-read-door-writable-verdict.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
---
"@objectstack/runtime": patch
"@objectstack/metadata-protocol": patch
---

feat(packages): `GET /packages` and `GET /packages/:id` rows carry the server's own `writable` verdict (#14375)

ADR-0130 Consequences row 6, server half. Every package row served by the two
read doors now carries `writable: boolean`, computed by the SAME predicate the
authoring and lifecycle gates already enforce — `isWritablePackage` (ADR-0070
D2) — so a client no longer has to guess it.

- **Why.** Studio's package switcher derived "writable" client-side from
`manifest.scope` alone (`scope !== 'project'`). That is not the server's
rule: `isWritablePackage` reads `engine.manifests` FIRST, so a package booted
from an artifact through `registerApp` is read-only whatever its scope says —
and a scope-less `type: module` carried by a multi-package artifact lands
there too. A scope-less Studio-created database base is writable. The client
cannot see `engine.manifests`, so it cannot tell those two apart; the server
can, and now says so (#8146: one answer to "is this package writable?").
- **Where.** The runtime dispatcher door (`handlePackagesRequest`, list and
detail) decorates its read of the registry records; the metadata protocol's
`getMetaItems({ type: 'package' })` — the producer the REST `GET /packages`
door spreads its registry half from — decorates the same records the same
way. Both are spread COPIES: the registry's own records are never mutated and
the verdict is never stored.
- **Additive.** No existing key changes; no accept/reject surface moves. A REST
row that has no registry presence (durable-only) carries no verdict, and the
REST detail door's database-first row does not either — the registry item is
the only carrier, by design.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,7 +160,7 @@ The largest single consumer — **20 of the 109 sites**.
| 49 | Action `requiredPermissions` bypassed | runtime | Get: engine self-invocation runs any action | `action-execution.ts:399` |
| 50 | `manage_metadata` bypassed on metadata writes | runtime, rest | Get: schema writes without the capability | `domains/meta.ts:471`, `:874`, `rest-server.ts:4629`, `:5992`, `:6240`, `:6671`, `:6864` |
| 51 | The shared metadata-write verdict itself returns `allowed` | metadata-core | Get: the one function all of row 50's doors consult answers yes before any capability is examined | `meta-write-capability.ts:134` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:246`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:276`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `domains/mcp.ts:61` |
| 54 | Package REST route capability gate bypassed | rest | Get: package read/write over REST without `manage_metadata` / `studio.access` / `setup.access` | `package-routes.ts:102` |
| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `domains/packages.ts:95`, `:128` |
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `getMetaItems({ type: 'package' })` stamps the server's OWN writability
* verdict on every package item (#14375, ADR-0130 Consequences row 6 — the
* producer the REST `GET /packages` door spreads its registry half from).
*
* The verdict is `isWritablePackage` (ADR-0070 D2), the same predicate the
* authoring (`saveMetaItem`) and lifecycle (`DELETE` / `disable`) gates already
* enforce — #8146's "one answer to 'is this package writable?'" applied to the
* read side. It reads `engine.manifests` FIRST: a package booted from an
* artifact through `registerApp` is read-only whatever its scope says, and a
* scope-less `type: module` carried by a multi-package artifact lands there
* too, while a scope-less Studio-created base does not. Only the server holds
* `engine.manifests`, which is why the client could never derive this.
*
* The engine is the same shape `meta-overlay-cache.test.ts` drives: the
* registry surface this method touches, a `find` that answers the overlay
* query with nothing, and — the subject here — a `manifests` map.
*/

import { describe, it, expect } from 'vitest';
import { ObjectStackProtocolImplementation } from './protocol.js';

/** Booted code package, explicit `scope: 'project'`. */
const CODE_PROJECT = 'app.acme.crm';
/** Booted, SCOPE-LESS module — the multi-package-artifact sub-package. */
const CODE_MODULE = 'app.acme.crm.billing';
/** Platform / marketplace delivered. */
const SYSTEM_SCOPED = 'com.objectstack.platform';
const CLOUD_SCOPED = 'com.objectstack.cloudpack';
/** Studio-created database base: installed, never booted, scope-less. */
const DB_BASE = 'com.acme.mybase';

type Row = { manifest: Record<string, unknown>; status: string; enabled: boolean };

function row(id: string, extra: Record<string, unknown> = {}): Row {
return { manifest: { id, name: id, version: '1.0.0', ...extra }, status: 'installed', enabled: true };
}

function make() {
const records: Row[] = [
row(CODE_PROJECT, { scope: 'project', type: 'app' }),
row(CODE_MODULE, { type: 'module' }),
row(SYSTEM_SCOPED, { scope: 'system' }),
row(CLOUD_SCOPED, { scope: 'cloud' }),
row(DB_BASE),
];
const byId = new Map(records.map((r) => [r.manifest.id as string, r]));
// What `ObjectQL.registerApp` records for every package of a loaded artifact.
const manifests = new Map<string, unknown>([
[CODE_PROJECT, byId.get(CODE_PROJECT)!.manifest],
[CODE_MODULE, byId.get(CODE_MODULE)!.manifest],
]);
const engine: any = {
manifests,
find: async () => [],
registry: {
listItems: (type: string) => (type === 'package' ? records : []),
getPackage: (id: string) => byId.get(id),
getItem: () => undefined,
getObject: () => undefined,
getArtifactItem: () => undefined,
isPackageDisabled: () => false,
applyNavContributions: (app: unknown) => app,
},
};
const protocol = new ObjectStackProtocolImplementation(engine, () => new Map());
return { protocol, records };
}

async function listPackages(protocol: ObjectStackProtocolImplementation) {
const res = await protocol.getMetaItems({ type: 'package' });
return res.items as Array<Row & { writable?: boolean }>;
}

const pick = (items: Array<Row & { writable?: boolean }>, id: string) => {
const it = items.find((p) => p.manifest.id === id);
if (!it) throw new Error(`item ${id} missing`);
return it;
};

describe('getMetaItems({ type: "package" }) carries the writable verdict (#14375)', () => {
it('pin 1: a booted code package with scope "project" is writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_PROJECT).writable).toBe(false);
});

it('pin 2: a booted, SCOPE-LESS module is writable: false — the row itself carries no scope', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, CODE_MODULE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(false);
});

it('pin 3: system- and cloud-scoped packages are writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, SYSTEM_SCOPED).writable).toBe(false);
expect(pick(items, CLOUD_SCOPED).writable).toBe(false);
});

it('pin 4: a SCOPE-LESS database base (never booted) is writable: true', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, DB_BASE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(true);
});

it('pins 2 + 4: the two scope-less rows differ ONLY in the verdict — the scope cannot tell them apart', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_MODULE).manifest.scope).toBe(pick(items, DB_BASE).manifest.scope);
expect(pick(items, CODE_MODULE).writable).toBe(false);
expect(pick(items, DB_BASE).writable).toBe(true);
});

it('pin 5: additive and computed — the served row minus `writable` equals the registry record, which is never mutated', async () => {
const { protocol, records } = make();
const items = await listPackages(protocol);
expect(items).toHaveLength(records.length);
for (const record of records) {
const { writable, ...rest } = pick(items, record.manifest.id as string);
expect(typeof writable).toBe('boolean');
expect(rest).toEqual(record);
expect('writable' in record).toBe(false);
}
});

it('does not leak onto other types: an `app` listing gains no `writable` key', async () => {
const { protocol } = make();
const res = await protocol.getMetaItems({ type: 'app' });
for (const it_ of res.items as Array<Record<string, unknown>>) {
expect('writable' in it_).toBe(false);
}
});
});
22 changes: 22 additions & 0 deletions packages/metadata-protocol/src/protocol.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7198,6 +7198,28 @@ export class ObjectStackProtocolImplementation implements
items = (items as any[]).map((app) => this.engine.registry.applyNavContributions(app));
}

// [#14375 / ADR-0130 Consequences row 6] A package row carries the
// server's OWN writability verdict. The REST `GET /packages` door is
// this producer with the durable rows spread over it, and Studio's
// package switcher reads that list; it used to derive "writable"
// client-side from `manifest.scope` alone, which is not this server's
// rule — ADR-0070 D2 (`isWritablePackage`) reads `engine.manifests`
// FIRST, so a scope-less module booted from a multi-package artifact is
// read-only while a scope-less Studio-created base is writable, and only
// the server can tell the two apart. Same predicate the authoring and
// lifecycle gates use (#8146: one answer), computed on a spread COPY:
// the registry record is never mutated and the verdict is never stored.
// The runtime dispatcher door decorates its own read of the same
// records the same way (`withWritableVerdict` in
// `packages/runtime/src/domains/packages.ts`).
if (request.type === 'package' || request.type === 'packages') {
items = (items as any[]).map((pkg) => {
const manifestId = pkg?.manifest?.id;
const id = typeof manifestId === 'string' ? manifestId : (typeof pkg?.id === 'string' ? pkg.id : undefined);
return { ...pkg, writable: this.isWritablePackage(id) };
});
}

return {
type: request.type,
items: decorateMetadataItems(
Expand Down
115 changes: 115 additions & 0 deletions packages/rest/src/package-list-writable-carry.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* REST `GET /packages` CARRIES the producer's `writable` verdict (#14375).
*
* The REST list door does not compute writability itself — it must not: this
* package has no runtime dependency on `@objectstack/metadata-protocol`, and
* the verdict has one definition (`isWritablePackage`, ADR-0070 D2) that the
* protocol's `getMetaItems({ type: 'package' })` now stamps on every registry
* item. What THIS door owns is the merge: the durable (`PackageService.list()`)
* row is spread OVER the registry item, so a durable row that carries no
* `writable` key must leave the registry item's verdict standing, and a
* durable-only row (no registry presence) carries no verdict at all. Both are
* pinned here, because the spread order is the one place this file could lose
* the field.
*/

import { describe, it, expect } from 'vitest';
import type { RouteHandler } from '@objectstack/spec/contracts';
import { registerPackageRoutes } from './package-routes.js';

type Captured = { status: number; body: any };

function mount(svc: any, protocol: any) {
const routes = new Map<string, RouteHandler>();
const server = {
get: (p: string, h: RouteHandler) => { routes.set(`GET:${p}`, h); },
post: (p: string, h: RouteHandler) => { routes.set(`POST:${p}`, h); },
put: () => {},
delete: (p: string, h: RouteHandler) => { routes.set(`DELETE:${p}`, h); },
patch: () => {},
use: () => {},
listen: async () => {},
close: async () => {},
} as any;
// The authorization gate (#7033 / #7023) is not this file's subject.
registerPackageRoutes(server, () => svc, '/api/v1', {
resolveExecutionContext: async () => ({
userId: 'u_pkg', systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'],
}),
protocol,
});
return routes;
}

async function drive(routes: Map<string, RouteHandler>, method: string, path: string, req: Record<string, any> = {}): Promise<Captured> {
const handler = routes.get(`${method}:${path}`);
if (!handler) throw new Error(`no handler for ${method} ${path}`);
const captured: Captured = { status: 200, body: undefined };
const res: any = {
json(data: any) { captured.body = data; },
send() {},
status(code: number) { captured.status = code; return res; },
header() { return res; },
};
await handler({ params: {}, query: {}, body: undefined, headers: {}, method, path, ...req } as any, res);
return captured;
}

/** The scope-less booted module — the producer says read-only. */
const MODULE = 'app.acme.crm.billing';
/** A scope-less Studio base — the producer says writable; it also has a durable row. */
const BASE = 'com.acme.mybase';
/** A durable-only row: published, never registered on this process. */
const DURABLE_ONLY = 'com.acme.published-elsewhere';

const registryItems = [
{ manifest: { id: MODULE, name: MODULE, version: '1.0.0', type: 'module' }, status: 'installed', enabled: true, writable: false },
{ manifest: { id: BASE, name: BASE, version: '1.0.0' }, status: 'installed', enabled: true, writable: true },
];
const protocol = { getMetaItems: async () => ({ type: 'package', items: registryItems }) };
const svc = {
list: async () => [
// The durable row for BASE has NO `writable` key — a durable copy is not
// where the verdict lives.
{ id: BASE, version: '1.0.0', manifest: { id: BASE, name: BASE, version: '1.0.0' } },
{ id: DURABLE_ONLY, version: '3.0.0', manifest: { id: DURABLE_ONLY, version: '3.0.0' } },
],
};

const rowOf = (body: any, id: string) => body.data.packages.find((p: any) => (p.manifest?.id ?? p.id) === id);

describe('REST GET /packages carries the producer\'s writable verdict through the merge (#14375)', () => {
it('a registry-only row keeps the producer\'s verdict', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.status).toBe(200);
const row = rowOf(r.body, MODULE);
expect(row.source).toBe('registry');
expect(row.writable).toBe(false);
});

it('a durable row spread over a registry item does NOT erase the verdict (spread order)', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, BASE);
expect(row.source).toBe('both');
// The durable row carried no `writable`; the registry item's stands.
expect(row.writable).toBe(true);
});

it('a durable-only row carries no verdict — the registry item is the only carrier', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, DURABLE_ONLY);
expect(row.source).toBe('database');
expect('writable' in row).toBe(false);
});

it('is additive: nothing else about the merged rows changed', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.body.data.total).toBe(3);
const { writable, ...rest } = rowOf(r.body, MODULE);
expect(writable).toBe(false);
const { writable: _producerVerdict, ...producerItem } = registryItems[0];
expect(rest).toEqual({ ...producerItem, source: 'registry' });
});
});
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .changeset/packages-read-door-writable-verdict.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
---
"@objectstack/runtime": patch
"@objectstack/metadata-protocol": patch
---

feat(packages): `GET /packages` and `GET /packages/:id` rows carry the server's own `writable` verdict (#14375)

ADR-0130 Consequences row 6, server half. Every package row served by the two
read doors now carries `writable: boolean`, computed by the SAME predicate the
authoring and lifecycle gates already enforce — `isWritablePackage` (ADR-0070
D2) — so a client no longer has to guess it.

- **Why.** Studio's package switcher derived "writable" client-side from
`manifest.scope` alone (`scope !== 'project'`). That is not the server's
rule: `isWritablePackage` reads `engine.manifests` FIRST, so a package booted
from an artifact through `registerApp` is read-only whatever its scope says —
and a scope-less `type: module` carried by a multi-package artifact lands
there too. A scope-less Studio-created database base is writable. The client
cannot see `engine.manifests`, so it cannot tell those two apart; the server
can, and now says so (#8146: one answer to "is this package writable?").
- **Where.** The runtime dispatcher door (`handlePackagesRequest`, list and
detail) decorates its read of the registry records; the metadata protocol's
`getMetaItems({ type: 'package' })` — the producer the REST `GET /packages`
door spreads its registry half from — decorates the same records the same
way. Both are spread COPIES: the registry's own records are never mutated and
the verdict is never stored.
- **Additive.** No existing key changes; no accept/reject surface moves. A REST
row that has no registry presence (durable-only) carries no verdict, and the
REST detail door's database-first row does not either — the registry item is
the only carrier, by design.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -160,7 +160,7 @@ The largest single consumer — **20 of the 109 sites**.
| 49 | Action `requiredPermissions` bypassed | runtime | Get: engine self-invocation runs any action | `action-execution.ts:399` |
| 50 | `manage_metadata` bypassed on metadata writes | runtime, rest | Get: schema writes without the capability | `domains/meta.ts:471`, `:874`, `rest-server.ts:4629`, `:5992`, `:6240`, `:6671`, `:6864` |
| 51 | The shared metadata-write verdict itself returns `allowed` | metadata-core | Get: the one function all of row 50's doors consult answers yes before any capability is examined | `meta-write-capability.ts:134` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:246`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 52 | Anonymous-deny seam satisfied on the domain dispatchers and the package/federation routes | runtime, rest | Get: passes with no `userId` | `domains/actions.ts:411`, `domains/ai.ts:60`, `domains/automation.ts:989`, `domains/meta.ts:232`, `domains/security.ts:78`, `domains/packages.ts:276`, `external-datasource-routes.ts:302`, `package-routes.ts:97` |
| 53 | MCP principal check satisfied | runtime | Get: MCP surface reachable with no user | `domains/mcp.ts:61` |
| 54 | Package REST route capability gate bypassed | rest | Get: package read/write over REST without `manage_metadata` / `studio.access` / `setup.access` | `package-routes.ts:102` |
| 55 | Package domain capability gates bypassed | runtime | Get: package management and package-inventory reads without the capability | `domains/packages.ts:95`, `:128` |
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `getMetaItems({ type: 'package' })` stamps the server's OWN writability
* verdict on every package item (#14375, ADR-0130 Consequences row 6 — the
* producer the REST `GET /packages` door spreads its registry half from).
*
* The verdict is `isWritablePackage` (ADR-0070 D2), the same predicate the
* authoring (`saveMetaItem`) and lifecycle (`DELETE` / `disable`) gates already
* enforce — #8146's "one answer to 'is this package writable?'" applied to the
* read side. It reads `engine.manifests` FIRST: a package booted from an
* artifact through `registerApp` is read-only whatever its scope says, and a
* scope-less `type: module` carried by a multi-package artifact lands there
* too, while a scope-less Studio-created base does not. Only the server holds
* `engine.manifests`, which is why the client could never derive this.
*
* The engine is the same shape `meta-overlay-cache.test.ts` drives: the
* registry surface this method touches, a `find` that answers the overlay
* query with nothing, and — the subject here — a `manifests` map.
*/

import { describe, it, expect } from 'vitest';
import { ObjectStackProtocolImplementation } from './protocol.js';

/** Booted code package, explicit `scope: 'project'`. */
const CODE_PROJECT = 'app.acme.crm';
/** Booted, SCOPE-LESS module — the multi-package-artifact sub-package. */
const CODE_MODULE = 'app.acme.crm.billing';
/** Platform / marketplace delivered. */
const SYSTEM_SCOPED = 'com.objectstack.platform';
const CLOUD_SCOPED = 'com.objectstack.cloudpack';
/** Studio-created database base: installed, never booted, scope-less. */
const DB_BASE = 'com.acme.mybase';

type Row = { manifest: Record<string, unknown>; status: string; enabled: boolean };

function row(id: string, extra: Record<string, unknown> = {}): Row {
return { manifest: { id, name: id, version: '1.0.0', ...extra }, status: 'installed', enabled: true };
}

function make() {
const records: Row[] = [
row(CODE_PROJECT, { scope: 'project', type: 'app' }),
row(CODE_MODULE, { type: 'module' }),
row(SYSTEM_SCOPED, { scope: 'system' }),
row(CLOUD_SCOPED, { scope: 'cloud' }),
row(DB_BASE),
];
const byId = new Map(records.map((r) => [r.manifest.id as string, r]));
// What `ObjectQL.registerApp` records for every package of a loaded artifact.
const manifests = new Map<string, unknown>([
[CODE_PROJECT, byId.get(CODE_PROJECT)!.manifest],
[CODE_MODULE, byId.get(CODE_MODULE)!.manifest],
]);
const engine: any = {
manifests,
find: async () => [],
registry: {
listItems: (type: string) => (type === 'package' ? records : []),
getPackage: (id: string) => byId.get(id),
getItem: () => undefined,
getObject: () => undefined,
getArtifactItem: () => undefined,
isPackageDisabled: () => false,
applyNavContributions: (app: unknown) => app,
},
};
const protocol = new ObjectStackProtocolImplementation(engine, () => new Map());
return { protocol, records };
}

async function listPackages(protocol: ObjectStackProtocolImplementation) {
const res = await protocol.getMetaItems({ type: 'package' });
return res.items as Array<Row & { writable?: boolean }>;
}

const pick = (items: Array<Row & { writable?: boolean }>, id: string) => {
const it = items.find((p) => p.manifest.id === id);
if (!it) throw new Error(`item ${id} missing`);
return it;
};

describe('getMetaItems({ type: "package" }) carries the writable verdict (#14375)', () => {
it('pin 1: a booted code package with scope "project" is writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_PROJECT).writable).toBe(false);
});

it('pin 2: a booted, SCOPE-LESS module is writable: false — the row itself carries no scope', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, CODE_MODULE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(false);
});

it('pin 3: system- and cloud-scoped packages are writable: false', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, SYSTEM_SCOPED).writable).toBe(false);
expect(pick(items, CLOUD_SCOPED).writable).toBe(false);
});

it('pin 4: a SCOPE-LESS database base (never booted) is writable: true', async () => {
const items = await listPackages(make().protocol);
const it_ = pick(items, DB_BASE);
expect(it_.manifest.scope).toBeUndefined();
expect(it_.writable).toBe(true);
});

it('pins 2 + 4: the two scope-less rows differ ONLY in the verdict — the scope cannot tell them apart', async () => {
const items = await listPackages(make().protocol);
expect(pick(items, CODE_MODULE).manifest.scope).toBe(pick(items, DB_BASE).manifest.scope);
expect(pick(items, CODE_MODULE).writable).toBe(false);
expect(pick(items, DB_BASE).writable).toBe(true);
});

it('pin 5: additive and computed — the served row minus `writable` equals the registry record, which is never mutated', async () => {
const { protocol, records } = make();
const items = await listPackages(protocol);
expect(items).toHaveLength(records.length);
for (const record of records) {
const { writable, ...rest } = pick(items, record.manifest.id as string);
expect(typeof writable).toBe('boolean');
expect(rest).toEqual(record);
expect('writable' in record).toBe(false);
}
});

it('does not leak onto other types: an `app` listing gains no `writable` key', async () => {
const { protocol } = make();
const res = await protocol.getMetaItems({ type: 'app' });
for (const it_ of res.items as Array<Record<string, unknown>>) {
expect('writable' in it_).toBe(false);
}
});
});
22 changes: 22 additions & 0 deletions packages/metadata-protocol/src/protocol.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -7198,6 +7198,28 @@ export class ObjectStackProtocolImplementation implements
items = (items as any[]).map((app) => this.engine.registry.applyNavContributions(app));
}

// [#14375 / ADR-0130 Consequences row 6] A package row carries the
// server's OWN writability verdict. The REST `GET /packages` door is
// this producer with the durable rows spread over it, and Studio's
// package switcher reads that list; it used to derive "writable"
// client-side from `manifest.scope` alone, which is not this server's
// rule — ADR-0070 D2 (`isWritablePackage`) reads `engine.manifests`
// FIRST, so a scope-less module booted from a multi-package artifact is
// read-only while a scope-less Studio-created base is writable, and only
// the server can tell the two apart. Same predicate the authoring and
// lifecycle gates use (#8146: one answer), computed on a spread COPY:
// the registry record is never mutated and the verdict is never stored.
// The runtime dispatcher door decorates its own read of the same
// records the same way (`withWritableVerdict` in
// `packages/runtime/src/domains/packages.ts`).
if (request.type === 'package' || request.type === 'packages') {
items = (items as any[]).map((pkg) => {
const manifestId = pkg?.manifest?.id;
const id = typeof manifestId === 'string' ? manifestId : (typeof pkg?.id === 'string' ? pkg.id : undefined);
return { ...pkg, writable: this.isWritablePackage(id) };
});
}

return {
type: request.type,
items: decorateMetadataItems(
Expand Down
115 changes: 115 additions & 0 deletions packages/rest/src/package-list-writable-carry.test.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* REST `GET /packages` CARRIES the producer's `writable` verdict (#14375).
*
* The REST list door does not compute writability itself — it must not: this
* package has no runtime dependency on `@objectstack/metadata-protocol`, and
* the verdict has one definition (`isWritablePackage`, ADR-0070 D2) that the
* protocol's `getMetaItems({ type: 'package' })` now stamps on every registry
* item. What THIS door owns is the merge: the durable (`PackageService.list()`)
* row is spread OVER the registry item, so a durable row that carries no
* `writable` key must leave the registry item's verdict standing, and a
* durable-only row (no registry presence) carries no verdict at all. Both are
* pinned here, because the spread order is the one place this file could lose
* the field.
*/

import { describe, it, expect } from 'vitest';
import type { RouteHandler } from '@objectstack/spec/contracts';
import { registerPackageRoutes } from './package-routes.js';

type Captured = { status: number; body: any };

function mount(svc: any, protocol: any) {
const routes = new Map<string, RouteHandler>();
const server = {
get: (p: string, h: RouteHandler) => { routes.set(`GET:${p}`, h); },
post: (p: string, h: RouteHandler) => { routes.set(`POST:${p}`, h); },
put: () => {},
delete: (p: string, h: RouteHandler) => { routes.set(`DELETE:${p}`, h); },
patch: () => {},
use: () => {},
listen: async () => {},
close: async () => {},
} as any;
// The authorization gate (#7033 / #7023) is not this file's subject.
registerPackageRoutes(server, () => svc, '/api/v1', {
resolveExecutionContext: async () => ({
userId: 'u_pkg', systemPermissions: ['manage_metadata', 'studio.access', 'setup.access'],
}),
protocol,
});
return routes;
}

async function drive(routes: Map<string, RouteHandler>, method: string, path: string, req: Record<string, any> = {}): Promise<Captured> {
const handler = routes.get(`${method}:${path}`);
if (!handler) throw new Error(`no handler for ${method} ${path}`);
const captured: Captured = { status: 200, body: undefined };
const res: any = {
json(data: any) { captured.body = data; },
send() {},
status(code: number) { captured.status = code; return res; },
header() { return res; },
};
await handler({ params: {}, query: {}, body: undefined, headers: {}, method, path, ...req } as any, res);
return captured;
}

/** The scope-less booted module — the producer says read-only. */
const MODULE = 'app.acme.crm.billing';
/** A scope-less Studio base — the producer says writable; it also has a durable row. */
const BASE = 'com.acme.mybase';
/** A durable-only row: published, never registered on this process. */
const DURABLE_ONLY = 'com.acme.published-elsewhere';

const registryItems = [
{ manifest: { id: MODULE, name: MODULE, version: '1.0.0', type: 'module' }, status: 'installed', enabled: true, writable: false },
{ manifest: { id: BASE, name: BASE, version: '1.0.0' }, status: 'installed', enabled: true, writable: true },
];
const protocol = { getMetaItems: async () => ({ type: 'package', items: registryItems }) };
const svc = {
list: async () => [
// The durable row for BASE has NO `writable` key — a durable copy is not
// where the verdict lives.
{ id: BASE, version: '1.0.0', manifest: { id: BASE, name: BASE, version: '1.0.0' } },
{ id: DURABLE_ONLY, version: '3.0.0', manifest: { id: DURABLE_ONLY, version: '3.0.0' } },
],
};

const rowOf = (body: any, id: string) => body.data.packages.find((p: any) => (p.manifest?.id ?? p.id) === id);

describe('REST GET /packages carries the producer\'s writable verdict through the merge (#14375)', () => {
it('a registry-only row keeps the producer\'s verdict', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.status).toBe(200);
const row = rowOf(r.body, MODULE);
expect(row.source).toBe('registry');
expect(row.writable).toBe(false);
});

it('a durable row spread over a registry item does NOT erase the verdict (spread order)', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, BASE);
expect(row.source).toBe('both');
// The durable row carried no `writable`; the registry item's stands.
expect(row.writable).toBe(true);
});

it('a durable-only row carries no verdict — the registry item is the only carrier', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
const row = rowOf(r.body, DURABLE_ONLY);
expect(row.source).toBe('database');
expect('writable' in row).toBe(false);
});

it('is additive: nothing else about the merged rows changed', async () => {
const r = await drive(mount(svc, protocol), 'GET', '/api/v1/packages');
expect(r.body.data.total).toBe(3);
const { writable, ...rest } = rowOf(r.body, MODULE);
expect(writable).toBe(false);
const { writable: _producerVerdict, ...producerItem } = registryItems[0];
expect(rest).toEqual({ ...producerItem, source: 'registry' });
});
});
Loading
Loading