diff --git a/.changeset/35157-capability-draft-count.md b/.changeset/35157-capability-draft-count.md new file mode 100644 index 00000000000..ce3cabd5af3 --- /dev/null +++ b/.changeset/35157-capability-draft-count.md @@ -0,0 +1,10 @@ +--- +'@object-ui/i18n': patch +--- + +feat(i18n): a count family for capability drafts in the pending-changes summary + +Clause-②: no +Metadata-protocol: none + +Every locale pack adds `preview.changes.typeCount.capability` (and its plural forms), so the console's pending-changes summary reads "2 capabilities" (`能力 2` in Chinese) instead of the raw type name when a publish carries capability drafts. diff --git a/.changeset/35157-scaffold-no-connector-plugins.md b/.changeset/35157-scaffold-no-connector-plugins.md new file mode 100644 index 00000000000..d31a9e4474d --- /dev/null +++ b/.changeset/35157-scaffold-no-connector-plugins.md @@ -0,0 +1,12 @@ +--- +'create-objectstack': minor +--- + +feat(create-objectstack): the blank scaffold lists no connector plugins until the app declares a connector + +Clause-②: no +Metadata-protocol: none + +A new project's `objectstack.config.ts` no longer lists `ConnectorRestPlugin`, `ConnectorOpenApiPlugin` and `ConnectorMcpPlugin`, and its `package.json` no longer depends on the three connector packages. A plugin is code, so an app that lists any plugin installs managed only. The scaffold's own plugin list therefore kept every AI-built app from installing as an unmanaged copy, such as a marketplace trial. + +To use a connector, install its provider package and add it to `plugins:`, for example `plugins: [new ConnectorRestPlugin()]`. The template's README and the comment in `objectstack.config.ts` show how. The install contract is unchanged: a stack that lists plugins still validates for managed install only. diff --git a/.changeset/35157-unmanaged-copy-capabilities.md b/.changeset/35157-unmanaged-copy-capabilities.md new file mode 100644 index 00000000000..57e2701cb71 --- /dev/null +++ b/.changeset/35157-unmanaged-copy-capabilities.md @@ -0,0 +1,24 @@ +--- +'@objectstack/spec': minor +'@objectstack/metadata-protocol': minor +'@objectstack/objectql': minor +'@objectstack/plugin-security': patch +'@objectstack/cli': patch +--- + +feat(security): an unmanaged install copies an app's capabilities, renamed with the copy + +Clause-②: yes (widening) +Metadata-protocol: added + +An app that gates an action on its own capability can now install as an unmanaged copy (`installModes: ['unmanaged']`). Before, `capability` was code-only (`allowRuntimeCreate: false`), so the validator refused the mode for any app that declared one, and the install door had no channel to write the copy's capabilities. + +- **`capability` is runtime-creatable.** Its `DEFAULT_METADATA_TYPE_REGISTRY` entry is now `allowRuntimeCreate: true`, and overlays stay closed (`supportsOverlay: false`, `allowEnvironmentOverlay: false`). A body is judged by `CapabilityDeclarationSchema`, as before. +- **The save door refuses two names.** + - A platform capability's name (`manage_users`, `setup.access`, every name in `PLATFORM_CAPABILITIES`) answers `422 NAMESPACE_CONFLICT`. An environment item under that name would shadow the platform's definition, because the registry answers its bare slot first. + - A name an installed package's capability holds answers `422 NAMESPACE_CONFLICT`, naming the holder. A capability holds one name per deployment, the same rule permission sets and positions follow. +- **The environment catalog holds capabilities.** `ENVIRONMENT_HELD_SECURITY_CATALOG_TYPES` is `['position', 'permission', 'capability']`. A package that ships a capability name the environment already authored is refused at boot, as a position or permission-set name is. `os migrate security-catalog-overlays`, the remedy that refusal names, lists and deletes such a capability row too (`capability` and `capabilities` spellings). +- **An unmanaged copy renames its capabilities.** When the copy takes a new namespace, a capability whose name starts with the source namespace (`.` or `_`) is renamed into the copy's namespace. Every reference is rewritten with it: a permission set's `systemPermissions` (list or per-operation map), an object's or action's `requiredPermissions`, and a quoted `current_user.hasCapability('')` in a predicate. There the object-name rename never touches a name the package declares, so a capability named after a renamed object has one name in the copy; a token the package does not declare follows a renamed object as before. An unprefixed capability keeps its name. A renamed capability that collides with another package's capability refuses the install, naming both. Install again under another namespace. +- **Duplicating a package refuses a shared gate.** `duplicatePackage` keeps its source installed, so a capability it cannot rename (no source prefix, or a copy name the package already declares) is refused, and so is every copied item that grants, requires or tests for it, each at its own name in `failed[]`. +- **The `everyone` anchor excuses only a declaration that carries a package.** The check that refuses a high-privilege permission set bound to `everyone` excuses the tokens an app declared itself. It now counts only declarations bound to a package (`_packageId`), as ADR-0090 D5 rules: an app's shipped capabilities, an unmanaged copy's, and one saved into a writable package. A capability saved with no package excuses nothing. What bounds a saved declaration is the two refusals above: a platform capability is never excused, and a name a package declares cannot be declared again. A name nobody declares can be declared once, by a `manage_metadata` holder, inside a writable package. +- **The gate is unchanged.** It still matches capability names. The copy's action is gated on the copy's capability: a holder of the copy's permission set passes, and a holder of only the source's set does not. diff --git a/content/docs/automation/connectors.mdx b/content/docs/automation/connectors.mdx index 8aa55d776c4..4cd8e0a2b72 100644 --- a/content/docs/automation/connectors.mdx +++ b/content/docs/automation/connectors.mdx @@ -72,9 +72,12 @@ At boot, the automation service resolves each provider-bound entry: 1. **Look up the provider factory** registered under `entry.provider`. The three generic executors — `@objectstack/connector-rest`, `@objectstack/connector-openapi`, `@objectstack/connector-mcp` — each - contribute one; scaffolded projects (`npm create objectstack`) ship all - three in `plugins:` by default, paired with the `automation` capability - that performs the materialization. + contribute one. A scaffolded project (`npm create objectstack`) lists + none: install the provider's package and add its executor to `plugins:` + when the app first declares a connector, beside the `automation` + capability that performs the materialization. A plugin is code, so an app + that lists one installs only as a managed package, never as an editable + (`unmanaged`) copy. 2. **The factory validates `providerConfig`** and the automation service resolves `auth.credentialRef` to its secret (see [What `credentialRef` resolves through](#what-credentialref-resolves-through)). diff --git a/content/docs/deployment/install-modes.mdx b/content/docs/deployment/install-modes.mdx index 3704db0e2ec..a66e5a176fb 100644 --- a/content/docs/deployment/install-modes.mdx +++ b/content/docs/deployment/install-modes.mdx @@ -58,8 +58,13 @@ while it carries something that door cannot write as environment metadata. The refusal is `STACK_UNMANAGED_INSTALL_UNCOPYABLE`, with one finding per key: - items of a metadata type the metadata-type registry declares - runtime-uncreatable (`allowRuntimeCreate: false`); -- code: `functions`, `plugins` and the other keys that carry or describe code; + runtime-uncreatable (`allowRuntimeCreate: false`). A package's own + capabilities are not among them: they are copied, with the permission sets + that grant them and the actions, flows and objects that require them; +- code: `functions`, `plugins` and the other keys that carry or describe code. + A project scaffolded by `npm create objectstack` lists no `plugins`; add a + connector's plugin only when the app declares that connector, and it then + installs managed only; - extensions of another package's items: `objectExtensions`, `picklistExtensions`, `navigationContributions`, `contributes`; - `packages`, which describes an artifact of several packages, while one @@ -244,6 +249,14 @@ The copy is renamed by the same rules as duplicating a package: is a whole prefixed object name (`crm_lead`, never `x_crm_lead`). - **Translations are named `acme_`**, with the object keys inside them renamed. +- **A capability the package names with its prefix takes the new one.** + `crm.approve_deal` copies as `acme.approve_deal` (and `crm_approve_deal` as + `acme_approve_deal`), and every permission set's `systemPermissions` grant and + every `requiredPermissions` requirement of it in the copy follows, so the copy + never shares a gate with the package or another copy. A capability the package + does not declare, a platform one among them, keeps its name, unless it is + spelled with the name of an object the copy renames: then it follows the + object (`crm_lead.convert` copies as `acme_lead.convert`). - **An object of another package keeps its name**, and so do its view items. `targetNamespace` follows the rule for a manifest `namespace`, and the @@ -256,6 +269,7 @@ refusal is answered before the base exists, so nothing is installed: | An object whose copy name another object's copy takes (`ticket` beside `crm_ticket`) | `400 INVALID_REQUEST`, naming the object and the rename that clears it | | A copy name that is not a legal item name, longer than an object's table name may be (63 characters), or longer than an item name may be (255) | `400 INVALID_REQUEST`, naming each item | | A renamed key that meets a key the item already holds (a permission set granting both `crm_lead` and `acme_lead`) | `400 INVALID_REQUEST`, naming the item and both keys | +| A capability whose copy name another capability of the package declares (`crm.approve` beside `acme.approve`) | `400 INVALID_REQUEST`, naming the capability | | A renamed name the environment or a managed package already holds | `409 RESOURCE_CONFLICT`, naming each | | A `targetNamespace` another package owns | `409 RESOURCE_CONFLICT`, naming it | diff --git a/content/docs/getting-started/your-first-project.mdx b/content/docs/getting-started/your-first-project.mdx index 97d44aca983..356aa2fcfae 100644 --- a/content/docs/getting-started/your-first-project.mdx +++ b/content/docs/getting-started/your-first-project.mdx @@ -136,9 +136,6 @@ view, action or flow adds a file and one export line to its directory's ```typescript title="objectstack.config.ts" import { defineStack } from '@objectstack/spec'; -import { ConnectorRestPlugin } from '@objectstack/connector-rest'; -import { ConnectorOpenApiPlugin } from '@objectstack/connector-openapi'; -import { ConnectorMcpPlugin } from '@objectstack/connector-mcp'; import * as objects from './src/objects'; import * as views from './src/views'; import * as actions from './src/actions'; @@ -162,16 +159,10 @@ export default defineStack({ engines: { protocol: '^18' }, }, // `automation` runs flows and, per ADR-0097, materializes declarative - // `connectors:` entries at boot. The three generic executors below register - // their `rest` / `openapi` / `mcp` provider factories with it. `triggers` - // fires a flow that starts on a record change, the kind `os generate flow` - // writes. + // `connectors:` entries at boot, through the provider factory a connector + // executor in `plugins:` registers. `triggers` fires a flow that starts on + // a record change, the kind `os generate flow` writes. requires: ['automation', 'triggers'], - plugins: [ - new ConnectorRestPlugin(), - new ConnectorOpenApiPlugin(), - new ConnectorMcpPlugin(), - ], objects: exportsOf(objects), views: exportsOf(views), actions: exportsOf(actions), @@ -216,11 +207,15 @@ them a pattern to rely on: The REST API needs no configuration — it is on by default for every object -with `apiEnabled`. The `plugins:` array ships the three **generic connector -executors**, so you can integrate an external REST / OpenAPI / MCP service as -pure metadata: add a `connectors:` entry naming a `provider` and the -`automation` capability materializes it into a live connector at boot — see -[Automation → Flows](/docs/automation/flows). +with `apiEnabled`. The starter lists no `plugins:`: a plugin is code, and an app +with code in `plugins:` installs only as a managed package, never as the +editable copy a marketplace trial template is (`manifest.installModes: +['unmanaged']`). To integrate an external REST / OpenAPI / MCP service as pure +metadata, install that **generic connector executor** +(`@objectstack/connector-rest`, `-openapi` or `-mcp`), list it in `plugins:`, +and add a `connectors:` entry naming its `provider`; the `automation` +capability materializes it into a live connector at boot — see +[Automation → Connectors](/docs/automation/connectors). **`src/objects/note.object.ts`** is a complete data model — schema, validation, API surface, and searchability in one typed definition: diff --git a/content/docs/permissions/capabilities.mdx b/content/docs/permissions/capabilities.mdx index 576cfdcd4a5..4a6db28cf68 100644 --- a/content/docs/permissions/capabilities.mdx +++ b/content/docs/permissions/capabilities.mdx @@ -224,49 +224,76 @@ deletes the seeded copies (ADR-0131 D10). Withdraw a capability by withdrawing the **grant**. -## `capability` is code-only +## Declaring a capability in the environment `capability` is a registered metadata kind, and its registry entry declares -`allowRuntimeCreate: false` **and** `allowEnvironmentOverlay: false`. Together those -are the code-only declaration, so: - -``` -PUT /api/v1/meta/capability/:name - → 403 NOT_CREATABLE - "Metadata type 'capability' is code-only: the metadata-type registry - declares allowRuntimeCreate=false and allowEnvironmentOverlay=false, so it - cannot be created through the runtime metadata API … on any kernel. - Declare it in source (**/*.capability.ts) and redeploy." -``` - -The refusal fires **before** the body is validated, on every kernel, in draft -mode as well as active. This is deliberate and follows straight from the -three-way separation: an administrator minting a brand-new capability at runtime -has no counterpart in it — nothing in code would ever *require* the name, so the -result is an unreferenced grant target sitting in the live authorization -namespace. `job` and `agent` carry the same pair for the same reason. +`allowRuntimeCreate: true` with `allowEnvironmentOverlay: false`. So an +environment may declare a capability of its own through the metadata door +(`PUT /api/v1/meta/capability/:name`), but never re-declare one a package +ships. An `unmanaged` install is the write that needs this: it copies an app +into the environment, and an app that gates its actions on its own +capabilities copies them too (below). + +Every such write is judged before anything is stored: + +- **The body** by `CapabilityDeclarationSchema`; a malformed one is + `422 INVALID_METADATA`. +- **A platform capability's name** (`manage_users`, `manage_metadata`, …) is + refused `422 NAMESPACE_CONFLICT`. A declaration under it would re-declare a + platform power's `scope`, and the scope decides whether an organization + administrator may hand out the sets that grant it. +- **A name another holder declares** — a package, the environment, or another + copy — is refused `422 NAMESPACE_CONFLICT`, naming the holder. A grant and a + requirement match a capability by name across the whole deployment, so one + name has one holder. + +At the `everyone` anchor, a token a package's declaration names is the app's +own and is excused (ADR-0090 D5): one an app ships, one an unmanaged copy +writes, and one saved into a package the environment can write (a copy, a +duplicate, a base you author). A capability saved with no package is not, +whatever package its own `packageId` names: binding a permission set that grants it to `everyone` is judged as for any +undeclared token, and refused as high-privilege. The two refusals above are +what bounds this. No declaration can take a platform capability's name, so a +platform power is never excused, and none can take a name a package already +declares. A name nobody declares, such as a token an app grants or requires +without declaring it, can be declared once inside a writable package, and that +declaration decides its `scope` and excuses it at the anchor. Only a holder of +`manage_metadata` can save one. Under a `group` or `isolated` tenancy posture, a caller below the platform -operator reads a different refusal, with the same `403` status: the walled -refusal every environment-metadata write takes there (ADR-0131 D3, D12 items -7–8), whose message names the posture, with the code `FORBIDDEN` on the REST -door and `PERMISSION_DENIED` on the runtime dispatcher. -It runs before the code-only refusal, so the block above is the answer the -platform operator reads, and every caller under `single`. - -Two things this does **not** close: - -- **The package-declaration channel is untouched.** `AppPlugin` registers stack - `capabilities[]` through the in-memory registry and the filesystem loader - globs `filePatterns`; neither goes through the runtime write door. -- **`supportsOverlay: false`** — a capability is a name, a label and a scope; - there is no merge semantic, and a per-organization overlay of a - package-shipped declaration could re-scope `org` → `platform`. - -`OS_METADATA_WRITABLE=capability` remains the one documented operator escape -hatch (ADR-0005). Behind it the write is judged by `CapabilityDeclarationSchema` -and a malformed body is rejected with `422 invalid_metadata` — it is not a way -to store arbitrary JSON on the authorization surface. +operator reads the walled refusal every environment-metadata write takes there +(ADR-0131 D3, D12 items 7–8) before any of these. + +The package-declaration channel is untouched: `AppPlugin` registers stack +`capabilities[]` through the in-memory registry and the filesystem loader globs +`filePatterns`; neither goes through the runtime write door. +`supportsOverlay: false` still holds — a capability is a name, a label and a +scope, with no merge semantic. + +### In an unmanaged copy + +A package that permits `installModes: ['unmanaged']` may declare capabilities. +The copy writes each one into the environment, owned by the copy. Installed +under a `targetNamespace`, a capability the package names with its namespace +(`demoasset.manage_assets`, or `demoasset_manage_assets`) takes the target's +(`trial1.manage_assets`), and every `systemPermissions` grant and +`requiredPermissions` requirement of it in the copy follows. So two copies of +one app never share a gate. The name follows into a component's `visibleWhen` +too, where `current_user.hasCapability('')` gates it with a quoted name. +A capability named after an object the copy renames (`crm.crm_invoice.void`) +keeps one name in the copy, the declaration's (`shop.crm_invoice.void`), in +every place that names it. A name the package does not declare — a platform +capability it grants or requires, or another package's — is not renamed as a +capability. It keeps its name, unless it is spelled with the name of an object +the copy renames: then it follows the object, as other text does, in the +grant, the requirement and the predicate alike (`crm_invoice.void` copies as +`shop_invoice.void`). + +A capability the package declares without its namespace prefix keeps its name. +An unmanaged install keeps it; a second holder of that name refuses the whole +install. Duplicating a package refuses that capability, and every item that +grants, requires or tests for it, because the source stays installed beside the +copy and the two would share one gate. Prefix your capability names. ## Checklist diff --git a/packages/cli/src/commands/migrate/security-catalog-overlays.integration.test.ts b/packages/cli/src/commands/migrate/security-catalog-overlays.integration.test.ts index 9033fdf2eb0..3db184ece00 100644 --- a/packages/cli/src/commands/migrate/security-catalog-overlays.integration.test.ts +++ b/packages/cli/src/commands/migrate/security-catalog-overlays.integration.test.ts @@ -9,12 +9,14 @@ * ## The fixture * * A compiled artifact (`dist/objectstack.json`, the shape a deployed app boots - * from) whose package declares two positions and one permission set, over a + * from) whose package declares two positions, one permission set and one + * capability, over a * database an older release left behind with: * * - LISTED: a `permission` row and a `position` row over the package's names, - * one bound to no package and one bound to the package itself, and a - * legacy-plural `positions` row over the package's other position; + * one bound to no package and one bound to the package itself, a + * legacy-plural `positions` row over the package's other position, and + * (#35157) a `capability` row over the capability the package declares; * - LISTED ONLY WITH AUTH ON: a legacy-plural `permissions` row over * `member_default`, a set the platform security plugin declares — and that * plugin is composed only behind `os serve`'s auth gate; @@ -56,6 +58,9 @@ import MigrateSecurityCatalogOverlays from './security-catalog-overlays.js'; import '@objectstack/runtime'; import '@objectstack/metadata-protocol'; import '@objectstack/platform-objects/plugin'; +import '@objectstack/rest'; +import '@objectstack/service-datasource'; +import '@objectstack/driver-turso'; const HERE = dirname(fileURLToPath(import.meta.url)); const CLI_ROOT = resolve(HERE, '..', '..', '..'); @@ -66,6 +71,7 @@ const ARTIFACT = { manifest: { id: PKG, name: 'm22371', version: '1.0.0', type: 'app' }, positions: [{ name: 'm22371_lead', label: 'Lead' }, { name: 'm22371_old_lead', label: 'Old lead' }], permissions: [{ name: 'm22371_rep', label: 'Rep', objects: {} }], + capabilities: [{ name: 'm22371.approve', label: 'Approve' }], }; interface SeedRow { type: string; name: string; organization_id: string | null; package_id: string | null; state: string } @@ -74,6 +80,7 @@ const SEED: SeedRow[] = [ { type: 'position', name: 'm22371_lead', organization_id: null, package_id: PKG, state: 'active' }, { type: 'positions', name: 'm22371_old_lead', organization_id: null, package_id: null, state: 'active' }, { type: 'permissions', name: 'member_default', organization_id: null, package_id: null, state: 'active' }, + { type: 'capability', name: 'm22371.approve', organization_id: null, package_id: null, state: 'active' }, // Controls. { type: 'permission', name: 'm22371_free', organization_id: null, package_id: null, state: 'active' }, { type: 'permission', name: 'm22371_rep', organization_id: 'org_m22371', package_id: null, state: 'active' }, @@ -87,10 +94,13 @@ const LISTED_AUTH_OFF = [ `position/m22371_lead@${PKG} ${PKG}`, `positions/m22371_old_lead@- ${PKG}`, `permission/m22371_rep@- ${PKG}`, + `capability/m22371.approve@- ${PKG}`, ]; +// Positions, then permission sets, then capabilities (the step's order). const LISTED_AUTH_ON = [ - ...LISTED_AUTH_OFF, + ...LISTED_AUTH_OFF.slice(0, 3), `permissions/member_default@- ${SECURITY_PLUGIN_ID}`, + ...LISTED_AUTH_OFF.slice(3), ]; const CONTROLS = [ @@ -340,11 +350,16 @@ describe('os migrate security-catalog-overlays --apply — deletes exactly the l 'positions/m22371_old_lead deleted sys-metadata-repository', 'permission/m22371_rep deleted protocol.deleteMetaItem', 'permissions/member_default deleted sys-metadata-repository', + // [#35157] The protocol's door refuses a capability row over a managed + // package's capability (its type takes no overlay), so it takes the + // repository beneath, as a legacy plural does. + 'capability/m22371.approve deleted sys-metadata-repository', ]); // Exactly the listed rows are gone; every control is still stored. const after = await storedRows(db); expect(before.filter((r) => !after.includes(r)).sort()).toEqual([ + 'capability/m22371.approve/env/active', 'permission/m22371_rep/env/active', 'permissions/member_default/env/active', 'position/m22371_lead/env/active', @@ -356,6 +371,7 @@ describe('os migrate security-catalog-overlays --apply — deletes exactly the l // row for each one the protocol's door deleted. const { history, audit } = await trail(db); expect(history).toEqual([ + 'capability/m22371.approve delete by os migrate security-catalog-overlays', 'permission/m22371_rep delete by os migrate security-catalog-overlays', 'permissions/member_default delete by os migrate security-catalog-overlays', 'position/m22371_lead delete by os migrate security-catalog-overlays', diff --git a/packages/cli/src/commands/migrate/security-catalog-overlays.ts b/packages/cli/src/commands/migrate/security-catalog-overlays.ts index 2c6f7f47b35..b2ad69171ee 100644 --- a/packages/cli/src/commands/migrate/security-catalog-overlays.ts +++ b/packages/cli/src/commands/migrate/security-catalog-overlays.ts @@ -41,7 +41,7 @@ async function confirm(question: string): Promise { /** One row as the report shows it, in both faces. */ function describeRow(row: SecurityCatalogOverlayRow): string { - const label = row.catalogType === 'permission' ? 'permission set' : 'position'; + const label = row.catalogType === 'permission' ? 'permission set' : row.catalogType; const spelling = row.storedType === row.catalogType ? '' : ` (stored under the legacy type '${row.storedType}')`; const binding = row.packageId ? `bound to ${row.packageId}` : 'bound to no package'; return `${label} "${row.name}"${spelling}, ${binding}, row ${row.id} — held by ${row.heldBy.join(', ')}`; @@ -64,7 +64,7 @@ function jsonRow(row: SecurityCatalogOverlayRow, outcome?: SecurityCatalogOverla /** * `os migrate security-catalog-overlays` — list, and with `--apply` delete, the * environment-wide `sys_metadata` rows a v18 cold boot refuses: an active, - * environment-wide `permission` / `position` row (the legacy plurals included) + * environment-wide `permission` / `position` / `capability` row (the plurals included) * whose name a configured package holds (ADR-0048 N.3). * * ## Why an offline step @@ -120,7 +120,7 @@ function jsonRow(row: SecurityCatalogOverlayRow, outcome?: SecurityCatalogOverla */ export default class MigrateSecurityCatalogOverlays extends Command { static override description = - 'List, and with --apply delete, the environment-wide permission-set and position rows (legacy plurals ' + 'List, and with --apply delete, the environment-wide permission-set, position and capability rows (plurals ' + 'included) over a name a configured package holds — the rows a v18 cold boot refuses. Run before the first ' + 'v18 boot.'; @@ -216,7 +216,7 @@ export default class MigrateSecurityCatalogOverlays extends Command { return; } const ok = await confirm( - chalk.bold('\nDelete the environment-wide rows over package-held permission-set and position names? [y/N] '), + chalk.bold('\nDelete the environment-wide rows over package-held permission-set, position and capability names? [y/N] '), ); if (!ok) { printInfo('Aborted — nothing deleted.'); @@ -323,7 +323,7 @@ export default class MigrateSecurityCatalogOverlays extends Command { console.log(''); if (rows.length === 0) { printSuccess( - 'No environment-wide permission-set or position row is stored over a package-held name — ' + 'No environment-wide permission-set, position or capability row is stored over a package-held name — ' + `nothing here refuses the cold boot ${chalk.dim(`(${timer.display()})`)}`, ); return exitCode; diff --git a/packages/cli/src/utils/security-catalog-overlays.ts b/packages/cli/src/utils/security-catalog-overlays.ts index 43d46d8c427..8af3320c33e 100644 --- a/packages/cli/src/utils/security-catalog-overlays.ts +++ b/packages/cli/src/utils/security-catalog-overlays.ts @@ -10,8 +10,9 @@ * Every active environment `sys_metadata` row (`state = 'active'`; on a * database the organization-ownership ceremony has not migrated, a row whose * physical `organization_id` holds a value is a legacy organization's and is - * left out, ADR-0131 D6/D7) of type `permission` or `position` — the legacy plurals - * `permissions` / `positions` included, which the boot's load folds to the same + * left out, ADR-0131 D6/D7) of type `permission`, `position` or (#35157) + * `capability` — the plurals `permissions` / `positions` / `capabilities` + * included, which the boot's load folds to the same * types — whose name a configured package holds. That is exactly what the cold * boot's catalog check refuses (ADR-0048 N.3): the check meets the package-held * names with what `sys_metadata` hydration put in the registry's bare slot, and @@ -39,7 +40,9 @@ * * A row stored under a legacy plural is out of that door's reach: it folds the * type it is given to the canonical one before reading, and the audit trail - * refuses a non-canonical type by design. Such a row goes through the layer + * refuses a non-canonical type by design. So is a `capability` row (#35157): + * the door reads the managed seal for a type that takes no overlay, and + * refuses to remove it. Such a row goes through the layer * beneath it, the `SysMetadataRepository` delete, addressed by its stored * spelling, its name, its `package_id` and its checksum: the same transaction * and the same history tombstone (under the spelling the row carried), without @@ -51,22 +54,29 @@ import type { SecurityCatalogType } from '@objectstack/core'; /** The command's own name, the `actor` its deletions record. */ export const SECURITY_CATALOG_OVERLAYS_ACTOR = 'os migrate security-catalog-overlays'; -/** The stored spellings of each catalog type the boot's load folds together. */ -const STORED_TYPE_SPELLINGS: ReadonlyArray = [ +/** + * The stored spellings of each catalog type the boot's load folds together. + * [#35157] `capability` joins: an environment can store a capability since it + * became runtime-creatable, and the cold boot refuses one held under a name a + * configured package declares, so the remedy that refusal prescribes lists it. + */ +const STORED_TYPE_SPELLINGS: ReadonlyArray = [ ['position', 'position'], ['positions', 'position'], ['permission', 'permission'], ['permissions', 'permission'], + ['capability', 'capability'], + ['capabilities', 'capability'], ]; /** One listed row. */ export interface SecurityCatalogOverlayRow { /** The `sys_metadata` row id. */ readonly id: string; - /** The type as stored: `permission` / `position`, or a legacy plural. */ + /** The type as stored: `permission` / `position` / `capability`, or a plural spelling. */ readonly storedType: string; /** The catalog type the boot folds it to. */ - readonly catalogType: 'permission' | 'position'; + readonly catalogType: SecurityCatalogType; readonly name: string; /** The row's own package binding (`package_id`), `null` when it has none. */ readonly packageId: string | null; @@ -179,6 +189,20 @@ async function stillStored(engine: EngineLike, storedType: string, name: string, return new Set(ids.filter((id) => present.has(id))); } +/** + * Whether a row goes through the protocol's delete (module header, "The + * deletion"). [#35157] A `capability` row does not, in either spelling: its type + * takes no overlay (`supportsOverlay: false`), so that door reads the managed + * seal over the package's capability of the same name and refuses the removal + * (`refusePackagedBaseRemoval`), where a position or permission set, whose + * types merge at read, takes the #6960 carve-out. It goes through the + * repository beneath, as a legacy plural does, removed as the environment's + * own runtime-created item. + */ +function throughProtocolDelete(row: SecurityCatalogOverlayRow): boolean { + return row.storedType === row.catalogType && row.catalogType !== 'capability'; +} + function messageOf(error: unknown): string { return error instanceof Error ? error.message : String(error); } @@ -201,7 +225,7 @@ export async function deleteSecurityCatalogOverlayRows( // Canonical spellings: the protocol's delete, one call per row of a name. const canonical = new Map(); for (const row of rows) { - if (row.storedType !== row.catalogType) continue; + if (!throughProtocolDelete(row)) continue; const key = `${row.catalogType}|${row.name}`; canonical.set(key, [...(canonical.get(key) ?? []), row]); } @@ -245,7 +269,7 @@ export async function deleteSecurityCatalogOverlayRows( } // Legacy plural spellings: the repository beneath that door, row by row. - const plural = rows.filter((row) => row.storedType !== row.catalogType); + const plural = rows.filter((row) => !throughProtocolDelete(row)); if (plural.length > 0) { const { SysMetadataRepository } = await import('@objectstack/metadata-protocol'); const repository = new SysMetadataRepository({ engine: engine as never, orgLabel: 'env' }); @@ -261,7 +285,11 @@ export async function deleteSecurityCatalogOverlayRows( source: SECURITY_CATALOG_OVERLAYS_ACTOR, message: `Deleted the environment-wide ${row.storedType}/${row.name} row over a name ` + `${row.heldBy.join(', ')} holds (ADR-0048 N.3)`, - intent: 'override-artifact', + // [#35157] A capability row is the environment's own runtime-created + // item (its type takes no overlay), removed as one: the override + // intent reads the managed seal over the package's capability and + // refuses, as the protocol's door does. + intent: row.catalogType === 'capability' ? 'runtime-only' : 'override-artifact', state: 'active', packageId: row.packageId, }, diff --git a/packages/cloud-connection/src/marketplace-install-local-catalog-name-collision.test.ts b/packages/cloud-connection/src/marketplace-install-local-catalog-name-collision.test.ts index 01b8d304813..36804e26644 100644 --- a/packages/cloud-connection/src/marketplace-install-local-catalog-name-collision.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-catalog-name-collision.test.ts @@ -44,9 +44,9 @@ * holding package still installs. Measured before the fix: `200`, * `hotLoaded: false`, ledgered. * - * A capability is code-only (`allowRuntimeCreate: false`), so no environment - * save produces one; its case pins that the door judges the refusal, not the - * type. + * A capability is environment-creatable like the other two (an unmanaged copy + * carries its app's capabilities); its case pins that the door judges the + * refusal the same way for all three catalog types. */ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; diff --git a/packages/create-objectstack/src/templates/blank/README.md b/packages/create-objectstack/src/templates/blank/README.md index 7e457fc3770..d6cdce9623d 100644 --- a/packages/create-objectstack/src/templates/blank/README.md +++ b/packages/create-objectstack/src/templates/blank/README.md @@ -98,10 +98,10 @@ for OAuth, API keys, and which objects/actions become tools. - `note.test.ts` — the starter test `pnpm test` runs, configured by `vitest.config.ts` -## Connectors (default providers) +## Connectors (add a provider when you need one) -`objectstack.config.ts` wires the three **generic connector executors**, so you -can call an external system from a flow as pure metadata — no host code: +A **generic connector executor** lets you call an external system from a flow +as pure metadata — no host code: | Provider | Package | Use for | |:---|:---|:---| @@ -109,13 +109,19 @@ can call an external system from a flow as pure metadata — no host code: | `openapi` | `@objectstack/connector-openapi` | An API described by an OpenAPI document | | `mcp` | `@objectstack/connector-mcp` | A Model Context Protocol server | -Add a `connectors:` entry that names one of these `provider`s and the -`automation` capability materializes it into a live, dispatchable connector at -boot — see [Automation → Connectors](https://objectstack.ai/docs/automation/connectors) +The starter lists none of them in `plugins:`. A plugin is code, and an app +with code in `plugins:` installs only as a managed package — never as an +editable copy (`manifest.installModes: ['unmanaged']`, how a marketplace trial +template is installed), because a copy is made of metadata alone. So add a +provider when the app first needs one: install its package +(`pnpm add @objectstack/connector-rest`), list its executor in `plugins:` +(`new ConnectorRestPlugin()`), and add a `connectors:` entry that names its +`provider`. The `automation` capability materializes that entry into a live, +dispatchable connector at boot — see +[Automation → Connectors](https://objectstack.ai/docs/automation/connectors) for how that materialization works; a flow's `connector_action` node then -calls it. To add a brand connector (e.g. Slack), install its package and add -`new ConnectorSlackPlugin()` to `plugins:`; to drop a provider, remove its -plugin. +calls it. A brand connector (e.g. Slack) is added the same way, with its own +package and `new ConnectorSlackPlugin()`. > **Security — declarative MCP over stdio.** An `mcp` connector whose transport > spawns a local process (`stdio`) is denied by default, because the command diff --git a/packages/create-objectstack/src/templates/blank/objectstack.config.ts b/packages/create-objectstack/src/templates/blank/objectstack.config.ts index 76e0e29e1fd..a5b41ddebcf 100644 --- a/packages/create-objectstack/src/templates/blank/objectstack.config.ts +++ b/packages/create-objectstack/src/templates/blank/objectstack.config.ts @@ -1,7 +1,4 @@ import { defineStack } from '@objectstack/spec'; -import { ConnectorRestPlugin } from '@objectstack/connector-rest'; -import { ConnectorOpenApiPlugin } from '@objectstack/connector-openapi'; -import { ConnectorMcpPlugin } from '@objectstack/connector-mcp'; import * as objects from './src/objects'; import * as views from './src/views'; import * as actions from './src/actions'; @@ -42,10 +39,10 @@ export default defineStack({ }, // `automation` backs flow execution and materializes any declarative - // `connectors:` entry into a live, dispatchable connector at boot. The - // connector executors below register their provider factories with it — - // without `automation` loaded they have nowhere to register and boot fails, - // so keep this capability whenever `plugins:` lists a connector. + // `connectors:` entry into a live, dispatchable connector at boot. A + // connector executor you add to `plugins:` registers its provider factory + // with it — without `automation` loaded it has nowhere to register and boot + // fails, so keep this capability whenever `plugins:` lists a connector. // // `triggers` fires a flow that starts on a record change, the kind // `objectstack generate flow NAME` writes: without it this config stops @@ -53,19 +50,20 @@ export default defineStack({ // hold one. requires: ['automation', 'triggers'], - // Generic connector executors, default-present so you can add a `connectors:` - // entry naming `provider: 'rest' | 'openapi' | 'mcp'` and have it materialize - // with zero host code. Zero-arg = contribute the provider factory only. Brand - // connectors (Slack, …) stay marketplace/opt-in. + // No `plugins:` yet, on purpose. A plugin is code, and code is the one thing + // a template install cannot copy: an app with an entry in `plugins:` installs + // only as a managed package, never as an editable copy (`installModes: + // ['unmanaged']`, how a marketplace trial is installed). So the scaffold adds + // none until the app needs one. + // + // To call an external system from a flow as pure metadata, add a + // `connectors:` entry naming `provider: 'rest' | 'openapi' | 'mcp'`, install + // that provider's package (`@objectstack/connector-rest`, `-openapi`, `-mcp`) + // and list its executor here, e.g. `plugins: [new ConnectorRestPlugin()]`. // Security: a declarative `mcp` stdio transport spawns a local process from // metadata, so it is denied by default — opt in per host with // `new ConnectorMcpPlugin({ declarativeStdio: [''] })`. // Authoring guide: https://objectstack.ai/docs/automation/connectors - plugins: [ - new ConnectorRestPlugin(), - new ConnectorOpenApiPlugin(), - new ConnectorMcpPlugin(), - ], // Every directory `objectstack generate` writes into is wired here: its // index.ts exports what the directory holds, and each list below hands diff --git a/packages/create-objectstack/src/templates/blank/package.json b/packages/create-objectstack/src/templates/blank/package.json index 4b11b5112d6..56dfcde7de3 100644 --- a/packages/create-objectstack/src/templates/blank/package.json +++ b/packages/create-objectstack/src/templates/blank/package.json @@ -19,10 +19,7 @@ "dependencies": { "@objectstack/spec": "18.6.0", "@objectstack/runtime": "18.6.0", - "@objectstack/plugin-hono-server": "18.6.0", - "@objectstack/connector-rest": "18.6.0", - "@objectstack/connector-openapi": "18.6.0", - "@objectstack/connector-mcp": "18.6.0" + "@objectstack/plugin-hono-server": "18.6.0" }, "devDependencies": { "@objectstack/cli": "18.6.0", diff --git a/packages/metadata-protocol/src/package-namespace-rename.test.ts b/packages/metadata-protocol/src/package-namespace-rename.test.ts index 92bc4cf3573..dc651687e20 100644 --- a/packages/metadata-protocol/src/package-namespace-rename.test.ts +++ b/packages/metadata-protocol/src/package-namespace-rename.test.ts @@ -13,6 +13,7 @@ import { METADATA_ITEM_NAME_STORAGE_LIMIT, OBJECT_TABLE_IDENTIFIER_LIMIT, planNamespaceRename, + type NamespaceRenameItem, } from './package-namespace-rename.js'; const items = [ @@ -93,3 +94,187 @@ describe('planNamespaceRename — the one rename engine (#30794)', () => { }); }); }); + +describe('planNamespaceRename — a copied capability, and every grant and requirement of it (#35157)', () => { + // The shape an AI-built app writes: the package DECLARES its capability, + // a set GRANTS it, an action and an object REQUIRE it (ADR-0066 D1). + const app: NamespaceRenameItem[] = [ + { type: 'object', name: 'demoasset_asset', body: { + name: 'demoasset_asset', + requiredPermissions: { delete: ['demoasset.manage_assets'], read: ['view_reports'] }, + fields: {}, + } }, + { type: 'capability', name: 'demoasset.manage_assets', body: { name: 'demoasset.manage_assets', label: 'Manage assets', scope: 'org' } }, + { type: 'capability', name: 'demoasset_decide_scrap', body: { name: 'demoasset_decide_scrap', label: 'Decide scrap' } }, + { type: 'capability', name: 'audit_trail', body: { name: 'audit_trail', label: 'Audit trail' } }, + { type: 'permission', name: 'demoasset_manager', body: { + name: 'demoasset_manager', + objects: { demoasset_asset: { allowRead: true } }, + systemPermissions: ['demoasset.manage_assets', 'demoasset_decide_scrap', 'manage_users'], + } }, + { type: 'action', name: 'demoasset_scrap', body: { + name: 'demoasset_scrap', objectName: 'demoasset_asset', requiredPermissions: ['demoasset_decide_scrap'], + } }, + ]; + const plan = (targetNamespace: string, items = app) => planNamespaceRename({ + sourcePackageId: 'com.demo.asset', sourceNamespace: 'demoasset', targetNamespace, items, retryVerb: 'install', + }); + + it('a capability the package names with its prefix takes the target prefix, in either separator', () => { + const rename = plan('trial1'); + expect(rename.copyName('capability', 'demoasset.manage_assets')).toBe('trial1.manage_assets'); + expect(rename.copyName('capabilities', 'demoasset.manage_assets')).toBe('trial1.manage_assets'); + expect(rename.copyName('capability', 'demoasset_decide_scrap')).toBe('trial1_decide_scrap'); + expect(rename.rewrite('capability', 'demoasset.manage_assets', app[1]!.body)) + .toEqual({ item: { name: 'trial1.manage_assets', label: 'Manage assets', scope: 'org' } }); + }); + + it('every grant and requirement of a renamed capability follows it — and nothing else moves', () => { + const rename = plan('trial1'); + const set = rename.rewrite('permission', 'demoasset_manager', app[4]!.body); + // The platform capability the set also grants is not the package's, so it keeps its name. + expect((set as { item: any }).item.systemPermissions).toEqual(['trial1.manage_assets', 'trial1_decide_scrap', 'manage_users']); + const action = rename.rewrite('action', 'demoasset_scrap', app[5]!.body); + expect((action as { item: any }).item.requiredPermissions).toEqual(['trial1_decide_scrap']); + // An object's per-operation map follows too; `view_reports` (a platform name) does not move. + const object = rename.rewrite('object', 'demoasset_asset', app[0]!.body); + expect((object as { item: any }).item.requiredPermissions) + .toEqual({ delete: ['trial1.manage_assets'], read: ['view_reports'] }); + }); + + it('a capability declared WITHOUT the source prefix keeps its name — the save door refuses a second holder', () => { + const rename = plan('trial1'); + expect(rename.copyName('capability', 'audit_trail')).toBe('audit_trail'); + }); + + it('CONTROL: a copy that keeps the source namespace renames no capability', () => { + const rename = plan('demoasset'); + expect(rename.copyName('capability', 'demoasset.manage_assets')).toBe('demoasset.manage_assets'); + const set = rename.rewrite('permission', 'demoasset_manager', app[4]!.body); + expect((set as { item: any }).item.systemPermissions).toEqual(['demoasset.manage_assets', 'demoasset_decide_scrap', 'manage_users']); + }); + + it('a copy name another capability of the package declares is refused at its own name — two gates never merge', () => { + const rename = plan('trial1', [ + ...app, + { type: 'capability', name: 'trial1.manage_assets', body: { name: 'trial1.manage_assets' } }, + ]); + const refused = rename.rewrite('capability', 'demoasset.manage_assets', app[1]!.body); + expect(refused).toEqual({ refusal: expect.stringContaining("Capability 'demoasset.manage_assets' is not copied") }); + expect((refused as { refusal: string }).refusal).toMatch(/then install again\.$/); + }); + + it('a `hasCapability` predicate follows the renamed capability, as the action it pairs with does', () => { + const rename = plan('trial1'); + const page = rename.rewrite('page', 'demoasset_asset_page', { + name: 'demoasset_asset_page', + visibleWhen: "current_user.hasCapability('demoasset_decide_scrap') && record.demoasset_asset != ''", + hint: 'current_user.hasCapability("manage_users")', + }); + expect((page as { item: any }).item.visibleWhen) + .toBe("current_user.hasCapability('trial1_decide_scrap') && record.trial1_asset != ''"); + // A name the package does not declare keeps its name. + expect((page as { item: any }).item.hint).toBe('current_user.hasCapability("manage_users")'); + }); + + it('a capability named after a renamed object is ONE name in the copy: declaration, grant, requirement and predicate agree', () => { + const items: NamespaceRenameItem[] = [ + { type: 'object', name: 'crm_invoice', body: { name: 'crm_invoice', fields: {} } }, + { type: 'capability', name: 'crm.crm_invoice.void', body: { name: 'crm.crm_invoice.void', label: 'Void invoices' } }, + { type: 'permission', name: 'crm_billing', body: { name: 'crm_billing', systemPermissions: ['crm.crm_invoice.void'] } }, + { type: 'action', name: 'crm_void', body: { + name: 'crm_void', objectName: 'crm_invoice', requiredPermissions: ['crm.crm_invoice.void'], + visible: "current_user.hasCapability('crm.crm_invoice.void')", + } }, + ]; + const rename = planNamespaceRename({ + sourcePackageId: 'com.demo.crm', sourceNamespace: 'crm', targetNamespace: 'shop', items, retryVerb: 'install', + }); + const declared = (rename.rewrite('capability', 'crm.crm_invoice.void', items[1]!.body) as { item: any }).item.name; + expect(declared).toBe('shop.crm_invoice.void'); + const set = (rename.rewrite('permission', 'crm_billing', items[2]!.body) as { item: any }).item; + expect(set.systemPermissions).toEqual([declared]); + const action = (rename.rewrite('action', 'crm_void', items[3]!.body) as { item: any }).item; + expect(action.requiredPermissions).toEqual([declared]); + expect(action.visible).toBe(`current_user.hasCapability('${declared}')`); + // CONTROL: the object reference outside the capability places still follows the object. + expect(action.objectName).toBe('shop_invoice'); + }); + + it('a token the package does NOT declare still follows a renamed object, in grant, requirement and predicate alike', () => { + const items: NamespaceRenameItem[] = [ + { type: 'object', name: 'crm_invoice', body: { name: 'crm_invoice', fields: {} } }, + { type: 'permission', name: 'crm_billing', body: { name: 'crm_billing', systemPermissions: ['crm_invoice.void', 'manage_users'] } }, + { type: 'action', name: 'crm_void', body: { + name: 'crm_void', objectName: 'crm_invoice', requiredPermissions: ['crm_invoice.void'], + visible: "current_user.hasCapability('crm_invoice.void')", + } }, + ]; + const rename = planNamespaceRename({ + sourcePackageId: 'com.demo.crm', sourceNamespace: 'crm', targetNamespace: 'shop', items, + retryVerb: 'duplicate', sourceStaysInstalled: true, + }); + const set = (rename.rewrite('permission', 'crm_billing', items[1]!.body) as { item: any }).item; + expect(set.systemPermissions).toEqual(['shop_invoice.void', 'manage_users']); + const action = (rename.rewrite('action', 'crm_void', items[2]!.body) as { item: any }).item; + expect(action.requiredPermissions).toEqual(['shop_invoice.void']); + expect(action.visible).toBe("current_user.hasCapability('shop_invoice.void')"); + }); + + describe('when the source stays installed beside the copy (duplicatePackage)', () => { + const duplicate = (items = app) => planNamespaceRename({ + sourcePackageId: 'com.demo.asset', sourceNamespace: 'demoasset', targetNamespace: 'trial1', items, + retryVerb: 'duplicate', sourceStaysInstalled: true, + }); + + it('a declared capability the copy cannot rename is refused, and so is every item that names it — no shared gate', () => { + const items: NamespaceRenameItem[] = [ + ...app, + { type: 'permission', name: 'demoasset_auditor', body: { name: 'demoasset_auditor', systemPermissions: ['audit_trail'] } }, + { type: 'page', name: 'demoasset_audit_page', body: { + name: 'demoasset_audit_page', visibleWhen: "current_user.hasCapability('audit_trail')", + } }, + ]; + const rename = duplicate(items); + const capability = rename.rewrite('capability', 'audit_trail', { name: 'audit_trail' }); + expect((capability as { refusal: string }).refusal).toMatch( + /^Capability 'audit_trail' is not copied: it carries no 'demoasset\.' or 'demoasset_' prefix .* share one gate\. .*then duplicate again\.$/, + ); + const set = rename.rewrite('permission', 'demoasset_auditor', items[6]!.body); + expect((set as { refusal: string }).refusal).toMatch( + /^Permission set 'demoasset_auditor' is not copied: it names capability 'audit_trail', which package 'com\.demo\.asset' declares/, + ); + const page = rename.rewrite('page', 'demoasset_audit_page', items[7]!.body); + expect((page as { refusal: string }).refusal).toMatch(/it names capability 'audit_trail'/); + }); + + it('a capability whose copy name the package already declares refuses the items that name it too', () => { + const rename = duplicate([ + ...app, + { type: 'capability', name: 'trial1.manage_assets', body: { name: 'trial1.manage_assets' } }, + ]); + const set = rename.rewrite('permission', 'demoasset_manager', app[4]!.body); + expect((set as { refusal: string }).refusal).toMatch( + /it names capability 'demoasset\.manage_assets'.*a capability the package already declares/, + ); + }); + + it('CONTROL: renamed capabilities and names the package does not declare copy as before', () => { + const rename = duplicate(app.filter((item) => item.name !== 'audit_trail')); + const set = rename.rewrite('permission', 'demoasset_manager', app[4]!.body); + expect((set as { item: any }).item.systemPermissions).toEqual(['trial1.manage_assets', 'trial1_decide_scrap', 'manage_users']); + }); + + it('CONTROL: the unmanaged import (source not installed) keeps an unprefixed capability and the items naming it', () => { + const items: NamespaceRenameItem[] = [ + ...app, + { type: 'permission', name: 'demoasset_auditor', body: { name: 'demoasset_auditor', systemPermissions: ['audit_trail'] } }, + ]; + const rename = plan('trial1', items); + expect(rename.rewrite('capability', 'audit_trail', { name: 'audit_trail' })).toEqual({ item: { name: 'audit_trail' } }); + expect((rename.rewrite('permission', 'demoasset_auditor', items[6]!.body) as { item: any }).item.systemPermissions) + .toEqual(['audit_trail']); + }); + }); +}); + diff --git a/packages/metadata-protocol/src/package-namespace-rename.ts b/packages/metadata-protocol/src/package-namespace-rename.ts index 06314a02044..36bbd8e23b2 100644 --- a/packages/metadata-protocol/src/package-namespace-rename.ts +++ b/packages/metadata-protocol/src/package-namespace-rename.ts @@ -58,6 +58,15 @@ export interface NamespaceRenameInput { items: ReadonlyArray; /** The door's verb, for the remedy every refusal ends with ("then duplicate again"). */ retryVerb: 'duplicate' | 'install'; + /** + * [#35157] The source package stays installed beside the copy, in the same + * deployment — true for `duplicatePackage`, whose source is a stored base. + * A capability the copy cannot give a name of its own is then one gate + * shared by the copy and its source, so every item naming one is refused + * (see {@link planNamespaceRename}). Absent for the unmanaged import, whose + * source is a package body it is handed. + */ + sourceStaysInstalled?: boolean; } /** One body, re-namespaced — or the reason it cannot be. */ @@ -124,6 +133,34 @@ function isViewType(type: string): boolean { return (PLURAL_TO_SINGULAR[String(type)] ?? String(type)) === 'view'; } +/** A `capability` row, in either spelling of the type. */ +function isCapabilityType(type: string): boolean { + return (PLURAL_TO_SINGULAR[String(type)] ?? String(type)) === 'capability'; +} + +/** + * [#35157] The keys a body names capabilities under: a permission set GRANTS + * them (`systemPermissions`) and a resource REQUIRES them + * (`requiredPermissions` — on an object, a field, an app and its navigation, an + * action, a flow, a list view, a dashboard, a record block; a `string[]`, or on + * an object a `{ read, create, update, delete }` map of them). Their values are + * capability names and nothing else, so each entry goes to the capability + * rename, never to the generic walk: a name the package declares takes the + * capability rename alone, and any other name takes the object-name pass, so + * an undeclared token spelled with a renamed object's name follows the object. + */ +const CAPABILITY_REFERENCE_KEYS: ReadonlySet = new Set(['systemPermissions', 'requiredPermissions']); + +/** + * [#35157] The third place a body names a capability: a predicate that hides a + * component unless the viewer holds one, `current_user.hasCapability('')` + * (`PageComponentSchema.visibleWhen`, `packages/spec/src/ui/page.zod.ts`, which + * teaches writing it "with the name the gated action's `requiredPermissions` + * declares"). A quoted literal argument only; any other argument is an + * expression this engine does not evaluate, and it is left as written. + */ +const HAS_CAPABILITY_CALL = /(\bhasCapability\(\s*)(['"])([^'"\\]*)\2/g; + /** A `view` row whose name is qualified `.` (`ViewItemNameSchema`). */ function isQualifiedViewName(type: string, name: unknown): name is string { return isViewType(type) && typeof name === 'string' && name.includes('.'); @@ -312,6 +349,107 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam // one-to-one, so a meeting is always a renamed name and a name this copy // does not rename; an element the source itself repeats is copied as // stored. + // [#35157] ⭐ A COPIED CAPABILITY TAKES THE TARGET NAMESPACE, AND EVERY + // GRANT AND REQUIREMENT OF IT IN THE COPY FOLLOWS. A capability's name is + // ONE per deployment — the runtime matches a grant to a requirement by + // string, whichever package declared it (`missingCapabilities`, + // `@objectstack/core`) — so two copies of one app that kept the source's + // capability names would share one gate: a holder of either copy's set + // would pass both copies' actions. The name a package gives its own + // capability carries its namespace, `.` or `_`; the + // copy swaps that prefix for the target's, as an object name's prefix is + // swapped, and rewrites the name wherever the copy's bodies grant or + // require it ({@link CAPABILITY_REFERENCE_KEYS}). A capability the + // package declares without its prefix keeps its name — no rule says what + // its prefix is. A name the package does NOT declare (a platform + // capability, another package's) never takes the capability rename: it + // takes the object-name pass, as every string did before #35157, so it + // keeps its name unless it is spelled with a renamed object's name, and + // then it follows the object. + // + // The name is rewritten in the three places a body names a capability — + // the two keys above, and a `hasCapability('')` predicate + // ({@link HAS_CAPABILITY_CALL}) — and there the object-name pass below + // never touches a name the package declares, so a capability named after + // a renamed object (`crm.crm_invoice.void`) is ONE name in the copy, the + // declaration's, never a second one the object pass would invent. A name + // the package does not declare still takes the object-name pass there. + // + // ⛔ A SHARED GATE IS REFUSED (`sourceStaysInstalled`). When the source + // stays installed beside the copy (`duplicatePackage`), a declared + // capability the copy does not rename — it carries no source prefix, or + // its copy name is refused below — is held by the source already: the save + // door refuses the copy's declaration, and an item of the copy that grants + // or requires it would pass on the SOURCE's gate. So every such item is + // refused at its own name, with the rename that clears it. The unmanaged + // import keeps such a name: its source is not installed, and when a + // package does hold the name the save door refuses the declaration and + // the import, all or nothing, refuses with it. + // + // ⛔ REFUSED, NEVER RE-INVENTED: a copy name another capability of the + // package already holds would merge two gates into one, so that + // capability is refused at its own name. + const capabilityNames = new Set( + items.filter((item) => isCapabilityType(item?.type) && typeof item.name === 'string').map((item) => item.name), + ); + const capabilityRenames = new Map(); + const refusedCapabilities = new Map(); + if (sourceNs && targetNs !== sourceNs) { + for (const name of capabilityNames) { + const sep = name.startsWith(`${sourceNs}.`) ? '.' : name.startsWith(`${sourceNs}_`) ? '_' : undefined; + if (sep === undefined) continue; + const nn = `${targetNs}${sep}${name.slice(sourceNs.length + 1)}`; + if (capabilityNames.has(nn)) { + refusedCapabilities.set( + name, + `Capability '${name}' is not copied: its copy name in namespace '${targetNs}' is '${nn}', a ` + + `capability package '${sourcePackageId}' already declares, so the copy would merge two ` + + `gates into one. Rename '${name}' or '${nn}' on the source, ${again}.`, + ); + continue; + } + capabilityRenames.set(name, nn); + } + } + // Why a declared capability keeps the source's name, for each one that does. + const sharedCapabilities = new Map(); + if (input.sourceStaysInstalled) { + for (const name of capabilityNames) { + if (capabilityRenames.has(name)) continue; + sharedCapabilities.set(name, refusedCapabilities.has(name) + ? `its copy name in namespace '${targetNs}' is a capability the package already declares` + : !sourceNs + ? 'the package declares no namespace, so no prefix marks the name as the package\'s' + : targetNs !== sourceNs + ? `it carries no '${sourceNs}.' or '${sourceNs}_' prefix to swap for '${targetNs}'` + : 'the copy keeps the source\'s namespace'); + } + } + // The capability names one `rewrite` call met, for the shared-gate refusal. + let capabilitiesNamed: Set | undefined; + // A name the package DECLARES takes the capability rename alone, never the + // object-name pass, so its declaration and every reference agree. Any + // other name is the object-name pass's, as it was before #35157: an + // undeclared token spelled with a renamed object's name + // (`crm_invoice.void`) follows the object in the grant, the requirement + // and the predicate alike, so each copy keeps a gate of its own. + const renameCapability = (name: string): string => { + capabilitiesNamed?.add(name); + if (capabilityNames.has(name)) return capabilityRenames.get(name) ?? name; + return re ? name.replace(re, (m) => renameMap.get(m) ?? m) : name; + }; + const renameCapabilityList = (list: unknown): unknown => + Array.isArray(list) + ? list.map((entry) => (typeof entry === 'string' ? renameCapability(entry) : entry)) + : list; + const rewriteCapabilityValue = (val: unknown): unknown => + Array.isArray(val) + ? renameCapabilityList(val) + : val && typeof val === 'object' + ? Object.fromEntries(Object.entries(val as Record) + .map(([op, list]) => [op, renameCapabilityList(list)])) + : val; + const objectReferenceProperties = new Set( (REFERENCE_SITES.byTarget.get('object') ?? []).map((site) => site.property), ); @@ -322,7 +460,18 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam if (whole !== undefined) return whole; const viewItem = viewItemRenames.get(v); if (viewItem !== undefined) return viewItem; - return re ? v.replace(re, (m) => renameMap.get(m) ?? m) : v; + const objectPass = (text: string): string => (re ? text.replace(re, (m) => renameMap.get(m) ?? m) : text); + // A `hasCapability('')` argument is a capability name and + // goes to `renameCapability`: a name the package declares takes the + // capability rename alone, never the object pass; any other name + // takes the object pass there. + let out = ''; + let last = 0; + for (const m of v.matchAll(HAS_CAPABILITY_CALL)) { + out += objectPass(v.slice(last, m.index)) + m[1] + m[2] + renameCapability(m[3]!) + m[2]; + last = m.index! + m[0].length; + } + return last === 0 ? objectPass(v) : out + objectPass(v.slice(last)); } if (Array.isArray(v)) { const out = v.map((element, i) => deepRewrite(element, collisions, atReference, `${at}[${i}]`)); @@ -350,6 +499,10 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam collisions.push({ at, shape: 'key', moved: key === k ? other : k, met: key }); } from.set(key, k); + if (CAPABILITY_REFERENCE_KEYS.has(k)) { + o[key] = rewriteCapabilityValue(val); + continue; + } const entry = deepRewrite( val, collisions, objectReferenceProperties.has(k) || (atReference && k === 'name'), @@ -450,6 +603,8 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam const copyName = (type: string, name: string): string => type === 'object' ? (renameMap.get(name) ?? name) + : isCapabilityType(type) + ? (capabilityRenames.get(name) ?? name) : isQualifiedViewName(type, name) ? qualifiedViewCopyName(name) : isViewType(type) && renameMap.has(name) @@ -493,8 +648,31 @@ export function planNamespaceRename(input: NamespaceRenameInput): NamespaceRenam }, rewrite(type, name, item) { const singular = PLURAL_TO_SINGULAR[String(type)] ?? String(type); + const capabilityRefusal = singular === 'capability' ? refusedCapabilities.get(name) : undefined; + if (capabilityRefusal !== undefined) return { refusal: capabilityRefusal }; + const shared = singular === 'capability' ? sharedCapabilities.get(name) : undefined; + if (shared !== undefined) { + return { + refusal: `Capability '${name}' is not copied: ${shared}, so the copy would declare the name ` + + `package '${sourcePackageId}' still declares, and the two would share one gate. ` + + `Rename '${name}' on the source to a '${sourceNs || ''}.' name, ${again}.`, + }; + } const collisions: ReferenceCollision[] = []; + // Every call starts its own count, so a throw from an earlier one leaves nothing behind. + const named = new Set(); + capabilitiesNamed = named; const rewritten = deepRewrite(item, collisions); + capabilitiesNamed = undefined; + const sharedNamed = [...named].find((cap) => sharedCapabilities.has(cap)); + if (sharedNamed !== undefined) { + return { + refusal: `${nounOf(type)} '${name}' is not copied: it names capability '${sharedNamed}', which ` + + `package '${sourcePackageId}' declares and this copy cannot rename (${sharedCapabilities.get(sharedNamed)}), ` + + 'so the copy would pass on the source\'s gate. ' + + `Rename '${sharedNamed}' on the source to a '${sourceNs || ''}.' name, ${again}.`, + }; + } if (collisions.length > 0) { const more = collisions.length - 1; return { diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index 837651c7769..7cf034bec00 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -330,6 +330,8 @@ export class ProtocolPackageCommitsFacet { return { type: row?.type, name: row?.name, body }; }), retryVerb: 'duplicate', + // [#35157] The source base stays installed beside its duplicate. + sourceStaysInstalled: true, }); // [ADR-0146 D10, #28564] ⭐ THE `__c` RESERVATION, JUDGED AGAINST THE diff --git a/packages/metadata-protocol/src/protocol-save-door-refusals.ts b/packages/metadata-protocol/src/protocol-save-door-refusals.ts index ad78c37b85d..7ba79b6bbc9 100644 --- a/packages/metadata-protocol/src/protocol-save-door-refusals.ts +++ b/packages/metadata-protocol/src/protocol-save-door-refusals.ts @@ -65,6 +65,7 @@ import { isFederatedObject, PackageScopedNameRefusedError, permissionSetHoldersM import { itemDiscriminator } from '@objectstack/metadata-core'; import { externalBindingDatasourceRefusal, resolveInjectedSystemColumns, SeedSchema } from '@objectstack/spec/data'; import { METADATA_ITEM_NAME_PATTERN } from '@objectstack/spec/shared'; +import { PLATFORM_CAPABILITY_NAMES } from '@objectstack/spec/security'; import { defaultRecordPageObject } from '@objectstack/spec/ui'; import { MetadataProtectionFields, findNamespaceObjectNameClashes, validateObjectNamespacePrefix, type NamespaceHolder } from '@objectstack/spec/kernel'; // [#29898] The one walk of which picklists an object body's fields name — the @@ -330,7 +331,7 @@ export async function defaultRecordPageSaveRefusal( * Not caught: the reading is in memory, and a throw from it is a fault to * surface, never "nobody holds the name". */ -function registryPackageHoldersOf(registry: unknown, name: string): readonly string[] { +function registryPackageHoldersOf(registry: unknown, name: string, catalogType: 'permission' | 'capability' = 'permission'): readonly string[] { const read = (registry as { packageHeldSecurityCatalogNames?: unknown } | null | undefined) ?.packageHeldSecurityCatalogNames; if (typeof read !== 'function') return []; @@ -338,7 +339,7 @@ function registryPackageHoldersOf(registry: unknown, name: string): readonly str if (!Array.isArray(held)) return []; const holders = new Set(); for (const entry of held as Array<{ catalogType?: unknown; name?: unknown; packageIds?: unknown } | null>) { - if (entry?.catalogType !== 'permission' || entry.name !== name || !Array.isArray(entry.packageIds)) continue; + if (entry?.catalogType !== catalogType || entry.name !== name || !Array.isArray(entry.packageIds)) continue; for (const id of entry.packageIds) if (typeof id === 'string' && id !== '') holders.add(id); } return [...holders]; @@ -348,6 +349,15 @@ function registryPackageHoldersOf(registry: unknown, name: string): readonly str * The body of `ObjectStackProtocolImplementation#permissionSetNameCollisionRefusal`; * the method's docblock there is its contract. * + * [#35157] It judges a `capability` too, by the same two holder readings and + * the same envelope, with two differences the type itself makes: a + * capability's name is ONE per deployment (a grant and a requirement match + * it by string, whichever package declared it), so every holder meets every + * other; and a curated platform capability's name is refused outright, before + * any read (ADR-0090 D5 revision, boundary 1: the platform floor is + * absolute), because a declaration under it would re-declare a platform + * power's `scope`. + * * A `permission` set's name was its identity across the whole deployment (Q4 = * A on #15196, record 6050490870). [ADR-0150 D2/D9, #31698] It is now one name * per NAMESPACE: a set is `(package, name)`, a grant carries its package @@ -416,7 +426,26 @@ export async function permissionSetNameCollisionRefusal( owner: string | null | undefined, verb: 'save' | 'publish' | 'restore', ): Promise<(Error & { code: 'NAMESPACE_CONFLICT'; status: 422 }) | undefined> { - if (singularType !== 'permission') return undefined; + if (singularType !== 'permission' && singularType !== 'capability') return undefined; + const capability = singularType === 'capability'; + // [#35157] A capability is ONE name per deployment: a grant and a + // requirement match it by string, whichever package declared it, so no + // namespace scopes it. And the platform floor is absolute (ADR-0090 D5 + // revision, boundary 1): a curated platform capability's name is the + // platform's, and an environment declaration under it would re-declare a + // platform power's `scope` — the input to who may administer the sets + // that grant it (ADR-0090 D12 (c)). Refused before any read. + if (capability && PLATFORM_CAPABILITY_NAMES.has(name)) { + const err = new Error( + `Security catalog name conflict: this environment cannot ${verb} the capability "${name}" — it is a ` + + `platform capability. Nothing was ${verb === 'publish' ? 'published' : 'written'}. Name your capability ` + + 'with your own module prefix (`.`) and grant that one instead. A platform capability is ' + + 'declared by the platform alone, so no package or environment re-declares its scope.', + ) as Error & { code: 'NAMESPACE_CONFLICT'; status: 422 }; + err.code = 'NAMESPACE_CONFLICT'; + err.status = 422; + return err; + } let records: any[] = []; try { @@ -437,7 +466,7 @@ export async function permissionSetNameCollisionRefusal( const residueOf = storedUnbound && storedPackages.size === 1 ? [...storedPackages][0] : undefined; const holders = new Set(storedPackages); - for (const packageId of registryPackageHoldersOf(this.engine?.registry, name)) holders.add(packageId); + for (const packageId of registryPackageHoldersOf(this.engine?.registry, name, singularType)) holders.add(packageId); if (storedUnbound && residueOf === undefined) holders.add(null); const written = typeof owner === 'string' && owner !== '' ? owner : residueOf ?? null; @@ -455,7 +484,7 @@ export async function permissionSetNameCollisionRefusal( return typeof namespace === 'string' && namespace !== '' ? namespace : undefined; }; const meets = (holder: string | null): boolean => - holder === null || written === null + holder === null || written === null || capability || permissionSetHoldersMeet(namespaceOf(written), namespaceOf(holder), name); const foreign = [...holders] .filter((holder) => holder !== written && meets(holder)) @@ -470,9 +499,24 @@ export async function permissionSetNameCollisionRefusal( // the metadata door); never an edit inside another package. A set a // package ships leaves the writer only the rename. const deletable = foreign.filter((holder) => holder === null || storedPackages.has(holder)); + const noun = capability ? 'capability' : 'set'; const releases = deletable - .map((holder) => (holder === null ? 'delete the environment catalog\'s set' : `delete the set package "${holder}" stores`)) + .map((holder) => (holder === null ? `delete the environment catalog's ${noun}` : `delete the ${noun} package "${holder}" stores`)) .join(', or '); + if (capability) { + const remedy = verb === 'restore' + ? `Restore it once the name is free${releases === '' ? '' : ` (${releases} first)`}, or save this version's body as a capability of a name no other holder holds.` + : `Rename this capability to a name no other holder holds (prefix it with your own module prefix)${releases === '' ? '' : `, or ${releases} first`}.`; + const err = new Error( + `Security catalog name conflict: ${writer} cannot ${verb} the capability "${name}" — it is already held by ` + + `${foreign.map(holderPhrase).join(' and ')}. Nothing was ${verb === 'publish' ? 'published' : 'written'}. ${remedy} ` + + 'A capability holds one name per deployment: a grant and a requirement match it by name, whichever ' + + 'package declared it.', + ) as Error & { code: 'NAMESPACE_CONFLICT'; status: 422 }; + err.code = 'NAMESPACE_CONFLICT'; + err.status = 422; + return err; + } const remedy = verb === 'restore' ? (releases === '' ? 'Save this version\'s body as a set of a name no other holder holds.' diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 1d47fb7d4f9..c0347df1bc1 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -1392,7 +1392,10 @@ export class ProtocolSaveFacet { // through the console's plain `?mode=draft` save. An ambiguous // address has no row to land in, and is refused with the refusal // the repository answers it with. - if (singularType === 'permission') { + // [#35157] …and a `capability` the same way: one name, one + // holder, and never a platform capability's name — the same + // predicate, judged against the same landing binding. + if (singularType === 'permission' || singularType === 'capability') { let landsIn: string | null = null; if (typeof request.packageId === 'string' && request.packageId !== '') { landsIn = request.packageId; diff --git a/packages/metadata-protocol/src/protocol.capability-write-door.test.ts b/packages/metadata-protocol/src/protocol.capability-write-door.test.ts index 5c9f7777484..ac0a18d7b23 100644 --- a/packages/metadata-protocol/src/protocol.capability-write-door.test.ts +++ b/packages/metadata-protocol/src/protocol.capability-write-door.test.ts @@ -25,63 +25,38 @@ * textarea. * * --------------------------------------------------------------------------- - * The three doors, and which one each case is about + * #35157 — runtime-creatable, overlay-closed, one name per holder * --------------------------------------------------------------------------- - * `capability` is CODE-ONLY (`allowRuntimeCreate: false` + - * `allowEnvironmentOverlay: false`, ADR-0066 D1 — packages DEFINE capabilities). That - * makes the ORDER inside `saveMetaItem` load-bearing, and this file pins the - * order rather than asserting a 422 that the real code never reaches: + * `capability` is no longer code-only: `allowRuntimeCreate: true` with + * `allowEnvironmentOverlay: false`, because an `unmanaged` install (ADR-0131 + * D6) copies an app's capabilities into environment rows through this door, + * and an app that gates its own actions could not be copied without them. + * What the door now pins, in the order `saveMetaItem` meets them: * - * 1. DEFAULT — #5086's code-only refusal fires FIRST: 403 `not_creatable`, - * on every kernel, before any schema is consulted. Nothing is stored. - * 2. ESCAPE HATCH — with `OS_METADATA_WRITABLE=capability` (ADR-0005's one - * documented operator door) the write reaches the spec-conformance check, - * and THAT is where the new schema earns its keep: 422 `invalid_metadata` - * instead of storing the body verbatim. - * 3. PACKAGE DECLARATION — untouched. `AppPlugin` registers stack - * `capabilities[]` through `registerInMemory` and the filesystem loader - * globs `filePatterns`; neither goes through `saveMetaItem`, so - * `bootstrapDeclaredCapabilities` still seeds `sys_capability` exactly as - * before. Asserted here as the "legal payload still gets in" half. + * 1. SCHEMA — every write is judged by `CapabilityDeclarationSchema`: a + * garbage body is 422 `invalid_metadata` and nothing is stored, with no + * operator hatch needed to reach the check. A valid one saves. + * 2. PLATFORM FLOOR — a curated platform capability's name is refused + * `NAMESPACE_CONFLICT` / 422 before any read: a declaration under it + * would re-declare a platform power's `scope` (ADR-0090 D5 revision, + * boundary 1; D12 (c)). + * 3. ONE NAME, ONE HOLDER — a name a package holds, or the environment or + * another package stores, is refused the same way: a grant and a + * requirement match a capability by name across the whole deployment. + * 4. PACKAGE DECLARATION — untouched: `AppPlugin` registers stack + * `capabilities[]` through `registerInMemory`, never this door. + * + * #5961's reverse verification (below) measured the schema binding as a + * genuine second line of defence; with the code-only gate gone it is the first. * * --------------------------------------------------------------------------- - * Reverse verification, direction predicted BEFORE running + * Reverse verification of #5961, as recorded then * --------------------------------------------------------------------------- - * Two limbs, two predictions, both ordinary red. Each limb was rebuilt before - * measuring — this package resolves `@objectstack/spec` from `dist`, so an - * unbuilt limb measures the OLD spec and reports a false green (it did, once). - * - * • **Limb 1 — delete the `capability` row from - * `DEFAULT_METADATA_TYPE_REGISTRY`.** Predicted: `isRuntimeCreateAllowed` - * falls into its "no static entry ⇒ synthesised as creatable" branch, so - * the refusal cases RESOLVE instead of rejecting and `/meta/types` shows - * the synthesised descriptor again. Measured: 7 red / 3 green, with the - * refusals failing as `promise resolved "{ success: true, …(4) }" instead - * of rejecting` — the open door, reproduced on demand. - * - * One case failed in a SHARPER shape than predicted, and it is worth - * writing down rather than smoothing over: the first case (garbage body, - * no hatch) did not resolve — it turned into `422 invalid_metadata`, - * because with the registry row gone the write sails past the code-only - * gate and reaches the schema check, which is still bound and still - * rejects. So the two limbs are not merely additive: the schema binding is - * a genuine second line of defence behind the registry row, and only a - * body that is BOTH well-formed and unauthorised (case 2) isolates the row - * on its own. * - * • **Limb 2 — delete `capability: CapabilityDeclarationSchema` from - * `BUILTIN_METADATA_TYPE_SCHEMAS`.** Predicted: `resolveOverlaySchema` - * answers null, the escape-hatch case SAVES the garbage body instead of - * 422-ing, and `/meta/types` emits an entry with no schema. Measured: - * 3 red / 7 green, exactly those three, `promise resolved "{ success: - * true, …(4) }" instead of rejecting` and `expected undefined to be - * defined`. - * - * The green halves are not slack. A "fix" that made `capability` unwritable - * under every condition would pass every refusal case here and fail the - * behind-the-hatch save; a harness that could not save anything at all would - * pass the refusals for the wrong reason. Both are excluded by cases that stay - * green in the fixed tree and move in only one of the two limbs. + * • Deleting the `capability` registry row made `isRuntimeCreateAllowed` + * answer "creatable" and the refusals resolve; deleting the schema binding + * made a garbage body save. Only the second half still applies to the + * door as it stands, and case 1 below pins it. * * Harness: the real write path over a stub engine — the same shape as * `protocol.flow-org-override-closed.test.ts`. The gates run INSIDE @@ -95,6 +70,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel'; import { ObjectStackProtocolImplementation } from './protocol.js'; +// The served save reaches a dynamic `import('@objectstack/lint')` (metadata diagnostics): pay its load at collection. +import '@objectstack/lint'; interface Row { id: string; @@ -105,7 +82,10 @@ interface Row { metadata: string; } -function makeStubEngine(registeredTypes: string[] = []) { +function makeStubEngine( + registeredTypes: string[] = [], + packageHeld: Array<{ catalogType: string; name: string; packageIds: string[] }> = [], +) { const rows = new Map(); let nextId = 0; const keyOf = (w: Record) => @@ -121,7 +101,15 @@ function makeStubEngine(registeredTypes: string[] = []) { } return null; }, - async find() { return []; }, + async find(_t: string, opts?: { where?: Record; limit?: number }) { + if (_t !== 'sys_metadata') return []; + const where = opts?.where ?? {}; + // Every scalar condition is an equality on that column; an operator + // object is not modelled by this double and does not narrow. + const matched = [...rows.values()].filter((row) => Object.entries(where).every(([key, value]) => + value === undefined || (typeof value === 'object' && value !== null) || (row as unknown as Record)[key] === value)); + return typeof opts?.limit === 'number' ? matched.slice(0, opts.limit) : matched; + }, async insert(_t: string, data: Record) { if (_t !== 'sys_metadata') return { id: 'side_effect_skip' }; nextId += 1; @@ -144,13 +132,20 @@ function makeStubEngine(registeredTypes: string[] = []) { getItem: () => undefined, getArtifactItem: () => undefined, getRegisteredTypes: () => registeredTypes, + // The registry's own package-held reading (`@objectstack/objectql` + // `packageHeldSecurityCatalogNames`), which the save door asks. + packageHeldSecurityCatalogNames: () => packageHeld, }, }; return { engine, rows }; } -function makeProtocol(registeredTypes?: string[], environmentId?: string) { - const { engine, rows } = makeStubEngine(registeredTypes); +function makeProtocol( + registeredTypes?: string[], + environmentId?: string, + packageHeld?: Array<{ catalogType: string; name: string; packageIds: string[] }>, +) { + const { engine, rows } = makeStubEngine(registeredTypes, packageHeld); const protocol = new ObjectStackProtocolImplementation( engine, () => new Map(), @@ -180,7 +175,7 @@ const NOT_A_CAPABILITY = { const entry = (type: string) => DEFAULT_METADATA_TYPE_REGISTRY.find((e) => e.type === type); -describe('#5961 — capability: the runtime write door is closed, and validated behind the hatch', () => { +describe('#5961 / #35157 — capability: runtime-creatable, schema-judged, one name per holder', () => { beforeEach(() => { delete process.env.OS_METADATA_WRITABLE; ObjectStackProtocolImplementation.resetEnvWritableCache(); @@ -190,150 +185,110 @@ describe('#5961 — capability: the runtime write door is closed, and validated ObjectStackProtocolImplementation.resetEnvWritableCache(); }); - // ── door 1: the default, and the acceptance criterion ───────────────── - - it('PUT /meta/capability/:name is refused 403 — nothing reaches sys_metadata', async () => { - // The write that used to succeed with ANY body. `environmentId` is set - // here and omitted in the next case on purpose: the refusal must not - // depend on deployment topology. - const { protocol, rows } = makeProtocol([], 'env_prod'); - - await expect( - protocol.saveMetaItem({ - type: 'capability', - name: 'billing.refund', - item: NOT_A_CAPABILITY, - }), - ).rejects.toMatchObject({ code: 'NOT_CREATABLE', status: 403 }); - - // Refused, not "refused after writing". The stored row is the bug. - expect(rows.size).toBe(0); + // ── 1. the schema judges every write ────────────────────────────────── + + it('a garbage body is 422 INVALID_METADATA — nothing reaches sys_metadata, no hatch needed', async () => { + // #5961's regression, on the open door: the body the old unregistered + // type stored verbatim. With or without an environment id — the + // answer must not depend on deployment topology (#5086). + for (const environmentId of ['env_prod', undefined]) { + const { protocol, rows } = makeProtocol([], environmentId); + await expect( + protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', item: NOT_A_CAPABILITY }), + ).rejects.toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + expect(rows.size).toBe(0); + } }); - it('a WELL-FORMED declaration is refused too — the door is about WHO writes, not what', async () => { - // The distinction that makes this a code-only kind rather than a - // validation improvement: a perfectly valid capability is still not - // authorable through the runtime API, because ADR-0066 D1 says - // packages DEFINE capabilities. If this ever goes green, the kind has - // silently become runtime-creatable. + it('a WELL-FORMED declaration saves — the environment may declare its own capability (#35157)', async () => { + // The control for the case above, and the acceptance criterion of + // #35157: an unmanaged copy writes its capabilities through this door. const { protocol, rows } = makeProtocol([], 'env_prod'); - - await expect( - protocol.saveMetaItem({ - type: 'capability', - name: 'billing.refund', - item: CAPABILITY, - }), - ).rejects.toMatchObject({ code: 'NOT_CREATABLE', status: 403 }); - expect(rows.size).toBe(0); - }); - - it('the refusal does not depend on deployment topology (no environmentId either)', async () => { - // #5086's finding: keying an authorization rule off `environmentId` - // left the flagship showcase — a host config boots with NO - // environmentId — running with the gate disengaged, on a surface whose - // `PUT /api/v1/meta/*` is an END-USER door. - const { protocol, rows } = makeProtocol(); - - await expect( - protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', item: CAPABILITY }), - ).rejects.toMatchObject({ code: 'NOT_CREATABLE', status: 403 }); - expect(rows.size).toBe(0); - }); - - it('the refusal prescribes where to declare it instead', async () => { - // `codeOnlySourceHint` reads the registry row's own `filePatterns[0]`, - // so the remedy cannot drift from the entry. A refusal that only says - // "no" sends the author looking for a workaround. - const { protocol } = makeProtocol(); - - await expect( - protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', item: CAPABILITY }), - ).rejects.toThrow(/\.capability\./); + const result = await protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', item: CAPABILITY }); + expect(result.success).toBe(true); + expect(rows.size).toBe(1); }); it('the plural spelling is judged by the same rule', async () => { // `STATIC_REGISTRY_TYPES` / `RUNTIME_CREATE_ALLOWED_TYPES` add // `SINGULAR_TO_PLURAL[type]` alongside each entry, so - // `PUT /meta/capabilities/:name` must not be a second, open door. + // `PUT /meta/capabilities/:name` is never a second, looser door. const { protocol, rows } = makeProtocol(); - await expect( - protocol.saveMetaItem({ type: 'capabilities', name: 'billing.refund', item: CAPABILITY }), - ).rejects.toMatchObject({ code: 'NOT_CREATABLE', status: 403 }); + protocol.saveMetaItem({ type: 'capabilities', name: 'billing.refund', item: NOT_A_CAPABILITY }), + ).rejects.toMatchObject({ code: 'INVALID_METADATA', status: 422 }); expect(rows.size).toBe(0); }); - // ── door 2: behind the operator escape hatch, the schema bites ──────── + // ── 2. the platform floor ───────────────────────────────────────────── - it('with OS_METADATA_WRITABLE=capability, a garbage body is 422 — not stored verbatim', async () => { - // THE regression this issue is about, isolated. Reaching the - // spec-conformance check requires opening ADR-0005's documented hatch, - // because the code-only refusal fires first — so this is the one place - // the new schema binding is observable on the write path, and without - // it this body was persisted. - process.env.OS_METADATA_WRITABLE = 'capability'; - ObjectStackProtocolImplementation.resetEnvWritableCache(); + it('a platform capability name is refused NAMESPACE_CONFLICT / 422, before any write', async () => { + // `manage_users` declared `scope: 'org'` by the environment would make + // every set granting it pass condition (c) of the organization + // boundary (ADR-0090 D12): an organization administrator could hand + // out user management. The floor is absolute. const { protocol, rows } = makeProtocol([], 'env_prod'); - - // [#6190] The `organizationId` this case used to pass was incidental — - // the door under test is the SCHEMA one, not the org one. Since the - // #6190 ruling an org-scoped write of a non-org-overridable type is - // refused BEFORE the schema is consulted (and `OS_METADATA_WRITABLE` - // deliberately does not unlock the org dimension), so keeping the org - // here would have turned this into a test of that other refusal and - // left the 422 unmeasured. Env-wide keeps it pointed at the schema. - // The hatch-plus-org interaction is pinned in - // `protocol.org-scoped-write-refused.test.ts` (case R7). - await expect( - protocol.saveMetaItem({ - type: 'capability', - name: 'billing.refund', - item: NOT_A_CAPABILITY, - }), - ).rejects.toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + const refused = protocol.saveMetaItem({ + type: 'capability', + name: 'manage_users', + item: { name: 'manage_users', label: 'Manage users', scope: 'org' }, + }); + await expect(refused).rejects.toMatchObject({ code: 'NAMESPACE_CONFLICT', status: 422 }); + await expect(refused).rejects.toThrow(/platform capability/); expect(rows.size).toBe(0); }); - it('behind the same hatch a VALID declaration saves — the 422 is about the body', async () => { - // The control that stops the case above from passing for the wrong - // reason. Without it, a change that made `capability` unwritable under - // every condition would look identical. - process.env.OS_METADATA_WRITABLE = 'capability'; - ObjectStackProtocolImplementation.resetEnvWritableCache(); - const { protocol, rows } = makeProtocol([], 'env_prod'); + // ── 3. one name, one holder ─────────────────────────────────────────── - const result = await protocol.saveMetaItem({ - type: 'capability', - name: 'billing.refund', - item: CAPABILITY, - }); + it('a name a package holds is refused — the environment cannot re-declare (re-scope) it', async () => { + const { protocol, rows } = makeProtocol([], 'env_prod', [ + { catalogType: 'capability', name: 'billing.refund', packageIds: ['com.acme.billing'] }, + ]); + const refused = protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', item: CAPABILITY }); + await expect(refused).rejects.toMatchObject({ code: 'NAMESPACE_CONFLICT', status: 422 }); + await expect(refused).rejects.toThrow(/package "com\.acme\.billing"/); + expect(rows.size).toBe(0); + }); + it('CONTROL: a permission set of the same name held by a package does not hold the capability name', async () => { + // The reading is per catalog type: a set and a capability that share a + // spelling are two different names. + const { protocol, rows } = makeProtocol([], 'env_prod', [ + { catalogType: 'permission', name: 'billing.refund', packageIds: ['com.acme.billing'] }, + ]); + const result = await protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', item: CAPABILITY }); expect(result.success).toBe(true); expect(rows.size).toBe(1); }); - // ── door 3: the package-declaration channel, untouched ──────────────── + it('re-saving the environment\'s own capability is untouched — the owner meets itself', async () => { + const { protocol, rows } = makeProtocol([], 'env_prod'); + await protocol.saveMetaItem({ type: 'capability', name: 'billing.refund', item: CAPABILITY }); + const again = await protocol.saveMetaItem({ + type: 'capability', name: 'billing.refund', item: { ...CAPABILITY, label: 'Refund payments' }, + }); + expect(again.success).toBe(true); + expect(rows.size).toBe(1); + }); + + // ── 4. the package-declaration channel, untouched ───────────────────── it('the package channel does not go through saveMetaItem at all', async () => { // `AppPlugin` calls `metadata.registerInMemory('capability', name, item)` // for every stack-declared capability, and the filesystem loader globs - // `filePatterns` — neither reaches the gate above, which is why - // `allowRuntimeCreate: false` closes the ADMIN door without breaking - // the one ADR-0066 D1 actually prescribes. Asserted structurally: the - // registry row is what the loader reads, and it must carry patterns. + // `filePatterns` — neither reaches the door above. Asserted + // structurally: the registry row is what the loader reads, and it + // must carry patterns; the overlay channel stays closed, so a package's + // declaration is never an environment author's to re-declare. const row = entry('capability')!; - expect(row.allowRuntimeCreate).toBe(false); + expect(row.allowRuntimeCreate).toBe(true); + expect(row.allowEnvironmentOverlay).toBe(false); expect(row.filePatterns.length).toBeGreaterThan(0); - - // And the declaration itself is spec-valid, so the seeding pass that - // reads it back (`bootstrapDeclaredCapabilities`) is being handed a - // body this schema accepts rather than one it would now reject. const { getMetadataTypeSchema } = await import('@objectstack/spec/kernel'); expect(getMetadataTypeSchema('capability')!.safeParse(CAPABILITY).success).toBe(true); }); - // ── /meta/types no longer publishes a fiction ───────────────────────── + // ── /meta/types serves the registry descriptor ──────────────────────── it('/meta/types serves the REAL registry descriptor, not a synthesised one', async () => { const { protocol } = makeProtocol(['capability']); @@ -342,19 +297,13 @@ describe('#5961 — capability: the runtime write door is closed, and validated const descriptor = entries.find((e: any) => e.type === 'capability'); expect(descriptor).toBeDefined(); - // The three tells of the synthesised branch, each asserted against the - // value the registry actually declares. - expect(descriptor.allowRuntimeCreate).toBe(false); // was: true - expect(descriptor.domain).toBe('security'); // was: 'system' - expect(descriptor.loadOrder).toBe(entry('capability')!.loadOrder); // was: 1000 - expect(descriptor.label).toBe('Capability'); // was: 'capability' + expect(descriptor.allowRuntimeCreate).toBe(true); + expect(descriptor.domain).toBe('security'); // the synthesised branch said 'system' + expect(descriptor.loadOrder).toBe(entry('capability')!.loadOrder); // …and 1000 + expect(descriptor.label).toBe('Capability'); // …and 'capability' }); it('/meta/types emits a real JSON Schema, so the admin form is not a raw-JSON textarea', async () => { - // The read-side consequence of the missing schema binding. The engine - // picks its controls from this; with no schema it falls back to a free - // text area, which is how arbitrary JSON got authored in the first - // place. const { protocol } = makeProtocol(['capability']); const { entries } = await protocol.getMetaTypes(); diff --git a/packages/metadata-protocol/src/protocol.code-only-types.test.ts b/packages/metadata-protocol/src/protocol.code-only-types.test.ts index 098e04b9524..9b29d585a63 100644 --- a/packages/metadata-protocol/src/protocol.code-only-types.test.ts +++ b/packages/metadata-protocol/src/protocol.code-only-types.test.ts @@ -40,6 +40,8 @@ import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFin import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel'; import { ObjectStackProtocolImplementation } from './protocol.js'; import { resetEnvWritableMetadataTypes } from './sys-metadata-repository.js'; +// The served save reaches a dynamic `import('@objectstack/lint')` (metadata diagnostics): pay its load at collection. +import '@objectstack/lint'; interface Row { id: string; @@ -85,23 +87,10 @@ const PROBES: Record }> = instructions: 'be helpful', }, }, - // [#5961] The third flagged type. ADR-0066 D1: packages DEFINE - // capabilities — an administrator minting one at runtime has no place in - // the capability / assignment / requirement separation, so the kind is - // code-only for the same reason `job` and `agent` are. This probe is - // schema-valid on purpose (see the note above): only a body the schema - // ACCEPTS proves the refusal came from the registry consult rather than - // from the 422 that #5961 also gave this type. - capability: { - name: 'rc3_capability_probe', - item: { - name: 'rc3_capability_probe', - label: 'C', - description: 'Probe capability.', - scope: 'org', - packageId: 'com.example.probe', - }, - }, + // [#5961] `capability` was the third flagged type, until #35157 made it + // runtime-creatable (an unmanaged install copies an app's capabilities + // into environment rows); its door is pinned in + // `protocol.capability-write-door.test.ts`. // [#5488] The fourth flagged type. `api` declared `allowRuntimeCreate: // true` and the runtime never honoured it: `matchEndpoint` reads // `MetadataManager.listForIndex('api')` (the manager's registry plus its @@ -308,8 +297,7 @@ describe('code-only metadata types are refused on every kernel (#5086)', () => { // ── the flags are data: keep the suite honest about new ones ────────── it('covers every code-only type the registry declares', () => { - // Today: job (#4509), agent (ADR-0063 §2), capability (#5961, - // ADR-0066 D1), api (#5488, ADR-0049 remove side — the maintainer + // Today: job (#4509), agent (ADR-0063 §2), api (#5488, ADR-0049 remove side — the maintainer // ruling of 2026-08-07 withdrew a runtime create door the endpoint // matcher could never read) and field (#7893, the same remove side — // ruled 2026-08-12; a `field` write minted a standalone row nothing @@ -323,7 +311,7 @@ describe('code-only metadata types are refused on every kernel (#5086)', () => { // (Prime Directive #8). expect(CODE_ONLY_TYPES.length).toBeGreaterThan(0); expect([...CODE_ONLY_TYPES].sort()).toEqual([ - 'agent', 'api', 'assignment_rule', 'capability', 'field', 'job', 'picklist', 'queue', 'sharing_rule', + 'agent', 'api', 'assignment_rule', 'field', 'job', 'picklist', 'queue', 'sharing_rule', ]); for (const type of CODE_ONLY_TYPES) { expect(PROBES[type], `no probe payload for code-only type '${type}'`).toBeDefined(); diff --git a/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts b/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts index 12a0f1834ad..6d8ee1b8219 100644 --- a/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts @@ -1034,7 +1034,7 @@ describe('[#30062] each excluded type\'s refusal names a remedy that works for i }); it('a code-only type names a new version of the base that ships it', () => { - for (const type of ['job', 'api', 'agent', 'capability', 'picklist', 'assignment_rule']) { + for (const type of ['job', 'api', 'agent', 'picklist', 'assignment_rule']) { expect(refusalOf(type), type).toContain(`changes only with a new version of '${BASE_ID}'`); } expect(refusalOf('api')).toContain('but an api takes no override'); diff --git a/packages/metadata-protocol/src/protocol.recovery-doors-emit-mutation.test.ts b/packages/metadata-protocol/src/protocol.recovery-doors-emit-mutation.test.ts index 35325fed0eb..cd19949ec8f 100644 --- a/packages/metadata-protocol/src/protocol.recovery-doors-emit-mutation.test.ts +++ b/packages/metadata-protocol/src/protocol.recovery-doors-emit-mutation.test.ts @@ -557,7 +557,7 @@ describe('[#14179] reachability: the legacy exit is confined to bootstrap mode', // Non-empty: the branch is not dead code. expect(codeOnly.length).toBeGreaterThan(0); expect(codeOnly.map((e) => e.type).sort()) - .toEqual(['agent', 'api', 'assignment_rule', 'capability', 'field', 'job', 'picklist', 'queue', + .toEqual(['agent', 'api', 'assignment_rule', 'field', 'job', 'picklist', 'queue', 'sharing_rule']); // …and the #6960 carve-out reaches none of them, which is what makes // the 403 below total rather than incidental. diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 98cf64e173e..fbc3478d7d7 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -87,7 +87,7 @@ export { } from './registry.js'; // [#22371] The package half of the cold-boot check's holder reading (ADR-0048 -// N.3): every package-held position and permission-set name, with its holders. +// N.3): every package-held position, permission-set and capability name, with its holders. // Exported for `os migrate security-catalog-overlays`, which boots the // deployment's composition without hydrating `sys_metadata` and meets this // list with the stored rows — the population the cold boot refuses — so the diff --git a/packages/objectql/src/protocol-boot-hydration-scoped.test.ts b/packages/objectql/src/protocol-boot-hydration-scoped.test.ts index 3fdbb596ac5..13fbd91e879 100644 --- a/packages/objectql/src/protocol-boot-hydration-scoped.test.ts +++ b/packages/objectql/src/protocol-boot-hydration-scoped.test.ts @@ -352,7 +352,9 @@ describe('security catalog read — a name two packages ship (ADR-0131 D4, ruled * `packages/qa/dogfood` and the artifact boot in `packages/runtime`. */ describe('cold boot — a package-held catalog name the environment catalog holds refuses the boot (ADR-0048 N.3)', () => { - type CatalogType = 'permission' | 'position'; + // `capability` joined the environment-held types with #35157: an unmanaged + // copy saves its app's capabilities into the environment catalog. + type CatalogType = 'permission' | 'position' | 'capability'; type Envelope = Error & { code?: string; status?: number; @@ -371,6 +373,7 @@ describe('cold boot — a package-held catalog name the environment catalog hold type: 'app', ...(decl.position ? { positions: decl.position.map((n) => catalogBody('position', n, 'shipped')) } : {}), ...(decl.permission ? { permissions: decl.permission.map((n) => catalogBody('permission', n, 'shipped')) } : {}), + ...(decl.capability ? { capabilities: decl.capability.map((n) => catalogBody('capability', n, 'shipped')) } : {}), }); const kernels: ObjectKernel[] = []; @@ -419,7 +422,7 @@ describe('cold boot — a package-held catalog name the environment catalog hold const environmentConflict = (type: CatalogType, name: string) => ({ catalogType: type, name, incomingPackageId: PKG, existingHolder: { kind: 'environment' } }); - describe.each(['permission', 'position'] as const)('%s', (type) => { + describe.each(['permission', 'position', 'capability'] as const)('%s', (type) => { const name = `coldboot_${type}`; it('a package-held name the environment catalog already holds refuses the boot, naming both holders', async () => { diff --git a/packages/objectql/src/protocol-unmanaged-import-rename-battery.test.ts b/packages/objectql/src/protocol-unmanaged-import-rename-battery.test.ts index 4daeed1c077..fe3e050800e 100644 --- a/packages/objectql/src/protocol-unmanaged-import-rename-battery.test.ts +++ b/packages/objectql/src/protocol-unmanaged-import-rename-battery.test.ts @@ -28,7 +28,7 @@ import { randomUUID } from 'node:crypto'; import { afterEach, describe, expect, it } from 'vitest'; -import { ObjectKernel } from '@objectstack/core'; +import { ObjectKernel, createSecurityCatalogReader, missingCapabilities } from '@objectstack/core'; import { ObjectQL } from './engine.js'; import { ObjectQLPlugin } from './plugin.js'; @@ -126,6 +126,7 @@ interface Fixture { /** The manifest collection each fixture type is declared under. */ const COLLECTION: Record = { object: 'objects', view: 'views', action: 'actions', permission: 'permissions', flow: 'flows', hook: 'hooks', + capability: 'capabilities', }; interface Harness { @@ -631,3 +632,66 @@ describe('[#30794] the duplicate battery, replayed through the unmanaged import }); }); }); + +// ── #35157: an app that gates an action on its own capability ────────────── + +const capabilityGated: Fixture[] = [ + { + type: 'object', item: { + name: 'dupsrc_asset', label: 'Asset', sharingModel: 'private', + requiredPermissions: { delete: ['dupsrc.manage_assets'] }, + fields: { title: { name: 'title', type: 'text', label: 'Title' } }, + }, + }, + { type: 'capability', item: { name: 'dupsrc.manage_assets', label: 'Manage assets', scope: 'org' } }, + { + type: 'permission', item: { + name: 'dupsrc_manager', label: 'Asset manager', + objects: { dupsrc_asset: { allowRead: true, allowEdit: true, allowDelete: true } }, + systemPermissions: ['dupsrc.manage_assets'], + }, + }, + { + type: 'action', item: { + name: 'dupsrc_scrap', label: 'Scrap', type: 'url', objectName: 'dupsrc_asset', target: 'https://example.com/scrap', + requiredPermissions: ['dupsrc.manage_assets'], + }, + }, +]; + +describe('[#35157] an app that gates an action on its own capability installs unmanaged, and the copy keeps its gate', () => { + it('the capability is copied under the target namespace, and every grant and requirement of it follows', async () => { + const imp = await viaImport(capabilityGated); + expect(imp.error).toBeUndefined(); + + expect(storedBody(imp.h, 'capability', 'dupdst.manage_assets', Q)) + .toMatchObject({ name: 'dupdst.manage_assets', label: 'Manage assets', scope: 'org' }); + expect(storedBody(imp.h, 'capability', 'dupsrc.manage_assets', Q)).toBeUndefined(); + expect(storedBody(imp.h, 'permission', 'dupdst_manager', Q).systemPermissions).toEqual(['dupdst.manage_assets']); + expect(storedBody(imp.h, 'action', 'dupdst_scrap', Q).requiredPermissions).toEqual(['dupdst.manage_assets']); + expect(storedBody(imp.h, 'object', 'dupdst_asset', Q).requiredPermissions).toEqual({ delete: ['dupdst.manage_assets'] }); + }); + + it('the security catalog resolves the copied capability with its scope — the input ADR-0090 D12 (c) reads', async () => { + const imp = await viaImport(capabilityGated); + expect(imp.error).toBeUndefined(); + // The metadata service holds no stack declaration in this kernel; the + // copy lives in the engine registry, which the reader asks first. + const metadata = { get: async () => undefined, list: async () => [] }; + const catalog = createSecurityCatalogReader({ registry: imp.h.engine.registry as never, metadata: metadata as never }); + const declared = await catalog.resolve('capability', 'dupdst.manage_assets'); + expect(declared?.definition).toMatchObject({ name: 'dupdst.manage_assets', scope: 'org' }); + }); + + it('the copied action admits a holder of the copied set, and refuses a non-holder and a holder of the SOURCE\'s grant', async () => { + const imp = await viaImport(capabilityGated); + expect(imp.error).toBeUndefined(); + const required = storedBody(imp.h, 'action', 'dupdst_scrap', Q).requiredPermissions; + const holder = { systemPermissions: storedBody(imp.h, 'permission', 'dupdst_manager', Q).systemPermissions }; + + expect(missingCapabilities(required, holder)).toEqual([]); + expect(missingCapabilities(required, { systemPermissions: [] })).toEqual(['dupdst.manage_assets']); + // Two copies of one app never share a gate: the source's grant opens nothing in the copy. + expect(missingCapabilities(required, { systemPermissions: ['dupsrc.manage_assets'] })).toEqual(['dupdst.manage_assets']); + }); +}); diff --git a/packages/objectql/src/registry-namespaces-and-claims.ts b/packages/objectql/src/registry-namespaces-and-claims.ts index 00de042b803..6261c1912f0 100644 --- a/packages/objectql/src/registry-namespaces-and-claims.ts +++ b/packages/objectql/src/registry-namespaces-and-claims.ts @@ -394,7 +394,7 @@ export class NamespacesAndClaimsFacet { /** * The cold-boot half of the rule (`security-catalog-namespace.ts`, "The cold * boot"; maintainer ruling letter A on #22307, record 6063176077): every - * package-held position and permission-set name the environment catalog also + * package-held position, permission-set and capability name the environment catalog also * holds, as the conflicts {@link SecurityCatalogNameConflictError} reports — * the package that declares the name as the incoming side, the environment * catalog as the holder. Read-only: it records nothing and refuses nothing; @@ -466,12 +466,12 @@ export class NamespacesAndClaimsFacet { } /** - * Every position and permission-set name a package holds, with its holders — + * Every position, permission-set and capability name a package holds, with its holders — * the package half of {@link environmentHeldSecurityCatalogConflicts}, and the * reading {@link findPackageHeldSecurityCatalogNames} exports. * * The candidate names are every composite slot's name and every install - * claim of the two types the environment catalog can hold + * claim of the types the environment catalog can hold * ({@link ENVIRONMENT_HELD_SECURITY_CATALOG_TYPES}); each one's holders are * {@link securityCatalogPackageHolders}'s answer, the one predicate. Built-in * names are skipped, as the cold boot skips them (see the method above). diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 2e870dda3c7..239c9c0f46d 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -1458,7 +1458,7 @@ export class MisplacedDefaultPageError extends Error { } /** - * Every package-held position and permission-set name the environment catalog + * Every package-held position, permission-set and capability name the environment catalog * also holds, read off `registry` — the conflicts the engine plugin's cold-boot * check refuses the boot with (`ObjectQLPlugin`, right after `sys_metadata` * hydration; the reading itself is the registry's private @@ -1473,7 +1473,7 @@ export function findEnvironmentHeldSecurityCatalogNames(registry: SchemaRegistry } /** - * Every position and permission-set name a package holds, with the packages + * Every position, permission-set and capability name a package holds, with the packages * that hold it, read off `registry` — the PACKAGE half of the reading the * cold-boot check refuses with ({@link findEnvironmentHeldSecurityCatalogNames} * is this list met with the environment catalog's bare slot, and nothing else). diff --git a/packages/objectql/src/security-catalog-namespace.ts b/packages/objectql/src/security-catalog-namespace.ts index 3beec6f92a6..43a8b72a682 100644 --- a/packages/objectql/src/security-catalog-namespace.ts +++ b/packages/objectql/src/security-catalog-namespace.ts @@ -58,7 +58,7 @@ * neither door above can see an environment-held name then: the stored row * arrives second, in the bare slot. Once hydration has run and before any other * plugin starts, the engine plugin asks the registry for every package-held - * position and permission-set name the environment catalog also holds + * position, permission-set and (#35157) capability name the environment catalog also holds * ({@link ENVIRONMENT_HELD_SECURITY_CATALOG_TYPES}), and one such name refuses the * boot with this rule's envelope, naming both holders. So a cold boot, a hot * install and an artifact boot answer alike. (Maintainer ruling, letter A on @@ -145,14 +145,17 @@ export const BUILT_IN_SECURITY_CATALOG_NAMES: Readonly .toEqual(describeHighPrivilegeBits(setGranting(APP.name), undefined)); expect(describeHighPrivilegeBits(setGranting(APP.name), undefined)).not.toBeNull(); }); + + // [ADR-0090 D5, #35157] A capability saved in the environment registers in the + // same collection with no `_packageId` (measured: `{ name, label, _provenance }`). + // It is not an app's own token, so it excuses nothing; an unmanaged copy's + // capability carries the copy package's id and still does. + const ENV_SAVED = { name: 'envcap.export', label: 'Saved in the environment', _provenance: 'org' }; + const COPIED = { name: 'trial1.export', label: 'Copied', _packageId: 'com.example.field-copy', _provenance: 'org' }; + + it('an environment-saved declaration is not the app\'s own token: it excuses nothing', async () => { + const context = await readDeclaredCapabilityContext(engineWith([OWN, APP, ENV_SAVED]), undefined); + expect(context).toEqual({ declaredCapabilities: [OWN, APP] }); + expect(describeHighPrivilegeBits(setGranting(ENV_SAVED.name), context)).not.toBeNull(); + expect(describeHighPrivilegeBits(setGranting(ENV_SAVED.name), context)) + .toEqual(describeHighPrivilegeBits(setGranting(ENV_SAVED.name), undefined)); + }); + + it('an unmanaged copy\'s capability carries its package and is excused like the source\'s', async () => { + const context = await readDeclaredCapabilityContext(engineWith([COPIED]), undefined); + expect(describeHighPrivilegeBits(setGranting(COPIED.name), context)).toBeNull(); + }); + + it('a registry holding only environment-saved declarations does not fall back to the metadata service', async () => { + let listed = false; + const metadata = { list: () => { listed = true; return [APP]; } }; + expect(await readDeclaredCapabilityContext(engineWith([ENV_SAVED]), metadata)).toBeUndefined(); + expect(listed).toBe(false); + }); + + it('the metadata-service fallback is judged by the same provenance test', async () => { + const metadata = { list: async () => [ENV_SAVED, APP] }; + expect(await readDeclaredCapabilityContext(engineWith([]), metadata)).toEqual({ declaredCapabilities: [APP] }); + const onlySaved = { list: async () => [ENV_SAVED] }; + expect(await readDeclaredCapabilityContext(engineWith([]), onlySaved)).toBeUndefined(); + }); + + // [ADR-0090 D5, #35157] `packageId` is an author-written key of the strict + // declaration schema, so an environment save with no package may carry it and + // registers `{ name, packageId, _provenance }` with no `_packageId`. The row's + // binding is still empty: it excuses nothing, whatever package it names. + const AUTHORED = { name: 'envcap.claim', label: 'Names a package', packageId: 'com.example.anyone' }; + const NAMING_A_PACKAGE = { ...AUTHORED, _provenance: 'org' }; + + it('an environment-saved body naming a package under `packageId` excuses nothing at the `everyone` anchor', async () => { + // The key is authorable: the body an environment author saves parses. + expect(CapabilityDeclarationSchema.safeParse(AUTHORED).success).toBe(true); + const context = await readDeclaredCapabilityContext(engineWith([OWN, APP, NAMING_A_PACKAGE]), undefined); + expect(context).toEqual({ declaredCapabilities: [OWN, APP] }); + expect(describeHighPrivilegeBits(setGranting(NAMING_A_PACKAGE.name), context)).not.toBeNull(); + expect(describeHighPrivilegeBits(setGranting(NAMING_A_PACKAGE.name), context)) + .toEqual(describeHighPrivilegeBits(setGranting(NAMING_A_PACKAGE.name), undefined)); + }); + + it('the metadata-service fallback reads no body key either: `packageId` or `package` excuses nothing there', async () => { + const naming = { list: async () => [NAMING_A_PACKAGE, { name: 'envcap.legacy', package: 'com.example.anyone' }] }; + expect(await readDeclaredCapabilityContext(engineWith([]), naming)).toBeUndefined(); + const beside = { list: async () => [NAMING_A_PACKAGE, APP] }; + const context = await readDeclaredCapabilityContext(engineWith([]), beside); + expect(context).toEqual({ declaredCapabilities: [APP] }); + expect(describeHighPrivilegeBits(setGranting(NAMING_A_PACKAGE.name), context)).not.toBeNull(); + }); }); diff --git a/packages/plugins/plugin-security/src/declared-capability-context.ts b/packages/plugins/plugin-security/src/declared-capability-context.ts index 90baecf594f..18a0c1bc685 100644 --- a/packages/plugins/plugin-security/src/declared-capability-context.ts +++ b/packages/plugins/plugin-security/src/declared-capability-context.ts @@ -86,11 +86,44 @@ export async function readDeclaredCapabilityContext( ql: any, metadataService?: any, ): Promise { - let caps: any[] = readDeclared(ql, 'capability'); - if (caps.length === 0) { + // [ADR-0090 D5, #35157] Only a declaration with PACKAGE provenance is the + // app's own token (「带 package provenance 的应用声明 capability 令牌不计」). + // A capability is runtime-creatable since #35157. A save with no package + // registers it here with no `_packageId`, and it excuses nothing. A save + // into a writable package (an unmanaged copy, a duplicate, a base the + // environment authors) carries that package's id, and it counts: the copy's + // capabilities must, and a row cannot tell a copied declaration from one + // saved by hand into the same package. What bounds that is the save door, + // not this filter: a platform capability's name and a name a package + // already declares are refused there, and `describeHighPrivilegeBits` + // applies the platform floor again. A name nobody declares can be declared + // once, by a `manage_metadata` holder, inside a writable package. + // Dropping a declaration errs toward refusing a binding, never toward + // granting one. + // + // ⛔ The binding is `_packageId` and nothing else, on both lists. It is the + // row's binding as the server states it: the save door strips it from every + // body (`stripDerivedProvenance`) and the stored-row reads restate it from + // the row's `package_id` column alone (`withRowBinding`). `packageId` is an + // author-written key of `CapabilityDeclarationSchema`, which an environment + // save keeps: a body saved with no package that names any package there, + // existing or not, is still a save with no package. The metadata service + // states no package key of its own either: `register` stores the body as + // written and `list` serves it as stored, so its `packageId` / `package` + // is the same author-written key. An item that service holds for a package + // under `packageId` alone is therefore dropped, which refuses a binding. + const withPackage = (list: any[]): any[] => list.filter((c) => { + const pkg = c?._packageId; + return typeof pkg === 'string' && pkg.length > 0; + }); + const registered: any[] = readDeclared(ql, 'capability'); + let caps: any[] = withPackage(registered); + if (registered.length === 0) { try { const listed = metadataService?.list?.('capability'); - caps = typeof (listed as any)?.then === 'function' ? await listed : (listed ?? []); + const answered = typeof (listed as any)?.then === 'function' ? await listed : (listed ?? []); + // The fallback is judged by the same provenance test, `_packageId` alone. + caps = Array.isArray(answered) ? withPackage(answered) : answered; } catch { caps = []; } } if (!Array.isArray(caps)) return undefined; diff --git a/packages/plugins/plugin-security/src/suggested-audience-bindings.test.ts b/packages/plugins/plugin-security/src/suggested-audience-bindings.test.ts index d63cbed8d55..521109d27f3 100644 --- a/packages/plugins/plugin-security/src/suggested-audience-bindings.test.ts +++ b/packages/plugins/plugin-security/src/suggested-audience-bindings.test.ts @@ -361,7 +361,9 @@ describe('confirmAudienceBindingSuggestion — the acceptance takes effect', () }); it('accepts an isDefault set whose systemPermissions token THIS stack declares', async () => { - const ql = makeQl([tokenPackage('crm.export_pipeline')], [{ name: 'crm.export_pipeline', label: 'Export Pipeline' }]); + // The registry stamps a package's declaration with its `_packageId`; only such + // a declaration is the app's own token (ADR-0090 D5). + const ql = makeQl([tokenPackage('crm.export_pipeline')], [{ name: 'crm.export_pipeline', label: 'Export Pipeline', _packageId: 'com.example.crm' }]); const deps = makeDeps(ql); const { suggestions } = await listAudienceBindingSuggestions(deps, ADMIN_CTX, {}); const { bindingCreated } = await confirmAudienceBindingSuggestion(deps, ADMIN_CTX, suggestions[0].id); @@ -369,6 +371,15 @@ describe('confirmAudienceBindingSuggestion — the acceptance takes effect', () expect(everyoneSets(ql)).toContain('crm_member_default'); }); + it('refuses a token declared only by an environment save (no package provenance) — #35157', async () => { + const ql = makeQl([tokenPackage('crm.export_pipeline')], [{ name: 'crm.export_pipeline', label: 'Export Pipeline' }]); + const deps = makeDeps(ql); + const { suggestions } = await listAudienceBindingSuggestions(deps, ADMIN_CTX, {}); + await expect(confirmAudienceBindingSuggestion(deps, ADMIN_CTX, suggestions[0].id)) + .rejects.toThrow(/cannot be given to the 'everyone' audience anchor/); + expect(everyoneSets(ql)).toEqual(BASELINE); + }); + it('still refuses an UNDECLARED systemPermissions token — the control for the case above', async () => { const ql = makeQl([tokenPackage('crm.settle_ledger')], [{ name: 'crm.export_pipeline', label: 'Export Pipeline' }]); const deps = makeDeps(ql); diff --git a/packages/runtime/src/domains/catalog-activation.ts b/packages/runtime/src/domains/catalog-activation.ts index 099bf3274d8..07bda1e81fa 100644 --- a/packages/runtime/src/domains/catalog-activation.ts +++ b/packages/runtime/src/domains/catalog-activation.ts @@ -158,8 +158,8 @@ export const CATALOG_ACTIVATION_SEGMENT = '_activation'; /** * The ledger types this door writes, each with its refusal wording. Exactly the - * types the resolver reads from the ledger; `capability` is code-only on the - * regime and has no switch. + * types the resolver reads from the ledger; `capability` has no switch on the + * regime (a declaration is a name, granted or not by the sets that switch). */ const CATALOG_ACTIVATION_SUBJECTS: Readonly { expect(listMetadataTypeSchemaTypes()).toContain('capability'); }); - it('has a registry entry, and it declares the kind CODE-ONLY', () => { - // The pair is the declaration: `allowRuntimeCreate: false` AND - // `allowEnvironmentOverlay: false` together are #5086's "no runtime write channel - // at all". Either one alone leaves a door open — which is why they are - // asserted together rather than in two cases. + it('has a registry entry: runtime-creatable, never an overlay of a packaged declaration (#35157)', () => { + // The pair is the declaration: `allowRuntimeCreate: true` lets an + // environment (an unmanaged copy among them) declare its own capability; + // `allowEnvironmentOverlay: false` keeps it from re-declaring one a + // package ships — a re-declaration could re-scope `org` ↔ `platform`. + // Asserted together, because flipping the second with the first would + // open the re-scoping door. expect(entry('capability')).toMatchObject({ domain: 'security', supportsOverlay: false, allowEnvironmentOverlay: false, - allowRuntimeCreate: false, + allowRuntimeCreate: true, }); }); @@ -98,11 +92,9 @@ describe('capability is a registered metadata kind', () => { expect(entry('capability')!.loadOrder).toBeLessThan(entry('position')!.loadOrder); }); - it('declares file patterns, so the code-only refusal can prescribe a remedy', () => { - // `codeOnlySourceHint` reads `filePatterns[0]` back into the 403 body — - // "Declare it in source (…) and redeploy". An entry with an empty array - // would refuse the write and then say nothing about the alternative, and - // the filesystem loader globs this same list, so it is not decoration. + it('declares file patterns, so the loader finds a `*.capability.ts` file', () => { + // The filesystem loader globs this list, and the CLI derives the file name + // `objectstack generate` writes from it, so it is not decoration. expect(entry('capability')!.filePatterns[0]).toMatch(/\.capability\./); }); diff --git a/packages/spec/src/kernel/metadata-create-seeds.test.ts b/packages/spec/src/kernel/metadata-create-seeds.test.ts index d8861b36228..6c73cb4d298 100644 --- a/packages/spec/src/kernel/metadata-create-seeds.test.ts +++ b/packages/spec/src/kernel/metadata-create-seeds.test.ts @@ -66,10 +66,10 @@ describe('metadata create seeds validate against their spec schemas', () => { // its `fields: {}` is where a new field goes. Same category as // `capability` / `api`, not deferred work. 'field', - // [#5961] `capability` is code-only by declaration - // (`allowRuntimeCreate: false` + `allowEnvironmentOverlay: false`, ADR-0066 D1): - // there is no runtime create surface for a create seed to seed. It is on - // this list for `job`/`agent`'s reason, not as deferred work. + // [#5961, #35157] `capability` is runtime-creatable (an unmanaged copy + // carries its app's capabilities) but has no Studio designer: it is + // created by the install copy or a `/meta` save, never from a blank form. + // It sits here with `permission` and `position`, not as deferred work. 'capability', // [#5488] `api` joined them on 2026-08-09 (maintainer ruling // 2026-08-07T16:59Z). It HAD a seed (#5271) and lost it with the runtime @@ -79,11 +79,11 @@ describe('metadata create seeds validate against their spec schemas', () => { // `publishPackage`. Same category as `capability`, not deferred work. 'api', // `picklist` is package-owned (`allowRuntimeCreate: false`): there is no - // runtime create surface to seed. Same category as `capability`. + // runtime create surface to seed. Same category as `api`. 'picklist', // [ADR-0131 D6] `sharing_rule` is code-only (regime C): an organization // authors its own rules through the sharing door, not `/meta`. Same - // category as `capability`. + // category as `api`. 'sharing_rule', // [ADR-0142 D1/D5] `queue` and `assignment_rule` are code-only (regime C, // `allowRuntimeCreate: false`): an organization staffs its own queues as diff --git a/packages/spec/src/kernel/metadata-plugin.zod.ts b/packages/spec/src/kernel/metadata-plugin.zod.ts index bcabd281540..7d603994af1 100644 --- a/packages/spec/src/kernel/metadata-plugin.zod.ts +++ b/packages/spec/src/kernel/metadata-plugin.zod.ts @@ -259,7 +259,7 @@ const MetadataTypeRegistryEntryBaseSchema = z.object({ * that never glob: the CLI derives every scaffolded file name from them * (commit 50fb191dc, pinned by `cli/test/generate-file-name-registry-parity.test.ts`), * and `codeOnlySourceHint` reads `filePatterns[0]` back as the prescription - * in a 403 `not_creatable` refusal — which the `capability` and `api` + * in a 403 `not_creatable` refusal — which the `job` and `api` * entries of `DEFAULT_METADATA_TYPE_REGISTRY` below already lean on. * * @example ["**\/*.object.ts", "**\/*.object.yml"] @@ -1147,7 +1147,7 @@ export const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntryParsed[] = // servable destination to be judged toward. // // `allowRuntimeCreate: false` + `allowEnvironmentOverlay: false` therefore makes - // `api` CODE-ONLY (the `job` / `agent` / `capability` shape): the #5086 inlet + // `api` CODE-ONLY (the `job` / `agent` shape): the #5086 inlet // refuses `PUT /api/v1/meta/api/:name` before persistence, on every kernel, // in draft mode as well as active, with `code: 'NOT_CREATABLE'`, `status: 403` // and a prescription naming this entry's own `filePatterns[0]` @@ -1234,28 +1234,39 @@ export const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntryParsed[] = { type: 'position', label: 'Position', filePatterns: ['**/*.position.ts', '**/*.position.yml'], supportsOverlay: true, allowEnvironmentOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, executionPinned: false, loadOrder: 15, domain: 'security' }, // [#5961] Package-declared authorization capabilities (ADR-0066 D1). // - // ⛔ CODE-ONLY, and that is the whole point of the entry. ADR-0066 D1 says - // packages DEFINE capabilities — `defineCapability` on a stack's - // `capabilities[]`, or a `*.capability.ts` file the loader globs — while - // permission sets GRANT them and resources REQUIRE them. An administrator - // minting a brand-new capability at runtime has no counterpart in that - // three-way separation: nothing in code would ever require the name, so the - // row would be an unreferenced grant target sitting in the SAME namespace - // `systemPermissions` / `requiredPermissions` resolve by string. Hence - // `allowRuntimeCreate: false` AND `allowEnvironmentOverlay: false`, which together - // are #5086's code-only declaration — `saveMetaItem` refuses - // `PUT /api/v1/meta/capability/:name` with 403 `not_creatable` on EVERY - // kernel, and `codeOnlySourceHint` reads `filePatterns[0]` back to tell the - // author where to declare it instead. `job` (#4509) and `agent` (ADR-0063 §2) - // carry the same pair for the same reason. + // RUNTIME-CREATABLE, OVERLAY-CLOSED (#35157). ADR-0066 D1 says a package + // DEFINES a capability, a permission set GRANTS it and a resource REQUIRES + // it. The entry was first code-only on the reading that an administrator + // minting a capability at runtime has no counterpart in that separation — + // "nothing in code would ever require the name". That stopped being true + // once environment metadata could carry the other two edges: an action, a + // flow or an object authored in the environment declares + // `requiredPermissions`, and a permission set authored there grants it. The + // case that forced the reading is an `unmanaged` install (ADR-0131 D6), + // which copies a package into environment rows through this save door: an + // app that gates its actions on its own capabilities had nowhere to put the + // declarations, so it could not be copied at all, and dropping them would + // have kept the gate (the runtime matches names) while losing what only a + // declaration carries — its label, its `org` scope (ADR-0090 D12 (c)) and + // the exemption that lets a set granting it bind to `everyone` (ADR-0090 + // D5 revision). + // + // What stays closed, and where: + // - `allowEnvironmentOverlay: false` — a capability a package ships is not + // an environment author's to re-declare: the save door's package door + // refuses a write onto it, so a tenant cannot re-scope it. + // - A platform capability name (`PLATFORM_CAPABILITY_NAMES`) and a name + // another holder already declares are refused at save, before anything + // is stored (`@objectstack/metadata-protocol`'s security-catalog name + // refusal): one name, one holder, and the platform floor is absolute + // (ADR-0090 D5 revision, boundary 1). + // - The body is judged by `CapabilityDeclarationSchema` (422), as it was + // behind the `OS_METADATA_WRITABLE` hatch. // // The package-declaration channel is untouched: `AppPlugin` registers stack // `capabilities[]` through `registerInMemory`, and the filesystem loader // globs `filePatterns` — neither goes through `saveMetaItem`, so a package's // declarations still reach the registry, their one home (ADR-0131 D3). - // `OS_METADATA_WRITABLE=capability` remains the ONE documented - // operator escape hatch (ADR-0005), and behind it the write is now judged by - // `CapabilityDeclarationSchema` (422) instead of being stored unvalidated. // // `supportsOverlay: false` — a capability is a name, label and scope; there // is no merge semantic, and letting a tenant overlay a package-shipped @@ -1266,10 +1277,10 @@ export const DEFAULT_METADATA_TYPE_REGISTRY: MetadataTypeRegistryEntryParsed[] = // `description` is admin-facing copy in plain words. In ADR terms this is the // DEFINITION side of ADR-0066 D1: grants live on permission sets, // requirements on resources. - { type: 'capability', label: 'Capability', description: 'A permission a package defines; you grant it through permission sets', filePatterns: ['**/*.capability.ts', '**/*.capability.yml'], supportsOverlay: false, allowEnvironmentOverlay: false, allowRuntimeCreate: false, supportsVersioning: false, executionPinned: false, loadOrder: 12, domain: 'security' }, + { type: 'capability', label: 'Capability', description: 'A permission a package defines; you grant it through permission sets', filePatterns: ['**/*.capability.ts', '**/*.capability.yml'], supportsOverlay: false, allowEnvironmentOverlay: false, allowRuntimeCreate: true, supportsVersioning: false, executionPinned: false, loadOrder: 12, domain: 'security' }, // [ADR-0131 D6, regime C] Declared sharing rules. // - // ⛔ CODE-ONLY, the `capability` pair, for a regime-C reason: a sharing rule + // ⛔ CODE-ONLY, the `job` pair, for a regime-C reason: a sharing rule // has exactly two sources — a package declares it (the stack's `sharingRules`, // served from the registry, switched off through the activation ledger) and an // organization authors its own (`sys_sharing_rule`, `POST /api/v1/sharing/rules`, diff --git a/packages/spec/src/kernel/metadata-type-field-registration.test.ts b/packages/spec/src/kernel/metadata-type-field-registration.test.ts index e55a056b761..fae9c150130 100644 --- a/packages/spec/src/kernel/metadata-type-field-registration.test.ts +++ b/packages/spec/src/kernel/metadata-type-field-registration.test.ts @@ -58,7 +58,7 @@ describe('`field` is still a declared metadata kind — only its create door clo }); it('still resolves a schema — schema RESOLUTION is not the write door', () => { - // Same separation `api` (#5488) and `capability` (#5961) keep: a code-only + // Same separation `api` (#5488) keeps: a code-only // type still needs its shape resolvable for validation, diagnostics and // generated docs. Losing this would make `_diagnostics` silently opinionless // on every existing `field` row. diff --git a/packages/spec/src/stack-unmanaged-install-mode.test.ts b/packages/spec/src/stack-unmanaged-install-mode.test.ts index 3b22b23ea85..6d42a65a11d 100644 --- a/packages/spec/src/stack-unmanaged-install-mode.test.ts +++ b/packages/spec/src/stack-unmanaged-install-mode.test.ts @@ -65,7 +65,31 @@ const rows: Array<{ site: string; extra: Record; manifestExtra? describe('defineStack refuses `installModes` with `unmanaged` on a package the copy cannot write (ADR-0131 D6)', () => { it('the premise: the registry declares runtime-uncreatable types, `picklist` among them', () => { const uncreatable = DEFAULT_METADATA_TYPE_REGISTRY.filter((e) => !e.allowRuntimeCreate).map((e) => e.type); - expect(uncreatable).toEqual(expect.arrayContaining(['agent', 'api', 'capability', 'field', 'job', 'picklist'])); + expect(uncreatable).toEqual(expect.arrayContaining(['agent', 'api', 'field', 'job', 'picklist'])); + }); + + it('[#35157] an app that gates an action on its own capability permits `unmanaged` — the AI-built app shape', () => { + // The shape the authoring skills teach for a confirm-gated business + // action, as an AI-built gallery app wrote it: the package DECLARES the + // capability, a permission set GRANTS it, the action and the object + // REQUIRE it (ADR-0066 D1). The capability was the one thing such an app + // could not copy; the registry now declares `capability` + // runtime-creatable, so the copy writes it like any other item. + const gated = { + objects: [{ ...task, requiredPermissions: { delete: ['probe.manage_tasks'] } }], + capabilities: [{ name: 'probe.manage_tasks', label: 'Manage tasks', scope: 'org' }], + permissions: [{ + name: 'probe_manager', label: 'Task manager', + objects: { probe_task: { allowRead: true, allowEdit: true, allowDelete: true } }, + systemPermissions: ['probe.manage_tasks'], + }], + actions: [{ + name: 'probe_close', label: 'Close', objectName: 'probe_task', type: 'script', target: 'probe_close', + requiredPermissions: ['probe.manage_tasks'], + }], + }; + expect(refusal({ manifest: manifest(BOTH), ...gated })).toBeNull(); + expect(refusal({ manifest: manifest(['unmanaged']), ...gated })).toBeNull(); }); for (const row of rows) { diff --git a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx index 738b36bb8e3..15bd1db4bb4 100644 --- a/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx +++ b/ui/packages/app-shell/src/preview/DraftChangesPanel.tsx @@ -894,6 +894,8 @@ const TYPE_COUNT: Readonly strin doc: (t, count) => t('preview.changes.typeCount.doc', { count, defaultValue: '{{count}} documentation pages' }), book: (t, count) => t('preview.changes.typeCount.book', { count, defaultValue: '{{count}} documentation books' }), position: (t, count) => t('preview.changes.typeCount.position', { count, defaultValue: '{{count}} positions' }), + capability: (t, count) => + t('preview.changes.typeCount.capability', { count, defaultValue: '{{count}} capabilities' }), tool: (t, count) => t('preview.changes.typeCount.tool', { count, defaultValue: '{{count}} AI tools' }), skill: (t, count) => t('preview.changes.typeCount.skill', { count, defaultValue: '{{count}} AI skills' }), datasource: (t, count) => diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index e32275a1bd5..b20a0a36715 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -5258,6 +5258,13 @@ const ar = { position_few: 'مناصب {{count}}', position_many: 'مناصب {{count}}', position_other: 'مناصب {{count}}', + capability: 'قدرات {{count}}', + capability_zero: 'قدرات {{count}}', + capability_one: 'قدرة {{count}}', + capability_two: 'قدرات {{count}}', + capability_few: 'قدرات {{count}}', + capability_many: 'قدرات {{count}}', + capability_other: 'قدرات {{count}}', tool: 'أدوات ذكاء اصطناعي {{count}}', tool_zero: 'أدوات ذكاء اصطناعي {{count}}', tool_one: 'أداة ذكاء اصطناعي {{count}}', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 06f90da1dd8..8d54ff22f74 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4713,6 +4713,9 @@ const de = { position: '{{count}} Positionen', position_one: '{{count}} Position', position_other: '{{count}} Positionen', + capability: '{{count}} Capabilities', + capability_one: '{{count}} Capability', + capability_other: '{{count}} Capabilities', tool: '{{count}} KI-Werkzeuge', tool_one: '{{count}} KI-Werkzeug', tool_other: '{{count}} KI-Werkzeuge', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index a6c1b468ada..f378782c0c3 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4308,6 +4308,9 @@ const en = { position: '{{count}} positions', position_one: '{{count}} position', position_other: '{{count}} positions', + capability: '{{count}} capabilities', + capability_one: '{{count}} capability', + capability_other: '{{count}} capabilities', tool: '{{count}} AI tools', tool_one: '{{count}} AI tool', tool_other: '{{count}} AI tools', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 4329b2efeb5..7993dd73346 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4850,6 +4850,10 @@ const es = { position_one: '{{count}} puesto', position_many: '{{count}} de puestos', position_other: '{{count}} puestos', + capability: '{{count}} capacidades', + capability_one: '{{count}} capacidad', + capability_many: '{{count}} de capacidades', + capability_other: '{{count}} capacidades', tool: '{{count}} herramientas de IA', tool_one: '{{count}} herramienta de IA', tool_many: '{{count}} de herramientas de IA', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 06dc2cd4b0e..5ac877d8672 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4846,6 +4846,10 @@ const fr = { position_one: '{{count}} poste', position_many: '{{count}} de postes', position_other: '{{count}} postes', + capability: '{{count}} capacités', + capability_one: '{{count}} capacité', + capability_many: '{{count}} de capacités', + capability_other: '{{count}} capacités', tool: '{{count}} outils d’IA', tool_one: '{{count}} outil d’IA', tool_many: '{{count}} d’outils d’IA', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 88c83711f34..9bbb462dc3e 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4715,6 +4715,9 @@ const ja = { position: '役職 {{count}}', position_one: '役職 {{count}}', position_other: '役職 {{count}}', + capability: 'ケイパビリティ {{count}}', + capability_one: 'ケイパビリティ {{count}}', + capability_other: 'ケイパビリティ {{count}}', tool: 'AI ツール {{count}}', tool_one: 'AI ツール {{count}}', tool_other: 'AI ツール {{count}}', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index c7e9cda5634..393f2b02b35 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4712,6 +4712,9 @@ const ko = { position: '직위 {{count}}', position_one: '직위 {{count}}', position_other: '직위 {{count}}', + capability: '기능 권한 {{count}}', + capability_one: '기능 권한 {{count}}', + capability_other: '기능 권한 {{count}}', tool: 'AI 도구 {{count}}', tool_one: 'AI 도구 {{count}}', tool_other: 'AI 도구 {{count}}', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index f079b8daeba..573ce8374ff 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4845,6 +4845,10 @@ const pt = { position_one: '{{count}} cargo', position_many: '{{count}} de cargos', position_other: '{{count}} cargos', + capability: '{{count}} capacidades', + capability_one: '{{count}} capacidade', + capability_many: '{{count}} de capacidades', + capability_other: '{{count}} capacidades', tool: '{{count}} ferramentas de IA', tool_one: '{{count}} ferramenta de IA', tool_many: '{{count}} de ferramentas de IA', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 36c7e64cc65..8e2d3d6275b 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -4996,6 +4996,11 @@ const ru = { position_few: 'Должности: {{count}}', position_many: 'Должности: {{count}}', position_other: 'Должности: {{count}}', + capability: 'Возможности: {{count}}', + capability_one: 'Возможность: {{count}}', + capability_few: 'Возможности: {{count}}', + capability_many: 'Возможности: {{count}}', + capability_other: 'Возможности: {{count}}', tool: 'ИИ-инструменты: {{count}}', tool_one: 'ИИ-инструмент: {{count}}', tool_few: 'ИИ-инструменты: {{count}}', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 80c52322b3a..04abb903fe6 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3692,6 +3692,9 @@ const zh = { position: '岗位 {{count}}', position_one: '岗位 {{count}}', position_other: '岗位 {{count}}', + capability: '能力 {{count}}', + capability_one: '能力 {{count}}', + capability_other: '能力 {{count}}', tool: 'AI 工具 {{count}}', tool_one: 'AI 工具 {{count}}', tool_other: 'AI 工具 {{count}}', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 52938754e0d..fa77c461e57 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3692,6 +3692,9 @@ const zhHant = { position: '崗位 {{count}}', position_one: '崗位 {{count}}', position_other: '崗位 {{count}}', + capability: '能力 {{count}}', + capability_one: '能力 {{count}}', + capability_other: '能力 {{count}}', tool: 'AI 工具 {{count}}', tool_one: 'AI 工具 {{count}}', tool_other: 'AI 工具 {{count}}',