diff --git a/.changeset/34726-enterprise-capability-advisory.md b/.changeset/34726-enterprise-capability-advisory.md new file mode 100644 index 00000000000..d59db4d10e5 --- /dev/null +++ b/.changeset/34726-enterprise-capability-advisory.md @@ -0,0 +1,16 @@ +--- +'@objectstack/cli': patch +--- + +feat(cli): `os validate`, `os verify` and `os serve` name a declared enterprise or cloud capability that no provider enforces + +Clause-②: yes (widening) +Metadata-protocol: none + +A stack that declares `requires: ['hierarchy-security']` and runs without the enterprise provider wired into `plugins[]` gets owner-only hierarchy scopes (`own_and_reports`, `unit`, `unit_and_below`), and before this nothing said so past `os validate`'s install hint. + +- `os verify` now runs the capability-provider check `os validate` runs and reports every finding as an advisory: a `capabilities` array on the `--json` report (`token`, `message`, and `validate`: `error` when `os validate` refuses the stack over it, `warning` when it reports it), and one line each on the text face. It never changes `os verify`'s exit status, for any token. +- `os validate` and `os build` (and through the first, `os verify`) add a wiring check: an `enterprise`-edition token whose package resolves but which no `plugins[]` entry provides is a warning. Which tokens are `enterprise` is read from the capability registry's edition tags. +- `os validate --strict` (and `os validate --json --strict`), which already fails on any warning, now exits 1 for a stack whose `enterprise` capability package resolves but is not wired into `plugins[]`, or resolves but fails to load, while without `--strict`, and in `os build` (which has no flag that fails on warnings), the exit status is unchanged. +- The `enterprise` message names what happens without a provider (for `hierarchy-security`: the hierarchy scopes behave as owner-only) and its remedy reads "Install the package and add its plugin to `plugins[]`, or remove the token from `requires`". +- `os serve` prints the same sentence once at start-up for a declared enterprise or cloud token that nothing mounts. The boot itself is unchanged. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 71f03a48826..cd2b81bc5a7 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -2955,9 +2955,17 @@ os verify --dashboard-windows # Also prove each dashboard date them, and `os validate` prints them. This stage is the rule registry, not all of `os validate`: the `defineStack` provenance refusal (a config whose default export `defineStack` did not build, `STACK_PROVENANCE_MISSING`), the - package-docs lint, the capability-provider check, the picklist-reference and - view-container-name checks and `--strict` stay `os validate`'s, so run it - too. + package-docs lint, the picklist-reference and view-container-name checks and + `--strict` stay `os validate`'s, so run it too. + + The stage then runs `os validate`'s capability-provider check over every + declared `requires` token and reports each finding as an **advisory**, in + the sentence `os validate` prints: a cloud-only token, an `enterprise` token + whose package is not installed, and an `enterprise` token whose package + resolves but which no plugin in `plugins[]` provides (for + `hierarchy-security`, the hierarchy scopes then behave as owner-only). These + never change `os verify`'s exit status, including the cloud-only tokens + `os validate` refuses. 2. **Runtime.** Boot the app in-process and exercise it through the real HTTP stack. The boot reads the project's `.env*` files first, the ones `os dev` reads, from the directory holding the config (a variable already exported @@ -3111,7 +3119,9 @@ document carries depends on where the run ended: `path`, `message`, `hint`, plus `package` for a finding raised inside one package of the artifact), or the schema issues when the stack does not parse. - **Reached the runtime stage:** the report — `app`, `config`, `multiTenant`, - `seed` (the boot's seed: its `status`, per-source counts, `totals` and the + `capabilities` (the capability-provider advisories: `token`, `message`, and + `validate`, which is `error` when `os validate` refuses the stack over it and + `warning` when it reports it; `[]` when there are none), `seed` (the boot's seed: its `status`, per-source counts, `totals` and the `hardFailures` it adds), `crud`, `rls` (with `--rls`), `referenceShapes` (with `--reference-shapes`), `deleteBehaviors` (with `--delete-behaviors`), `uniqueScopes` (with `--unique-scopes`; its `boot` names the legs the run could prove), diff --git a/content/docs/permissions/administrator-guide.mdx b/content/docs/permissions/administrator-guide.mdx index 7f4dcee28d7..ed1b9e6796b 100644 --- a/content/docs/permissions/administrator-guide.mdx +++ b/content/docs/permissions/administrator-guide.mdx @@ -62,7 +62,7 @@ Three similarly-named things, three different jobs — don't mix them up: | Object | Job | |:--|:--| -| **Business unit** (`sys_business_unit`) | The hierarchy. Drives visibility depth (`unit`, `unit_and_below`) and delegated-admin boundaries | +| **Business unit** (`sys_business_unit`) | The hierarchy. Drives visibility depth (`unit`, `unit_and_below`; enforced by the enterprise edition, owner-only on the open edition) and delegated-admin boundaries | | **Team** (`sys_team`) | Flat collaboration group. Teams *receive* sharing; they never carry capability | | **Organization** (`sys_organization`) | The tenant itself — your company's account, not a node inside it | diff --git a/content/docs/permissions/index.mdx b/content/docs/permissions/index.mdx index f7422bd4f0b..5d453e80a99 100644 --- a/content/docs/permissions/index.mdx +++ b/content/docs/permissions/index.mdx @@ -18,7 +18,9 @@ widens); **row-level security** is the expert escape hatch that narrows. without a declared rule stay visible by default — see the [FLS posture note](/docs/permissions/authorization#combination-semantics-the-fixed-order)). Object access scopes go from `own` through `own_and_reports`, `unit`, -`unit_and_below`, to `org`. There is no Profile concept and the word "role" +`unit_and_below`, to `org`; the three hierarchy scopes in between are enforced by +the enterprise edition only and behave as `own` on the open edition (see +[Access depth](/docs/permissions/permission-sets#access-depth--readscope--writescope-adr-0057-d1)). There is no Profile concept and the word "role" is reserved (D3) — if you knew the v1 model, start at [Profiles (removed)](/docs/permissions/profiles) and [Positions](/docs/permissions/positions). diff --git a/content/docs/permissions/permission-sets.mdx b/content/docs/permissions/permission-sets.mdx index 28c12cd35be..84990e76e5a 100644 --- a/content/docs/permissions/permission-sets.mdx +++ b/content/docs/permissions/permission-sets.mdx @@ -145,7 +145,12 @@ the anchor decides *which* unit `unit*` means. > **Open-core boundary (ADR-0016).** `own` and `org` are open-source. The > hierarchy-relative scopes (`own_and_reports` / `unit` / `unit_and_below`) > require the enterprise hierarchy resolver; without it they **fail closed to -> `own`** (never fail-open). +> `own`** (never fail-open). Only the enterprise edition enforces them: the stack +> declares `requires: ['hierarchy-security']` (`defineStack` refuses a hierarchy +> scope without it) and wires `@objectstack/security-enterprise`'s plugin into +> `plugins[]`. When the token is declared but no plugin in `plugins[]` provides +> it, `os validate`, `os verify` (an advisory under `capabilities` in `--json`) +> and `os serve` at start-up each name the token and the owner-only fallback. > **A depth axis beside the super-user bit that bypasses it is REFUSED.** The > read-scope resolver answers `org` on the super-user bit *before* it consults diff --git a/content/docs/permissions/permissions-matrix.mdx b/content/docs/permissions/permissions-matrix.mdx index 46b5d8798eb..f0aeb008051 100644 --- a/content/docs/permissions/permissions-matrix.mdx +++ b/content/docs/permissions/permissions-matrix.mdx @@ -307,7 +307,8 @@ graph TD - **Scope depth** — grant a permission set `readScope: 'unit'` / `'unit_and_below'`; the owner-match widens to the caller's unit (or its subtree). A position assignment's `business_unit_id` anchor decides *which* - unit that means for multi-unit users (ADR-0090 Addendum). + unit that means for multi-unit users (ADR-0090 Addendum). Enterprise edition + only: on the open edition these scopes behave as owner-only. - **Sharing-rule recipients** — share with `{ type: 'unit_and_subordinates', value: 'east' }` to reach everyone in the East subtree, or `{ type: 'position', value: 'sales_manager' }` to reach a diff --git a/content/docs/permissions/positions.mdx b/content/docs/permissions/positions.mdx index 936f1d6af26..3731eaf3b88 100644 --- a/content/docs/permissions/positions.mdx +++ b/content/docs/permissions/positions.mdx @@ -49,6 +49,9 @@ Visibility depth comes from two dedicated structures: - the **manager chain** (`sys_user.manager_id`) — consumed by `own_and_reports`. +The depth grants (`own_and_reports`, `unit`, `unit_and_below`) are enforced by +the enterprise edition only; on the open edition they behave as owner-only. + **There is no implicit "managers see subordinates' records" grant.** Upward visibility is always an explicit opt-in: a sharing rule targeting a position or BU subtree, or a scope-depth grant on the permission set. See diff --git a/packages/cli/src/commands/compile.ts b/packages/cli/src/commands/compile.ts index ad19c64ab9a..f821f9eef89 100644 --- a/packages/cli/src/commands/compile.ts +++ b/packages/cli/src/commands/compile.ts @@ -27,7 +27,11 @@ import { stackFilterJudge } from '../utils/authoring-filter-judge.js'; import { buildAccessMatrix, diffAccessMatrix } from '@objectstack/lint'; import { runAuthoringRules, splitBySeverity, authoringRulesFor } from '@objectstack/lint'; import { resolveJsxGateManifest, printJsxGateNotices } from '../utils/sdui-manifest.js'; -import { preflightDeclaredCapabilities, renderCapabilityMessage } from '../utils/capability-preflight.js'; +import { + preflightDeclaredCapabilities, + preflightProviderWiring, + renderCapabilityMessage, +} from '../utils/capability-preflight.js'; import { collectAndLintDocs, placeCollectedDocs, type DocIssue } from '../utils/collect-docs.js'; import { buildRuntimeBundle, cleanupOldRuntimeBundles } from '../utils/build-runtime.js'; import { @@ -1023,7 +1027,16 @@ export default class Compile extends Command { // `{ token, message }` record beside its own preflight call, so // mirroring it is what keeps the two commands from reporting // different sets. One list cannot drift from itself. - capProviderWarnings = capPreflight.warnings.map((c) => ({ + // An `enterprise` token whose package resolves but which no `plugins[]` + // entry provides is enforced by nothing (`preflightProviderWiring`), the + // same advisory `os validate` raises. + const capWiring = await preflightProviderWiring({ + requires: (config as { requires?: unknown }).requires, + packages: packageEntries, + plugins: (config as { plugins?: unknown }).plugins, + projectDir: path.dirname(absolutePath), + }); + capProviderWarnings = [...capPreflight.warnings, ...capWiring].map((c) => ({ token: c.token, message: renderCapabilityMessage(c), })); diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index 9193546e270..a2dbafa2ddb 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -75,7 +75,7 @@ import { type SeedSettlementSnapshot, type SeedSuppressionReason, } from '@objectstack/spec/contracts'; -import { missingProviderMessage } from '../utils/capability-preflight.js'; +import { judgeDeclaredCapabilities, missingProviderMessage } from '../utils/capability-preflight.js'; import { composeSeedSettledMessage } from '../utils/seed-settled-message.js'; // The deployment's product name, for `AuthPlugin` — the same resolver the email // capability's template context reads (`resolveEmailCapabilityArg`), so the two @@ -5469,6 +5469,33 @@ export default class Serve extends Command { const hasPluginMatching = (identities: readonly string[]) => Serve.providesCapability(plugins, identities) || Serve.providesCapability(resolverMounted, identities); + // A DECLARED token this resolver has no row for, and no tier block + // handles, is mounted by nothing here: an `enterprise` provider comes + // only from the app's own `plugins[]`, a cloud-only tier from a cloud + // runtime. The loop below stays quiet for those (they are known + // vocabulary, not typos), and the sharing layer then fails closed to + // owner-only without a word. Say it once at start-up, in the sentence + // `os validate` and `os verify` print for the same token, and only when + // nothing in `plugins[]` provides it. A warning, never a refusal: the + // boot is unchanged. + const unmountedKnownTokens = [...declaredRequires].filter( + (cap) => + !CAPABILITY_PROVIDERS[cap] && + !Object.prototype.hasOwnProperty.call(Serve.CAPABILITY_TO_TIER, cap) && + PLATFORM_CAPABILITY_TOKENS.includes(cap), + ); + if (unmountedKnownTokens.length > 0) { + const judged = await judgeDeclaredCapabilities({ + requires: unmountedKnownTokens, + packages: [], + plugins, + projectDir: hostRoot, + }); + for (const a of [...judged.errors, ...judged.warnings]) { + console.warn(chalk.yellow(` ⚠ ${a.message}`)); + } + } + for (const cap of requires) { const spec = CAPABILITY_PROVIDERS[cap]; if (!spec) { @@ -5476,7 +5503,8 @@ export default class Serve extends Command { // ui/auth) are handled by their dedicated blocks above; other KNOWN // vocabulary tokens are provided elsewhere (`hierarchy-security` via // an explicit enterprise plugin in `plugins[]`, `ai-seat`/`governance` - // by cloud's objectos-runtime) — stay quiet for those. An UNKNOWN + // by cloud's objectos-runtime) — this loop stays quiet for those; the + // start-up line above names any that nothing provides. An UNKNOWN // declared token is a typo that was previously ignored SILENTLY // (#3265) — warn loudly. Warn-first: intended to become a hard error // once the vocabulary proves complete (Prime Directive #12). diff --git a/packages/cli/src/commands/validate.ts b/packages/cli/src/commands/validate.ts index 401d3aec3f0..41273c34e09 100644 --- a/packages/cli/src/commands/validate.ts +++ b/packages/cli/src/commands/validate.ts @@ -23,7 +23,11 @@ import { artifactPackages, runPerPackageAuthoringRules } from '../utils/artifact import { stackFilterJudge } from '../utils/authoring-filter-judge.js'; import { runAuthoringRules, splitBySeverity, authoringRulesFor } from '@objectstack/lint'; import { resolveJsxGateManifest, printJsxGateNotices } from '../utils/sdui-manifest.js'; -import { preflightDeclaredCapabilities, renderCapabilityMessage } from '../utils/capability-preflight.js'; +import { + preflightDeclaredCapabilities, + preflightProviderWiring, + renderCapabilityMessage, +} from '../utils/capability-preflight.js'; import { collectAndLintDocs, type DocIssue } from '../utils/collect-docs.js'; import { collectSeedFiles } from '../utils/bundle-seed-files.js'; import { collectConnectorSpecFiles } from '../utils/bundle-connector-spec-files.js'; @@ -1035,7 +1039,16 @@ export default class Validate extends Command { projectDir: dirname(absolutePath), }); const capProviderErrors = capProviderPreflight.errors; - capProviderWarnings = capProviderPreflight.warnings.map((c) => ({ + // An `enterprise` token whose package resolves is still enforced by + // nothing until a `plugins[]` entry provides it: no runtime mounts an + // enterprise provider from `requires` (`preflightProviderWiring`). + const capProviderWiring = await preflightProviderWiring({ + requires: (config as { requires?: unknown }).requires, + packages: packageEntries, + plugins: (config as { plugins?: unknown }).plugins, + projectDir: dirname(absolutePath), + }); + capProviderWarnings = [...capProviderPreflight.warnings, ...capProviderWiring].map((c) => ({ token: c.token, message: renderCapabilityMessage(c), })); diff --git a/packages/cli/src/commands/verify.ts b/packages/cli/src/commands/verify.ts index dc1cf4054a0..0250b1f3d80 100644 --- a/packages/cli/src/commands/verify.ts +++ b/packages/cli/src/commands/verify.ts @@ -43,10 +43,13 @@ import { authoringRulesFor } from '@objectstack/lint'; import { loadConfig, resolveConfigPath } from '../utils/config.js'; import { loadProjectEnvFiles } from '../utils/schema-migrate.js'; import { judgeAuthorTimeRules, VERIFY_RULE_COMMAND } from '../utils/author-time-rules.js'; +import { artifactPackages } from '../utils/artifact-packages.js'; +import { judgeDeclaredCapabilities } from '../utils/capability-preflight.js'; import { printError, printStep, printSuccess, + printWarning, printAuthoringRuleErrors, formatZodErrors, JSON_FULL_LIST_REMEDY, @@ -88,13 +91,26 @@ export function resolveVerifyMultiTenant(flags: { 'multi-tenant'?: boolean }): b return Boolean(flags['multi-tenant']) || postureEnforcesWall(resolveTenancyPosture()); } +/** + * One capability finding on `os verify --json`'s `capabilities`: the sentence + * `os validate` prints for it, and that door's verdict on it. Advisory on this + * command whatever `validate` says. + */ +export interface VerifyCapabilityAdvisory { + readonly token: string; + readonly message: string; + readonly validate: 'error' | 'warning'; +} + /** * `objectstack verify` — two stages, in order: * * 1. the author-time rules — the registry `os validate` runs, over the stack * prepared the way `os validate` prepares it (`utils/author-time-rules.ts`). * A gating finding fails the run with those findings, and stage 2 never - * starts (#21323); + * starts (#21323). Then the capability provider check `os validate` + * runs, reported as advisories that never change the exit code + * (`capabilities` on the `--json` face); * 2. boot the app in-process, with the project's `.env*` files loaded as * `os dev` loads them, and exercise it through the real HTTP stack, * asserting runtime behavior the static gates can't see: @@ -280,6 +296,7 @@ export default class Verify extends Command { // Stage 1 — the author-time rules, before anything boots. A failure here // exits inside the call; see `runAuthorTimeStage`. await this.runAuthorTimeStage(config as Record, absolutePath, flags.json); + const capabilities = await this.runCapabilityAdvisories(config as Record, absolutePath, flags.json); const multiTenant = resolveVerifyMultiTenant(flags); @@ -495,7 +512,7 @@ export default class Verify extends Command { // `emitJson`, not `this.log`: stdout is reserved (see `run()`), so the // report has to leave through the real stream — and awaiting the write // drains a report larger than one pipe buffer before `this.exit` below. - await emitJson({ app: crud.app, config: absolutePath, multiTenant, seed, crud, rls, referenceShapes, deleteBehaviors, uniqueScopes, parentWriteReach, dashboardWindows, hardFailures }); + await emitJson({ app: crud.app, config: absolutePath, multiTenant, capabilities, seed, crud, rls, referenceShapes, deleteBehaviors, uniqueScopes, parentWriteReach, dashboardWindows, hardFailures }); } else { this.log(formatReport(crud)); this.log(formatSeedReport(seed)); @@ -519,6 +536,45 @@ export default class Verify extends Command { this.exit(hardFailures > 0 ? 1 : 0); } + /** + * Stage 1, second half — the capability provider check `os validate` runs, + * reported as ADVISORIES. + * + * `os verify` used to run none of it, so a stack declaring a capability no + * provider here enforces passed green: `requires: ['hierarchy-security']` + * with no enterprise provider (the hierarchy scopes then run owner-only, + * silently), and every cloud-only token `os validate` refuses. Each finding + * is the sentence `os validate` prints for it, with `validate` naming that + * door's verdict (`error`: it refuses the stack; `warning`: it reports it). + * Advisory here by decision: this stage never changes `verify`'s exit code, + * for any token. The text face prints them; the `--json` face carries them + * as `capabilities`. + */ + private async runCapabilityAdvisories( + config: Record, + absolutePath: string, + json: boolean, + ): Promise { + if (!json) printStep('Checking that every required capability has a provider in this edition...'); + const judged = await judgeDeclaredCapabilities({ + requires: config.requires, + packages: artifactPackages(config), + plugins: config.plugins, + projectDir: dirname(absolutePath), + }); + const advisories: VerifyCapabilityAdvisory[] = [ + ...judged.errors.map((a) => ({ ...a, validate: 'error' as const })), + ...judged.warnings.map((a) => ({ ...a, validate: 'warning' as const })), + ]; + if (!json) { + for (const a of advisories) { + printWarning(a.validate === 'error' ? `${a.message} (\`os validate\` refuses this stack.)` : a.message); + } + if (advisories.length > 0) this.log(''); + } + return advisories; + } + /** * Stage 1 — the author-time rule registry `os validate` runs, over the stack * prepared the way `os validate` prepares it (#21323). diff --git a/packages/cli/src/utils/capability-preflight.ts b/packages/cli/src/utils/capability-preflight.ts index 62d7a23ba99..e346e1a9e69 100644 --- a/packages/cli/src/utils/capability-preflight.ts +++ b/packages/cli/src/utils/capability-preflight.ts @@ -2,6 +2,8 @@ import { createRequire } from 'node:module'; import path from 'node:path'; +import { providesCapability } from '@objectstack/core'; +import { createHostImporter, packageNameFromSpecifier } from '@objectstack/types/node'; import { classifyRequiredCapability, RETIRED_PLATFORM_CAPABILITY_GUIDANCE, @@ -76,17 +78,61 @@ export function renderCapabilityMessage(c: DeclaredCapabilityClassification): st return c.package === undefined ? text : `package '${c.package}' — ${text}`; } +/** + * What an `enterprise`-edition capability's metadata does while no provider is + * wired in, for the tokens whose effect has a concrete shape worth naming. + * + * WHICH tokens get a finding is never read from here: every token whose + * registry row (`PLATFORM_CAPABILITY_PROVIDERS`) carries `edition: 'enterprise'` + * gets one, and a token with no row here gets the generic sentence of + * {@link enterpriseAbsenceConsequence}. This table only sharpens the + * consequence. Every key is pinned to an enterprise-edition registry row in + * `capability-preflight.test.ts`, so a row cannot outlive its token. + */ +export const ENTERPRISE_ABSENCE_CONSEQUENCE: Readonly> = Object.freeze({ + // The sharing layer fails CLOSED without the `hierarchy-scope-resolver` + // service (`SharingService.resolveOwnerScopeIds`, ADR-0057): a hierarchy + // scope never widens, and nothing logs it. + 'hierarchy-security': + "the hierarchy scopes (`own_and_reports`, `unit`, `unit_and_below`) behave as owner-only", +}); + +/** + * The consequence sentence for an `enterprise` token with no provider wired in. + * It names the edition that enforces the token and what the open edition does + * instead, and nothing else: no product pitch, one fact an author can act on. + */ +export function enterpriseAbsenceConsequence(token: string): string { + const shape = Object.prototype.hasOwnProperty.call(ENTERPRISE_ABSENCE_CONSEQUENCE, token) + ? ENTERPRISE_ABSENCE_CONSEQUENCE[token] + : `nothing provides "${token}", and the metadata that relies on it is not enforced`; + return `Only the enterprise edition enforces it: without a wired provider, as on the open edition, ${shape}, and no log line says so.`; +} + /** {@link renderCapabilityMessage} without the package prefix. */ -function renderTokenMessage(c: CapabilityClassification): string { +function renderTokenMessage(c: DeclaredCapabilityClassification): string { const p = c.provider; + if (c.wiring !== undefined && p?.package) { + const note = p.note ? ` (${p.note})` : ''; + const found = + c.wiring.state === 'unloadable' + ? `${p.package} resolves here, but it could not be loaded to check \`plugins[]\` (${c.wiring.error})` + : `${p.package} is installed, but no entry of \`plugins[]\` comes from it, and nothing mounts an enterprise provider on its own`; + return ( + `Capability "${c.token}" is provided by ${p.package}${note}. ${found}. ` + + `${enterpriseAbsenceConsequence(c.token)} ` + + `Add its plugin to \`plugins[]\`, or remove "${c.token}" from \`requires\`.` + ); + } switch (c.status) { case 'installable': { const pkg = p!.package!; if (p!.edition === 'enterprise') { const note = p!.note ? ` (${p!.note})` : ''; return ( - `Capability "${c.token}" is provided by ${pkg}${note}. ` + - `Run \`pnpm add ${pkg}\` and add it to \`plugins[]\`, or remove "${c.token}" from \`requires\`.` + `Capability "${c.token}" is provided by ${pkg}${note}, which is not installed. ` + + `${enterpriseAbsenceConsequence(c.token)} ` + + `Install ${pkg} and add its plugin to \`plugins[]\`, or remove "${c.token}" from \`requires\`.` ); } return ( @@ -166,6 +212,14 @@ export function preflightRequiredCapabilities(opts: { */ export interface DeclaredCapabilityClassification extends CapabilityClassification { readonly package?: string; + /** + * Set only by {@link preflightProviderWiring}: an `enterprise` token whose + * provider package resolves (`status: 'ok'`) but which no `plugins[]` entry + * provides (`unwired`), or whose package could not be loaded to tell + * (`unloadable`). Nothing mounts an enterprise provider from `requires`, so + * a resolvable package alone enforces nothing. + */ + readonly wiring?: { readonly state: 'unwired' } | { readonly state: 'unloadable'; readonly error: string }; } /** {@link CapabilityPreflightResult}, each finding attributed to where it was declared. */ @@ -230,6 +284,153 @@ export function preflightDeclaredCapabilities(opts: { return { errors, warnings }; } +// ── Wiring (enterprise providers are mounted from `plugins[]` only) ───────── + +/** Loads a provider package's module the way the served app would reach it. */ +export type ProviderModuleLoader = (pkg: string) => Promise; + +/** + * The default {@link ProviderModuleLoader}: `serve`'s host-anchored importer + * (`createHostImporter`, the app's own declaration first), falling back to + * this package's module graph. Loading a module runs it, so this is only ever + * called for a token whose package already resolved. + */ +export function makeProviderModuleLoader(projectDir: string): ProviderModuleLoader { + return createHostImporter(projectDir, { + fallbackImport: (specifier) => import(/* webpackIgnore: true */ specifier), + }); +} + +/** Names of the functions a module exports (its classes), the identities `providesCapability` matches. */ +function exportedFunctionNames(mod: unknown): string[] { + const names = new Set(); + const visit = (bag: unknown) => { + if (!bag || (typeof bag !== 'object' && typeof bag !== 'function')) return; + for (const value of Object.values(bag as Record)) { + if (typeof value === 'function' && value.name) names.add(value.name); + } + }; + visit(mod); + visit((mod as { default?: unknown } | null | undefined)?.default); + return [...names]; +} + +/** + * The `enterprise` tokens a stack declares whose provider package RESOLVES, + * but which no `plugins[]` entry provides. + * + * {@link preflightDeclaredCapabilities} asks only whether a token's package + * can be resolved. For an `open` token that is the whole question, because + * `os serve` mounts the provider from `requires` itself. For an `enterprise` + * token it is not: no runtime in this repository mounts an enterprise provider + * from `requires` (`serve`'s resolver has no row for one), so the app must wire + * the plugin into `plugins[]`, and a package that resolves but is not wired + * enforces nothing. Which tokens are `enterprise` is the registry's edition + * tag, never a list here. + * + * A `plugins[]` entry provides the token when it is an instance whose class (or + * `name`) is one the provider package exports, the exact identity match + * `serve` uses (`providesCapability`), or a string entry naming that package. + * A package that resolves but cannot be loaded is reported as such, never + * read as wired. + * + * @param opts.plugins - The stack's top-level `plugins` (`plugins[]` is a + * host-level array; package bodies carry none). + */ +export async function preflightProviderWiring(opts: { + requires: unknown; + packages: ReadonlyArray<{ readonly id: string; readonly body: Record }>; + plugins: unknown; + projectDir: string; + /** Injectable for tests; defaults to on-disk `require.resolve` resolution. */ + isInstalled?: (pkg: string) => boolean; + /** Injectable for tests; defaults to {@link makeProviderModuleLoader}. */ + loadModule?: ProviderModuleLoader; +}): Promise { + const isInstalled = opts.isInstalled ?? makeProviderResolver(opts.projectDir); + const loadModule = opts.loadModule ?? makeProviderModuleLoader(opts.projectDir); + const plugins = Array.isArray(opts.plugins) ? opts.plugins : []; + + // Same rule as `preflightDeclaredCapabilities`: a top-level `requires` wins; + // otherwise each package body's, attributed to its package. + const sources: Array<{ tokens: unknown[]; package?: string }> = + Array.isArray(opts.requires) || opts.packages.length === 0 + ? [{ tokens: Array.isArray(opts.requires) ? opts.requires : [] }] + : opts.packages.map((p) => ({ + tokens: Array.isArray(p.body.requires) ? (p.body.requires as unknown[]) : [], + package: p.id, + })); + + const verdicts = new Map>(); + const judge = (pkg: string) => { + let v = verdicts.get(pkg); + if (!v) { + v = (async () => { + const named = plugins.some( + (entry) => typeof entry === 'string' && packageNameFromSpecifier(entry) === pkg, + ); + if (named) return undefined; + let mod: unknown; + try { + mod = await loadModule(pkg); + } catch (err) { + return { state: 'unloadable' as const, error: err instanceof Error ? err.message : String(err) }; + } + return providesCapability(plugins, exportedFunctionNames(mod)) ? undefined : { state: 'unwired' as const }; + })(); + verdicts.set(pkg, v); + } + return v; + }; + + const found: DeclaredCapabilityClassification[] = []; + for (const source of sources) { + const seen = new Set(); + for (const token of source.tokens) { + if (typeof token !== 'string' || seen.has(token)) continue; + seen.add(token); + const c = classifyRequiredCapability(token, isInstalled); + if (c.status !== 'ok' || c.provider?.edition !== 'enterprise' || !c.provider.package) continue; + const wiring = await judge(c.provider.package); + if (wiring) found.push(source.package === undefined ? { ...c, wiring } : { ...c, package: source.package, wiring }); + } + } + return found; +} + +/** One capability advisory as `os validate --json` and `os verify --json` carry it. */ +export interface CapabilityAdvisory { + readonly token: string; + readonly message: string; +} + +/** + * Every capability finding for a stack, in one list: the resolution preflight's + * errors and warnings, then the wiring findings. `os verify` reports all of + * them as advisories (its exit code does not read them); `os serve` prints + * them at start-up. + */ +export async function judgeDeclaredCapabilities(opts: { + requires: unknown; + packages: ReadonlyArray<{ readonly id: string; readonly body: Record }>; + plugins: unknown; + projectDir: string; + isInstalled?: (pkg: string) => boolean; + loadModule?: ProviderModuleLoader; +}): Promise<{ errors: CapabilityAdvisory[]; warnings: CapabilityAdvisory[] }> { + const isInstalled = opts.isInstalled ?? makeProviderResolver(opts.projectDir); + const resolution = preflightDeclaredCapabilities({ ...opts, isInstalled }); + const wiring = await preflightProviderWiring({ ...opts, isInstalled }); + const advise = (c: DeclaredCapabilityClassification): CapabilityAdvisory => ({ + token: c.token, + message: renderCapabilityMessage(c), + }); + return { + errors: resolution.errors.map(advise), + warnings: [...resolution.warnings, ...wiring].map(advise), + }; +} + /** * The fatal one-line message `os serve` throws when a DECLARED capability's * provider import fails as module-not-found. The package is already confirmed diff --git a/packages/cli/test/capability-edition-advisory.test.ts b/packages/cli/test/capability-edition-advisory.test.ts new file mode 100644 index 00000000000..0a1d8b010b1 --- /dev/null +++ b/packages/cli/test/capability-edition-advisory.test.ts @@ -0,0 +1,165 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// test-budget: 50 — spawns the real producer once per single-cause fixture: four spawns of the source CLI, one per distinct (command, fixture) pair (`os validate --json` and `os verify --json` on the open-edition stack and on the same stack with its enterprise provider wired), the two verify spawns each booting the app; local reading 39.92 s file duration, 25.00 s in tests (shared box, under the verify lock), x 1.25, rounded up + +/** + * PIN — a stack that declares an `enterprise` capability with no provider + * wired in is NAMED, with what the open edition does instead, by `os validate` + * AND `os verify`; the same stack with the provider in `plugins[]` gets no + * finding from either. + * + * ## The defect + * + * `requires: ['hierarchy-security']` plus a `readScope: 'unit_and_below'` + * grant, on the open edition: `defineStack` accepts it (the token is declared), + * the sharing layer has no `hierarchy-scope-resolver` and falls back to + * owner-only without a log line, and `os verify` ran no capability check at + * all, so its `--json` report was green and said nothing. `os validate` named + * the package but not the consequence. + * + * ## What is pinned + * + * - the open-edition stack: `os validate --json` carries the token under + * `warnings` and `os verify --json` under `capabilities`, both naming the + * owner-only fallback, and both exit 0 (advisory, by decision); + * - the control: the same stack with a package of the provider's name, + * declared and resolvable, whose exported plugin class is in `plugins[]`, + * gets no capability finding from either door. Without it, a door that + * reported every enterprise token whatever was wired would pass the first + * half. + * + * Spawned rather than run in-process: the `--json` document and the exit code + * are the contract an agent reads, and only a real process produces them. The + * per-token battery (every `enterprise` and `cloud` registry row) is unit-level, + * in `capability-preflight.test.ts`. + */ + +import { describe, expect, it, beforeAll, afterAll } from 'vitest'; +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { CLI, childEnv } from './helpers/serve-process.js'; +import { defineStackSourceFromLiteral, linkSpec } from './helpers/define-stack-fixture.js'; + +const TOKEN = 'hierarchy-security'; +const PROVIDER = '@objectstack/security-enterprise'; + +/** The stack: one private object, one grant at a hierarchy depth, the token declared. */ +function stackLiteral(wired: boolean): string { + return `{ + manifest: { id: 'com.example.edition-advisory', namespace: 'ea', version: '1.0.0', name: 'Edition Advisory', type: 'app', engines: { protocol: '^18' } }, + requires: ['${TOKEN}'],${wired ? '\n plugins: [new FixtureProviderPlugin()],' : ''} + objects: [ + { name: 'ea_note', label: 'Note', pluralLabel: 'Notes', sharingModel: 'private', fields: { title: { type: 'text', label: 'Title' } } }, + ], + permissions: [ + { name: 'ea_member', label: 'Member', objects: { ea_note: { allowRead: true, allowCreate: true, allowEdit: true, readScope: 'unit_and_below' } } }, + ], +}`; +} + +/** + * A package under the provider's name, declared by the fixture app and + * resolvable from it, exporting one plugin class that does nothing. It stands + * in for the closed-source provider: what the doors judge is whether + * `plugins[]` holds a class that package exports, never what the plugin does. + */ +function writeProviderPackage(dir: string): void { + const root = join(dir, 'node_modules', ...PROVIDER.split('/')); + mkdirSync(root, { recursive: true }); + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ name: PROVIDER, version: '0.0.0-fixture', type: 'module', exports: { '.': './index.js' } }), + ); + writeFileSync( + join(root, 'index.js'), + "export class FixtureProviderPlugin {\n name = 'fixture.enterprise-provider';\n version = '0.0.0';\n async init() {}\n async start() {}\n}\n", + ); +} + +function projectDir(wired: boolean): string { + const dir = mkdtempSync(join(tmpdir(), `os-edition-advisory-${wired ? 'wired' : 'open'}-`)); + writeFileSync( + join(dir, 'package.json'), + JSON.stringify({ + name: 'edition-advisory-fixture', + private: true, + type: 'module', + ...(wired ? { dependencies: { [PROVIDER]: '0.0.0-fixture' } } : {}), + }), + ); + const source = defineStackSourceFromLiteral(stackLiteral(wired)); + writeFileSync( + join(dir, 'objectstack.config.mjs'), + wired ? `import { FixtureProviderPlugin } from '${PROVIDER}';\n${source}` : source, + ); + if (wired) writeProviderPackage(dir); + linkSpec(dir); + return dir; +} + +interface Run { + status: number | null; + stdout: string; + stderr: string; +} + +function runCli(dir: string, args: string[]): Run { + // `bin/run-dev.js` runs this checkout's `src/` through tsx, never `dist/`. + const r = spawnSync(process.execPath, [CLI, ...args], { + cwd: dir, + encoding: 'utf8', + env: childEnv({ NO_COLOR: '1' }), + maxBuffer: 64 * 1024 * 1024, + }); + return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' }; +} + +type Finding = { token?: string; message?: string }; + +/** The capability findings of one `--json` document: validate's `warnings`/`errors`, verify's `capabilities`. */ +function capabilityFindings(doc: Record): Finding[] { + const lists = [doc.warnings, doc.errors, doc.capabilities].filter(Array.isArray) as unknown[][]; + return lists.flat().filter((f): f is Finding => typeof (f as Finding)?.token === 'string'); +} + +describe('os validate and os verify name an enterprise capability no provider enforces', () => { + let open: string; + let wired: string; + + beforeAll(() => { + open = projectDir(false); + wired = projectDir(true); + }); + + afterAll(() => { + for (const dir of [open, wired]) if (dir) rmSync(dir, { recursive: true, force: true }); + }); + + it('the open-edition stack: both `--json` documents name the token and the owner-only fallback, exit 0', () => { + const validate = runCli(open, ['validate', '--json']); + expect(validate.status, `os validate --json:\n${validate.stdout}\n${validate.stderr}`).toBe(0); + const fromValidate = capabilityFindings(JSON.parse(validate.stdout)); + expect(fromValidate.map((f) => f.token)).toEqual([TOKEN]); + expect(fromValidate[0].message).toContain('owner-only'); + + const verify = runCli(open, ['verify', '--json']); + expect(verify.status, `os verify --json:\n${verify.stdout}\n${verify.stderr}`).toBe(0); + const verifyDoc = JSON.parse(verify.stdout) as Record; + expect(verifyDoc.capabilities).toEqual([ + { token: TOKEN, message: fromValidate[0].message, validate: 'warning' }, + ]); + }, 180_000); + + it('the control: the provider wired into `plugins[]` gets no capability finding from either door', () => { + const validate = runCli(wired, ['validate', '--json']); + expect(validate.status, `os validate --json:\n${validate.stdout}\n${validate.stderr}`).toBe(0); + expect(capabilityFindings(JSON.parse(validate.stdout))).toEqual([]); + + const verify = runCli(wired, ['verify', '--json']); + expect(verify.status, `os verify --json:\n${verify.stdout}\n${verify.stderr}`).toBe(0); + const verifyDoc = JSON.parse(verify.stdout) as Record; + // Present and empty: the stage ran and found nothing, not "never ran". + expect(verifyDoc.capabilities).toEqual([]); + }, 180_000); +}); diff --git a/packages/cli/test/capability-preflight.test.ts b/packages/cli/test/capability-preflight.test.ts index 5157d2b0767..f575069aac8 100644 --- a/packages/cli/test/capability-preflight.test.ts +++ b/packages/cli/test/capability-preflight.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from 'vitest'; import { + ENTERPRISE_ABSENCE_CONSEQUENCE, + judgeDeclaredCapabilities, preflightDeclaredCapabilities, + preflightProviderWiring, preflightRequiredCapabilities, renderCapabilityMessage, missingProviderMessage, @@ -84,7 +87,7 @@ describe('renderCapabilityMessage (#3366)', () => { it('enterprise provider hint names plugins[] wiring AND carries the edition boundary', () => { const m = msgFor('hierarchy-security', () => false); - expect(m).toContain('pnpm add @objectstack/security-enterprise'); + expect(m).toContain('Install @objectstack/security-enterprise'); expect(m).toContain('plugins[]'); // #10921 — this `pnpm add` names a package this repo does not build and that // is not publicly resolvable; it is followable only by a licensee. What keeps @@ -225,3 +228,176 @@ describe('makeProviderResolver — real on-disk resolution', () => { expect(isInstalled('@objectstack/this-package-does-not-exist')).toBe(false); }); }); + +// ── Enterprise / cloud capability findings (validate, verify, serve) ─────── +// +// Which tokens get a finding is the registry's edition tag, so the battery is +// DERIVED from `PLATFORM_CAPABILITY_PROVIDERS` and floored: a registry that +// lost its non-open rows would otherwise run zero cases and stay green. + +const NON_OPEN_TOKENS = Object.entries(PLATFORM_CAPABILITY_PROVIDERS) + .filter(([, p]) => p.edition !== 'open') + .map(([token, p]) => ({ token, edition: p.edition, pkg: p.package })); + +/** The provider package's module, as a loader hands it back: one exported plugin class. */ +class FixtureProviderPlugin { + name = 'fixture.enterprise-provider'; + async init() {} +} +class UnrelatedPlugin { + name = 'fixture.unrelated'; + async init() {} +} +const providerModule = { FixtureProviderPlugin, someHelper: () => 1 }; + +describe('enterprise and cloud registry tokens — one case per token', () => { + it('the battery is the registry, and it is not empty', () => { + // Today: one `enterprise` row and six `cloud` rows. A floor, not a total. + expect(NON_OPEN_TOKENS.filter((t) => t.edition === 'enterprise').length).toBeGreaterThanOrEqual(1); + expect(NON_OPEN_TOKENS.filter((t) => t.edition === 'cloud').length).toBeGreaterThanOrEqual(6); + }); + + for (const { token, edition, pkg } of NON_OPEN_TOKENS) { + it(`${token} (${edition}): no provider here ⇒ exactly one finding naming it`, async () => { + const r = await judgeDeclaredCapabilities({ + requires: [token], + packages: [], + plugins: [], + projectDir: '/tmp/nowhere', + isInstalled: () => false, + loadModule: async () => providerModule, + }); + const all = [...r.errors, ...r.warnings]; + expect(all.map((a) => a.token)).toEqual([token]); + // `os validate`'s verdict per edition, unchanged: a cloud token has no + // version here at all (refused); an enterprise token is installable. + if (edition === 'cloud') expect(r.errors.map((a) => a.token)).toEqual([token]); + else expect(r.warnings.map((a) => a.token)).toEqual([token]); + if (pkg) expect(all[0].message).toContain(pkg); + }); + + it(`${token} (${edition}): the provider present ⇒ no finding, unless no package can exist`, async () => { + const r = await judgeDeclaredCapabilities({ + requires: [token], + packages: [], + plugins: [new FixtureProviderPlugin()], + projectDir: '/tmp/nowhere', + isInstalled: () => true, + loadModule: async () => providerModule, + }); + const all = [...r.errors, ...r.warnings]; + // A cloud tier with no package has no provider to be present: it is + // still reported, the case `os validate` refuses. + expect(all.map((a) => a.token)).toEqual(pkg === null ? [token] : []); + }); + } +}); + +describe('preflightProviderWiring — an enterprise package that resolves is not yet a provider', () => { + const ENTERPRISE = NON_OPEN_TOKENS.filter((t) => t.edition === 'enterprise'); + const wiring = (plugins: unknown, loadModule = async (_pkg: string): Promise => providerModule) => + preflightProviderWiring({ + requires: ENTERPRISE.map((t) => t.token), + packages: [], + plugins, + projectDir: '/tmp/nowhere', + isInstalled: () => true, + loadModule, + }); + + it('installed, `plugins[]` empty ⇒ one `unwired` finding per enterprise token', async () => { + const found = await wiring([]); + expect(found.map((c) => [c.token, c.wiring?.state])).toEqual(ENTERPRISE.map((t) => [t.token, 'unwired'])); + }); + + it('installed, `plugins[]` holds only an unrelated plugin ⇒ still unwired', async () => { + const found = await wiring([new UnrelatedPlugin()]); + expect(found.map((c) => c.wiring?.state)).toEqual(ENTERPRISE.map(() => 'unwired')); + }); + + it('an instance of a class the package exports ⇒ wired, no finding', async () => { + expect(await wiring([new UnrelatedPlugin(), new FixtureProviderPlugin()])).toEqual([]); + }); + + it('a string `plugins[]` entry naming the package ⇒ wired, and the package is never loaded', async () => { + let loads = 0; + const entries = ENTERPRISE.map((t) => t.pkg as string); + const found = await wiring(entries, async () => { + loads++; + return providerModule; + }); + expect(found).toEqual([]); + expect(loads).toBe(0); + }); + + it('a package that resolves but cannot be loaded ⇒ `unloadable`, never read as wired', async () => { + const found = await wiring([new FixtureProviderPlugin()], async () => { + throw new Error('boom at import'); + }); + expect(found.map((c) => c.wiring)).toEqual(ENTERPRISE.map(() => ({ state: 'unloadable', error: 'boom at import' }))); + expect(renderCapabilityMessage(found[0])).toContain('boom at import'); + }); + + it('a package that does not resolve is the resolution preflight\'s finding, not this one', async () => { + const found = await preflightProviderWiring({ + requires: ENTERPRISE.map((t) => t.token), + packages: [], + plugins: [], + projectDir: '/tmp/nowhere', + isInstalled: () => false, + loadModule: async () => providerModule, + }); + expect(found).toEqual([]); + }); + + it('a per-package `requires` attributes the finding to that package', async () => { + const token = ENTERPRISE[0].token; + const found = await preflightProviderWiring({ + requires: undefined, + packages: [{ id: 'com.example.one', body: { requires: [token] } }], + plugins: [], + projectDir: '/tmp/nowhere', + isInstalled: () => true, + loadModule: async () => providerModule, + }); + expect(found.map((c) => [c.package, c.token])).toEqual([['com.example.one', token]]); + expect(renderCapabilityMessage(found[0])).toMatch(/^package 'com\.example\.one' — /); + }); + + it('open and cloud tokens never reach the wiring check', async () => { + const found = await preflightProviderWiring({ + requires: ['automation', ...NON_OPEN_TOKENS.filter((t) => t.edition === 'cloud').map((t) => t.token)], + packages: [], + plugins: [], + projectDir: '/tmp/nowhere', + isInstalled: () => true, + loadModule: async () => providerModule, + }); + expect(found).toEqual([]); + }); +}); + +describe('the enterprise consequence sentence', () => { + it('every consequence row keys an enterprise-edition registry token', () => { + for (const token of Object.keys(ENTERPRISE_ABSENCE_CONSEQUENCE)) { + expect(PLATFORM_CAPABILITY_PROVIDERS[token]?.edition, token).toBe('enterprise'); + } + }); + + it('hierarchy-security names the owner-only fallback, absent and unwired alike', async () => { + const absent = renderCapabilityMessage(classifyRequiredCapability('hierarchy-security', () => false)); + const [unwired] = await preflightProviderWiring({ + requires: ['hierarchy-security'], + packages: [], + plugins: [], + projectDir: '/tmp/nowhere', + isInstalled: () => true, + loadModule: async () => providerModule, + }); + for (const m of [absent, renderCapabilityMessage(unwired)]) { + expect(m).toContain('owner-only'); + expect(m).toContain('enterprise edition'); + expect(m).toContain('plugins[]'); + } + }); +}); diff --git a/packages/cli/test/normalized-call-sites.test.ts b/packages/cli/test/normalized-call-sites.test.ts index a7a761849bb..62970387dbc 100644 --- a/packages/cli/test/normalized-call-sites.test.ts +++ b/packages/cli/test/normalized-call-sites.test.ts @@ -428,6 +428,10 @@ const READS: Readonly> = { reads: 'top-level', why: 'as in compile.ts.', }, + 'commands/verify.ts :: config.requires': { + reads: 'top-level', + why: 'as in compile.ts: handed to `judgeDeclaredCapabilities` beside `artifactPackages(config)`, which applies the same top-level-else-bodies rule for the capability advisories.', + }, // ── os diff / os doctor / os generate / os migrate meta (#22288) ─────── 'commands/diff.ts :: beforeConfig': { reads: 'resolved', diff --git a/packages/cli/test/validate-build-gate-parity.test.ts b/packages/cli/test/validate-build-gate-parity.test.ts index 4303cb43663..e2ee274b440 100644 --- a/packages/cli/test/validate-build-gate-parity.test.ts +++ b/packages/cli/test/validate-build-gate-parity.test.ts @@ -60,6 +60,9 @@ const SHARED_NON_REGISTRY_GATES: readonly string[] = [ // or each `packages[]` body by name — so the row names the stack-level entry // both doors call, not the per-list classifier it runs. 'preflightDeclaredCapabilities', + // An `enterprise` token whose package resolves but which no `plugins[]` + // entry provides: an advisory at both doors, never a refusal. + 'preflightProviderWiring', // [#3786] The pre-parse undeclared-key diff, both halves. 'lintUnknownStackKeys', 'lintUnknownAuthoringKeys',