From 54251175d8e011b6ba18aca5b182235d53287f4a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:06:57 +0000 Subject: [PATCH 1/6] feat(spec): a book audience can name a capability, so Setup and Studio docs open only for callers who can open those apps Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgV8bjXeBN9N25FTesc --- packages/apps/setup/src/index.ts | 5 ++ packages/apps/setup/src/setup-manual.book.ts | 27 +++++++ packages/apps/studio/src/index.ts | 5 ++ .../apps/studio/src/studio-manual.book.ts | 23 ++++++ packages/rest/src/meta-item-read-gate.ts | 80 +++++++++++++++---- .../runtime/src/domains/mcp-package-docs.ts | 20 ++++- packages/spec/src/system/book.zod.ts | 42 ++++++++-- 7 files changed, 173 insertions(+), 29 deletions(-) create mode 100644 packages/apps/setup/src/setup-manual.book.ts create mode 100644 packages/apps/studio/src/studio-manual.book.ts diff --git a/packages/apps/setup/src/index.ts b/packages/apps/setup/src/index.ts index 3af7176fbdf..2240cdbe3f7 100644 --- a/packages/apps/setup/src/index.ts +++ b/packages/apps/setup/src/index.ts @@ -18,6 +18,7 @@ import { SETUP_APP, SETUP_NAV_CONTRIBUTIONS } from '@objectstack/platform-objects/apps'; import { SETUP_OVERVIEW_DOC } from './setup-overview.doc.js'; +import { SETUP_MANUAL_BOOK } from './setup-manual.book.js'; export const SETUP_APP_PACKAGE_ID = 'com.objectstack.setup'; export const SETUP_APP_NAMESPACE = 'setup'; @@ -60,6 +61,9 @@ export class SetupAppPlugin { navigationContributions: SETUP_NAV_CONTRIBUTIONS, // ADR-0046 package docs — grouped under "Setup" at /_console/docs. docs: [SETUP_OVERVIEW_DOC], + // ADR-0046 §6.7 — the manual claiming those docs, read only by the + // callers who may open the Setup app (its `audience`). + books: [SETUP_MANUAL_BOOK], }); } } @@ -71,3 +75,4 @@ export function createSetupAppPlugin(): SetupAppPlugin { export { SETUP_APP, SETUP_NAV_CONTRIBUTIONS }; export { SETUP_OVERVIEW_DOC }; +export { SETUP_MANUAL_BOOK }; diff --git a/packages/apps/setup/src/setup-manual.book.ts b/packages/apps/setup/src/setup-manual.book.ts new file mode 100644 index 00000000000..5f55f27095e --- /dev/null +++ b/packages/apps/setup/src/setup-manual.book.ts @@ -0,0 +1,27 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { Book } from '@objectstack/spec/system'; + +/** + * The Setup app's manual (ADR-0046 §6), registered beside its docs. + * + * Its job is the `audience`: Setup's pages are administrator help, so they are + * read by exactly the callers who may open the Setup app — whoever holds + * `setup.access` (the app's `requiredPermissions`), through ANY permission set + * (`organization_admin`, `admin_full_access`, a delegated-admin set an + * application authors). A `{ permissionSet }` audience would name one of + * those sets and shut out the holders of every other one. + * + * Membership is derived (`include: '*'` over this package's own docs), so a + * page this package adds later is gated the same way with no edit here. + * Without a book claiming them, the docs fall back to `org` (§3.6): listed + * only to admins by the Console's docs index, but readable at their address, + * and through `?include=content`, by every member. + */ +export const SETUP_MANUAL_BOOK: Book = { + name: 'setup_manual', + label: 'Setup', + slug: 'setup', + audience: { systemPermission: 'setup.access' }, + groups: [{ key: 'all', label: 'Documentation', include: '*' }], +}; diff --git a/packages/apps/studio/src/index.ts b/packages/apps/studio/src/index.ts index a03872c50f6..5b097f95976 100644 --- a/packages/apps/studio/src/index.ts +++ b/packages/apps/studio/src/index.ts @@ -28,6 +28,7 @@ import { STUDIO_APP } from '@objectstack/platform-objects/apps'; import { STUDIO_OVERVIEW_DOC } from './studio-overview.doc.js'; +import { STUDIO_MANUAL_BOOK } from './studio-manual.book.js'; export const STUDIO_APP_PACKAGE_ID = 'com.objectstack.studio'; export const STUDIO_APP_NAMESPACE = 'studio'; @@ -72,6 +73,9 @@ export class StudioAppPlugin { apps: [STUDIO_APP], // ADR-0046 package docs — grouped under "Studio" at /_console/docs. docs: [STUDIO_OVERVIEW_DOC], + // ADR-0046 §6.7 — the manual claiming those docs, read only by the + // callers who may open the Studio app (its `audience`). + books: [STUDIO_MANUAL_BOOK], }); } } @@ -83,3 +87,4 @@ export function createStudioAppPlugin(): StudioAppPlugin { export { STUDIO_APP }; export { STUDIO_OVERVIEW_DOC }; +export { STUDIO_MANUAL_BOOK }; diff --git a/packages/apps/studio/src/studio-manual.book.ts b/packages/apps/studio/src/studio-manual.book.ts new file mode 100644 index 00000000000..15efc8c880a --- /dev/null +++ b/packages/apps/studio/src/studio-manual.book.ts @@ -0,0 +1,23 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { Book } from '@objectstack/spec/system'; + +/** + * The Studio app's manual (ADR-0046 §6), registered beside its docs. + * + * Its job is the `audience`: Studio's pages are builder help, so they are read + * by exactly the callers who may open the Studio app — whoever holds + * `studio.access` (the app's `requiredPermissions`), through ANY permission + * set. A `{ permissionSet }` audience would name one set and shut out the + * holders of every other one. + * + * Membership is derived (`include: '*'` over this package's own docs), so a + * page this package adds later is gated the same way with no edit here. + */ +export const STUDIO_MANUAL_BOOK: Book = { + name: 'studio_manual', + label: 'Studio', + slug: 'studio', + audience: { systemPermission: 'studio.access' }, + groups: [{ key: 'all', label: 'Documentation', include: '*' }], +}; diff --git a/packages/rest/src/meta-item-read-gate.ts b/packages/rest/src/meta-item-read-gate.ts index fae5b4840e6..4783a899d45 100644 --- a/packages/rest/src/meta-item-read-gate.ts +++ b/packages/rest/src/meta-item-read-gate.ts @@ -146,6 +146,17 @@ export interface MetaReadGateAudienceSources { * gated audiences DENY (ADR-0049). */ resolveSecurityService(): Promise; + /** + * [ADR-0046 §6.7] The capabilities a `{ systemPermission }` book audience + * reads, when the transport's holdings caller is NOT the request's own + * caller (the MCP docs door's delegated agent envelope, whose audience + * reads the delegating person's grants). Absent: the caller's own + * `systemPermissions` ({@link resolveCaller}), the list every + * `requiredPermissions` arm of this gate reads. A rejection, or an answer + * that is not a list, is read as "holdings unresolvable", so those + * audiences DENY (ADR-0049). + */ + resolveAudienceSystemPermissions?(): Promise; /** * [#30126 row 12] The deployment's `errors.*` override lookup (an * `II18nService.t`-compatible function), or `undefined` when there is none — @@ -412,11 +423,11 @@ export type NavServabilityGate = (objectName: string, entry: any, appName: strin * cannot drift apart — there is no second resolver to drift. */ export interface DocsAudience { - /** The caller as the audience helpers see it (holdings resolved only when a `{ permissionSet }` book exists). */ + /** The caller as the audience helpers see it (holdings resolved only when a `{ permissionSet }` or `{ systemPermission }` book exists). */ readonly caller: AudienceCaller; /** - * The fast path: an authenticated caller and no `{ permissionSet }` book - * anywhere, so every doc's effective audience (`org` / `public`) admits + * The fast path: an authenticated caller and no `{ permissionSet }` or + * `{ systemPermission }` book anywhere, so every doc's effective audience (`org` / `public`) admits * them and no doc corpus is needed to say so. */ readonly allReadable: boolean; @@ -570,6 +581,14 @@ export function anyPermissionSetAudience(books: readonly any[]): boolean { ); } +/** Whether any of these books carries a `{ systemPermission }` audience (ADR-0046 §6.7). */ +export function anySystemPermissionAudience(books: readonly any[]): boolean { + return books.some( + (b) => b && typeof b === 'object' && b.audience && typeof b.audience === 'object' + && typeof b.audience.systemPermission === 'string', + ); +} + /** Coerce a getMetaItems result (array | {items}) into an array. */ export function metaItemsArray(raw: unknown): any[] { if (Array.isArray(raw)) return raw; @@ -687,24 +706,45 @@ export async function fetchAudienceBooks(source: MetaReadGateListSource): Promis * permission-set-gated audiences (fail closed, ADR-0049). Resolution is * skipped unless `needPermissionSets` — callers pass true only when a * `{ permissionSet }` audience is actually in play. + * + * `systemPermissions` (asked only with `needSystemPermissions`, when a + * `{ systemPermission }` audience is in play) is the caller's own + * capability list — the one {@link holdsRequiredPermissions} reads for an + * app's `requiredPermissions`, so a manual gated on `setup.access` opens for + * exactly the callers the Setup app opens for — unless the transport names + * other holdings ({@link MetaReadGateAudienceSources.resolveAudienceSystemPermissions}). + * Not a list, or a rejecting read: undefined, and those audiences deny. */ export async function resolveAudienceCaller( sources: MetaReadGateAudienceSources, - opts: { needPermissionSets: boolean }, -): Promise<{ authenticated: boolean; permissionSets?: string[] }> { + opts: { needPermissionSets: boolean; needSystemPermissions?: boolean }, +): Promise<{ authenticated: boolean; permissionSets?: string[]; systemPermissions?: string[] }> { const ctx = await sources.resolveCaller(); const authenticated = !!ctx?.userId; - if (!authenticated || !opts.needPermissionSets) { - return { authenticated }; + if (!authenticated) return { authenticated }; + const caller: { authenticated: boolean; permissionSets?: string[]; systemPermissions?: string[] } = { authenticated }; + if (opts.needSystemPermissions) { + try { + const held = sources.resolveAudienceSystemPermissions + ? await sources.resolveAudienceSystemPermissions() + : ctx?.systemPermissions; + if (Array.isArray(held)) { + caller.systemPermissions = held.filter((p): p is string => typeof p === 'string'); + } + } catch { + // unresolved holdings → `{ systemPermission }` audiences deny + } } + if (!opts.needPermissionSets) return caller; try { const svc = await sources.resolveSecurityService(); - if (!svc || typeof svc.resolvePermissionSetNames !== 'function') return { authenticated }; + if (!svc || typeof svc.resolvePermissionSetNames !== 'function') return caller; const names = await svc.resolvePermissionSetNames(ctx); - return { authenticated, permissionSets: Array.isArray(names) ? names : [] }; + caller.permissionSets = Array.isArray(names) ? names : []; } catch { - return { authenticated }; // unresolved holdings → gated audiences deny + // unresolved holdings → gated audiences deny } + return caller; } /** @@ -718,11 +758,12 @@ export async function resolveAudienceCaller( * `resolveDocAudiences`, `docAudienceAllows`, `resolveBookTree`, * `deriveImplicitPackageBook`). * - * Holdings are resolved only when a `{ permissionSet }` book exists, and - * unresolvable holdings deny those audiences ({@link resolveAudienceCaller}, - * fail closed per ADR-0049). The fast path is the doc list's own: with no - * such book, an authenticated caller reads every doc, so `docReader` needs - * no corpus and `readableTree` filters nothing. + * Holdings are resolved only when a `{ permissionSet }` or + * `{ systemPermission }` book exists, and unresolvable holdings deny those + * audiences ({@link resolveAudienceCaller}, fail closed per ADR-0049). The + * fast path is the doc list's own: with no such book, an authenticated caller + * reads every doc, so `docReader` needs no corpus and `readableTree` filters + * nothing. */ export async function resolveDocsAudience( sources: MetaReadGateAudienceSources, @@ -732,8 +773,13 @@ export async function resolveDocsAudience( audienceAllows, docAudienceAllows, resolveDocAudiences, resolveBookTree, resolveBookClaimedDocs, deriveImplicitPackageBook, } = await import('@objectstack/spec/system'); - const gated = anyPermissionSetAudience(books); - const caller = await resolveAudienceCaller(sources, { needPermissionSets: gated }); + const setGated = anyPermissionSetAudience(books); + const capabilityGated = anySystemPermissionAudience(books); + const gated = setGated || capabilityGated; + const caller = await resolveAudienceCaller(sources, { + needPermissionSets: setGated, + needSystemPermissions: capabilityGated, + }); const allReadable = caller.authenticated && !gated; const docReader = (corpus: ResolverDoc[]): ((docName: unknown) => boolean) => { if (allReadable) return () => true; diff --git a/packages/runtime/src/domains/mcp-package-docs.ts b/packages/runtime/src/domains/mcp-package-docs.ts index ba009a7879d..3783829f6e9 100644 --- a/packages/runtime/src/domains/mcp-package-docs.ts +++ b/packages/runtime/src/domains/mcp-package-docs.ts @@ -18,10 +18,11 @@ * found. * * The caller is the request's execution context as the door received it. Its - * permission-set holdings, which a `{ permissionSet }` audience reads, are its + * permission-set holdings, which a `{ permissionSet }` audience reads, and its + * capabilities, which a `{ systemPermission }` audience reads, are its * own, with one exception ({@link packageDocsReadGate}): on a delegated agent * envelope (an OAuth grant: `principalKind: 'agent'` acting `onBehalfOf` a - * person) they are the delegating person's own sets, resolved by grant + * person) they are the delegating person's own sets and capabilities, resolved by grant * resolution in the organization the request runs in (ADR-0090 D10: the * token's ceiling decides whether the docs tools are reached at all, and the * person's holdings decide which manuals open). Never the envelope's @@ -441,8 +442,8 @@ export function createPackageDocMembers(getSources: () => Promise | undefined; return { resolveCaller: async () => caller, + // A `{ systemPermission }` audience reads the same holder as a + // `{ permissionSet }` one: on a delegated envelope the person's own + // capabilities, never the envelope's scope-derived ceiling; otherwise + // (no override) the caller's own `systemPermissions`. + ...(personId === undefined + ? {} + : { + resolveAudienceSystemPermissions: async () => + (await (holdings ??= delegatorHoldingsCaller(resolveEngine, personId, caller?.tenantId))) + .systemPermissions, + }), resolveSecurityService: personId === undefined ? security : async () => { diff --git a/packages/spec/src/system/book.zod.ts b/packages/spec/src/system/book.zod.ts index 3a93b150ba2..81e8e5a72cf 100644 --- a/packages/spec/src/system/book.zod.ts +++ b/packages/spec/src/system/book.zod.ts @@ -123,19 +123,31 @@ export type BookGroup = { /** * Access audience for a book — a reference into the permission model * (ADR-0046 §6.7, vocabulary per ADR-0090). The gate is a capability - * reference (a permission-set name), never a distribution one: books ship in - * packages, and packages own permission sets but never positions (ADR-0090 - * D9) — a package gating its Admin Guide to its own `crm_admin` set keeps - * provenance and uninstall semantics intact (ADR-0086). + * reference, never a distribution one: books ship in packages, and packages + * own permission sets but never positions (ADR-0090 D9) — a package gating + * its Admin Guide to its own `crm_admin` set keeps provenance and uninstall + * semantics intact (ADR-0086). + * + * Two gated forms: + * - `{ permissionSet }` — the reader holds that ONE named set; + * - `{ systemPermission }` — the reader holds that capability (a + * `systemPermissions` token, ADR-0066 D1) through ANY set, the same answer + * an app's `requiredPermissions: [token]` gets. This is the form for a + * manual that belongs to an app gated on a capability several sets grant + * (Setup's `setup.access`): a set name would shut out every other holder. */ export const BookAudienceSchema = lazySchema(() => z.union([ z.literal('org'), // default — inherits the package grant (§3.6) z.literal('public'), // ≡ the built-in `guest` position (ADR-0090 D9): anonymous, indexable z.object({ permissionSet: z.string() }), // capability-gated, e.g. { permissionSet: 'crm_admin' } + z + .object({ systemPermission: z.string() }) + .strict() + .describe("Readers holding this capability through any permission set, e.g. { systemPermission: 'setup.access' }"), ]), ); -export type BookAudience = 'org' | 'public' | { permissionSet: string }; +export type BookAudience = 'org' | 'public' | { permissionSet: string } | { systemPermission: string }; export const BookSchema = lazySchema(() => strictObject({ @@ -469,20 +481,34 @@ export interface AudienceCaller { * genuinely returned nothing. */ permissionSets?: readonly string[]; + /** + * The capabilities the caller effectively holds — the `systemPermissions` + * list the `/meta` read gate's `requiredPermissions` arms read, so a + * `{ systemPermission }` book opens exactly for whoever can open an app + * gated on that token. Absent/undefined means "unknown" and + * `{ systemPermission }` audiences DENY (fail closed, ADR-0049). + */ + systemPermissions?: readonly string[]; } /** * Whether a caller may read content published under `audience`: * `'public'` → always; `'org'` (or unset — §3.6 default) → any authenticated * principal; `{ permissionSet }` → an authenticated principal that holds the - * named set. Unknown/unresolvable set holdings deny (fail closed). + * named set; `{ systemPermission }` → an authenticated principal that holds + * the named capability. Unknown/unresolvable holdings deny (fail closed). */ export function audienceAllows(audience: BookAudience | undefined, caller: AudienceCaller): boolean { if (isPublicAudience(audience)) return true; if (!caller.authenticated) return false; if (audience === undefined || audience === 'org') return true; - if (typeof audience === 'object' && typeof audience.permissionSet === 'string') { - return Array.isArray(caller.permissionSets) && caller.permissionSets.includes(audience.permissionSet); + if (typeof audience === 'object' && typeof (audience as { permissionSet?: unknown }).permissionSet === 'string') { + const set = (audience as { permissionSet: string }).permissionSet; + return Array.isArray(caller.permissionSets) && caller.permissionSets.includes(set); + } + if (typeof audience === 'object' && typeof (audience as { systemPermission?: unknown }).systemPermission === 'string') { + const capability = (audience as { systemPermission: string }).systemPermission; + return Array.isArray(caller.systemPermissions) && caller.systemPermissions.includes(capability); } return false; // unknown future shape → fail closed } From 76570b8751baeecb89ab40885cccdc6058abcd31 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:12:15 +0000 Subject: [PATCH 2/6] test: pin the capability book audience in the spec helpers, the lint and the REST docs doors Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgV8bjXeBN9N25FTesc --- packages/lint/src/rule-explanations.ts | 3 +- .../validate-capability-references.test.ts | 25 +++ .../src/validate-capability-references.ts | 21 +- ...eta-doc-system-permission-audience.test.ts | 206 ++++++++++++++++++ packages/spec/src/system/book.test.ts | 55 ++++- 5 files changed, 303 insertions(+), 7 deletions(-) create mode 100644 packages/rest/src/meta-doc-system-permission-audience.test.ts diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index ad2e0c741d9..91147a6cced 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -5025,7 +5025,8 @@ const CAPABILITY_REFERENCE_UNKNOWN_EXPLANATION: RuleExplanation = { 'form, or each operation of the per-operation map), each field\'s, each object action\'s and ' + 'each top-level action\'s, each flow\'s, an app\'s and each of its nav entries (through `navigation`, ' + '`areas`, `tabs`, `children` and `items`), a view\'s (its own, its `config`\'s, its default ' + - '`list`\'s and each `listViews` entry\'s, on views and on objects) and a dashboard\'s.', + '`list`\'s and each `listViews` entry\'s, on views and on objects), a dashboard\'s, and a book\'s ' + + '`audience.systemPermission`, the same gate on a manual\'s pages.', 'A warning, not an error: the lint reads every package of the artifact being built, but it ' + 'cannot see the capabilities other installed packages declare, and the reference fails closed ' + 'anyway, so a dangling one is almost certainly a typo to surface, not a build to break. If ' + diff --git a/packages/lint/src/validate-capability-references.test.ts b/packages/lint/src/validate-capability-references.test.ts index bb3db0412f8..7b58d04eb0f 100644 --- a/packages/lint/src/validate-capability-references.test.ts +++ b/packages/lint/src/validate-capability-references.test.ts @@ -335,3 +335,28 @@ describe('[#22161] one-line verdicts — capability-reference-unknown', () => { expect(text).toContain('fails CLOSED'); }); }); + +// [ADR-0046 §6.7] A `{ systemPermission }` book audience is a capability gate +// on a manual: the docs reads serve its pages only to a holder, so a typo hides +// the manual from everyone. It resolves against the same known set. +describe('book audience — a { systemPermission } manual is resolved like every capability gate', () => { + it('warns on a typo at the book audience, at its own path, and passes a built-in and a granted one', () => { + const findings = validateCapabilityReferences({ + permissions: [{ name: 'crm_docs', systemPermissions: ['crm.read_runbook'] }], + books: [ + { name: 'setup_manual', audience: { systemPermission: 'setup.access' }, groups: [] }, + { name: 'crm_runbook', audience: { systemPermission: 'crm.read_runbook' }, groups: [] }, + { name: 'crm_typo', audience: { systemPermission: 'crm.read_runbok' }, groups: [] }, + // Not capability gates: nothing to resolve. + { name: 'crm_sets', audience: { permissionSet: 'crm_docs' }, groups: [] }, + { name: 'crm_org', audience: 'org', groups: [] }, + { name: 'crm_public', audience: 'public', groups: [] }, + ], + }); + expect(findings.map((f) => [f.where, f.path])).toEqual([ + ['book "crm_typo"', 'books[2].audience.systemPermission'], + ]); + expect(findings[0]).toMatchObject({ severity: 'warning', rule: CAPABILITY_REFERENCE_UNKNOWN }); + expect(findings[0].message).toContain('audience.systemPermission names capability "crm.read_runbok"'); + }); +}); diff --git a/packages/lint/src/validate-capability-references.ts b/packages/lint/src/validate-capability-references.ts index e794c731203..dbd15fec823 100644 --- a/packages/lint/src/validate-capability-references.ts +++ b/packages/lint/src/validate-capability-references.ts @@ -4,8 +4,8 @@ * [ADR-0066 ⑨] Authoring-time validation for capability references. * * `requiredPermissions` (on objects, fields, apps, actions, flows, list views - * and dashboards) and `systemPermissions` (on permission sets) are free capability - * strings. A typo + * and dashboards), a book's `audience.systemPermission` (ADR-0046 §6.7) and + * `systemPermissions` (on permission sets) are free capability strings. A typo * — `mange_users` for `manage_users` — is Zod-valid and fails CLOSED at runtime * (the caller is denied), which is the safe direction but UNDISCOVERABLE: nothing * tells the author the referenced capability exists nowhere. This rule closes @@ -131,7 +131,7 @@ export function validateCapabilityReferences(stack: AnyRec): CapabilityRefFindin 'Fix the capability name, or declare it with `defineCapability` (`stack.capabilities`) or on a ' + 'permission set’s `systemPermissions`.'; - const flag = (cap: string, where: string, path: string) => { + const flag = (cap: string, where: string, path: string, key = 'requiredPermissions') => { if (known.has(cap)) return; findings.push({ severity: 'warning', @@ -142,7 +142,7 @@ export function validateCapabilityReferences(stack: AnyRec): CapabilityRefFindin // positions walked and why it only warns is // `os explain capability-reference-unknown`. message: - `requiredPermissions names capability "${cap}", which no built-in, \`defineCapability\` ` + + `${key} names capability "${cap}", which no built-in, \`defineCapability\` ` + `or \`systemPermissions\` grant provides, so this gate fails closed`, hint, }); @@ -283,5 +283,18 @@ export function validateCapabilityReferences(stack: AnyRec): CapabilityRefFindin } } + // ── [ADR-0046 §6.7] Books: a `{ systemPermission }` audience is the same + // capability gate on a manual — the docs reads serve its pages only to a + // caller holding the capability, so a misspelled one hides the manual + // from everyone, silently. ── + for (const [i, book] of recordsOf(stack.books).entries()) { + const audience = book.audience; + if (!audience || typeof audience !== 'object' || Array.isArray(audience)) continue; + const cap = (audience as AnyRec).systemPermission; + if (typeof cap !== 'string' || cap.length === 0) continue; + const bName = typeof book.name === 'string' ? book.name : `(book ${i})`; + flag(cap, `book "${bName}"`, `books[${i}].audience.systemPermission`, 'audience.systemPermission'); + } + return findings; } diff --git a/packages/rest/src/meta-doc-system-permission-audience.test.ts b/packages/rest/src/meta-doc-system-permission-audience.test.ts new file mode 100644 index 00000000000..9f0d2c12eec --- /dev/null +++ b/packages/rest/src/meta-doc-system-permission-audience.test.ts @@ -0,0 +1,206 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0046 §6.7] A `{ systemPermission }` book audience, on every docs door. + * + * The Setup app opens for whoever holds `setup.access` — through + * `organization_admin`, `admin_full_access`, or any delegated-admin set an + * application authors — so Setup's own manual is gated on that capability, not + * on one set's name. The gate reads the caller's own `systemPermissions`, the + * list every `requiredPermissions` arm of the `/meta` read gate reads, so the + * manual opens for exactly the callers the app opens for. + * + * Pinned on the three doors the card names — the list (with and without + * `?include=content`, whose answer carries the body the docs search reads), + * the single read — plus the book's own tree and the book list: + * + * setup_manual { systemPermission: setup.access } claims setup_overview + * help_center 'org' claims crm_intro + * + * The holders are told apart by capability alone: the security service + * resolves the SAME permission sets for both, so a pass can only come from + * `systemPermissions`. + */ + +import { describe, it, expect, vi } from 'vitest'; +// Explicit `.js` extension: NodeNext resolution (see the sibling nav-gate tests). +import { RestServer } from './rest-server.js'; + +const SETUP_MANUAL = { + name: 'setup_manual', + label: 'Setup', + audience: { systemPermission: 'setup.access' }, + _packageId: 'com.objectstack.setup', + groups: [{ key: 'all', label: 'Documentation', include: '*' }], +}; +const HELP_CENTER = { + name: 'help_center', + label: 'Help Centre', + audience: 'org', + _packageId: 'crm', + groups: [{ key: 'start', label: 'Start', include: 'crm_intro' }], +}; +/** The body a member without `setup.access` must never receive. */ +const SETUP_BODY = 'Access is additive: a user holds the union of every permission set granted to them.'; +const DOCS = [ + { name: 'crm_intro', label: 'Getting started', content: 'Welcome aboard.', _packageId: 'crm' }, + { name: 'setup_overview', label: 'Setup overview', content: SETUP_BODY, _packageId: 'com.objectstack.setup' }, +]; + +function createMockServer() { + return { + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), use: vi.fn(), + listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), + }; +} + +function makeRes() { + const res: any = { statusCode: 200, body: undefined }; + res.status = vi.fn((c: number) => { res.statusCode = c; return res; }); + res.json = vi.fn((b: any) => { res.body = b; return res; }); + res.send = vi.fn(() => res); + res.header = vi.fn(); res.setHeader = vi.fn(); res.write = vi.fn(); res.end = vi.fn(); + return res; +} + +const clone = (v: T): T => JSON.parse(JSON.stringify(v)); + +interface SetupOpts { + /** The caller's `systemPermissions`; `undefined` leaves the key off the context. */ + systemPermissions?: unknown; + /** No resolved session at all. */ + anonymous?: boolean; + books?: any[]; +} + +function setup(opts: SetupOpts = {}) { + const byType: Record = { book: opts.books ?? [SETUP_MANUAL, HELP_CENTER], doc: DOCS }; + const protocol: any = { + getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' } }), + getMetaTypes: vi.fn().mockResolvedValue([]), + getMetaItems: vi.fn(async ({ type }: any) => clone(byType[String(type ?? '').replace(/s$/, '')] ?? [])), + getMetaItem: vi.fn(async ({ type, name }: any) => { + const t = String(type ?? '').replace(/s$/, ''); + const found = (byType[t] ?? []).find((i: any) => i.name === name); + return { type: t, name, item: found ? clone(found) : undefined }; + }), + findData: vi.fn().mockResolvedValue([]), + }; + // Both callers resolve the same sets: only the capability tells them apart. + const resolvePermissionSetNames = vi.fn(async () => ['member_default']); + const rest: any = new RestServer(createMockServer() as any, protocol, {} as any); + if (!opts.anonymous) { + rest.resolveExecCtx = async () => ({ + userId: 'u1', + ...('systemPermissions' in opts ? { systemPermissions: opts.systemPermissions } : {}), + }); + rest.securityServiceProvider = async () => ({ resolvePermissionSetNames }); + } + rest.registerRoutes(); + return { rest, resolvePermissionSetNames }; +} + +async function call(rest: any, path: string, params: Record, query: Record = {}) { + const route = rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === `/api/v1/meta${path}`); + if (!route) throw new Error(`GET /meta${path} not registered`); + const res = makeRes(); + await route.handler({ method: 'GET', params, query, body: {}, headers: {} }, res); + return res; +} +const readDoc = (rest: any, name: string) => call(rest, '/:type/:name', { type: 'doc', name }); +const listDocs = (rest: any, query: Record = {}) => call(rest, '/:type', { type: 'doc' }, query); +const listBooks = (rest: any) => call(rest, '/:type', { type: 'book' }); +const bookTree = (rest: any, name: string) => call(rest, '/book/:name/tree', { name }); + +const items = (body: any): any[] => (Array.isArray(body) ? body : (body?.items ?? [])); +const listed = (body: any): string[] => items(body).map((d: any) => d?.name); +/** The ADR-0112 minimum: the status and the machine code, never the prose. */ +const envelope = (res: any) => ({ status: res.statusCode, code: res.body?.code ?? res.body?.error?.code }); +const treeDocs = (body: any): string[] => + (body?.groups ?? []).flatMap((g: any) => (g.entries ?? []).map((e: any) => e.doc)).filter(Boolean); + +describe('a member WITHOUT setup.access — the Setup manual is neither listed nor read', () => { + const member = () => setup({ systemPermissions: ['api.read'] }); + + it('GET /meta/doc lists only the org doc', async () => { + expect(listed((await listDocs(member().rest)).body)).toEqual(['crm_intro']); + }); + + it('GET /meta/doc?include=content lists only the org doc, and the Setup body is nowhere in the answer', async () => { + const res = await listDocs(member().rest, { include: 'content' }); + expect(listed(res.body)).toEqual(['crm_intro']); + // The positive control: content IS carried on this door. + expect(items(res.body)[0]?.content).toBe('Welcome aboard.'); + expect(JSON.stringify(res.body)).not.toContain(SETUP_BODY); + }); + + it('GET /meta/doc/setup_overview is 403 PERMISSION_DENIED, with no body', async () => { + const res = await readDoc(member().rest, 'setup_overview'); + expect(envelope(res)).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect(JSON.stringify(res.body)).not.toContain(SETUP_BODY); + }); + + it('the book itself: absent from GET /meta/book, and its tree is 403', async () => { + const { rest } = member(); + expect(listed((await listBooks(rest)).body)).toEqual(['help_center']); + expect(envelope(await bookTree(rest, 'setup_manual'))).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + }); + + it('the package\'s implicit book serves no Setup page either (the claim is the doc\'s, whichever book is asked)', async () => { + const res = await bookTree(member().rest, 'com.objectstack.setup'); + expect(treeDocs(res.body)).not.toContain('setup_overview'); + }); +}); + +describe('a holder of setup.access — reads the manual as an admin always has', () => { + const holder = () => setup({ systemPermissions: ['api.read', 'setup.access'] }); + + it('GET /meta/doc lists it; ?include=content carries its body', async () => { + const { rest } = holder(); + expect(listed((await listDocs(rest)).body)).toEqual(['crm_intro', 'setup_overview']); + const withContent = await listDocs(rest, { include: 'content' }); + expect(items(withContent.body).find((d: any) => d.name === 'setup_overview')?.content).toBe(SETUP_BODY); + }); + + it('GET /meta/doc/setup_overview is 200 with its body', async () => { + const res = await readDoc(holder().rest, 'setup_overview'); + expect(res.statusCode).toBe(200); + expect(res.body?.item?.content).toBe(SETUP_BODY); + }); + + it('the book is listed and its tree carries the page', async () => { + const { rest } = holder(); + expect(listed((await listBooks(rest)).body)).toEqual(['setup_manual', 'help_center']); + const tree = await bookTree(rest, 'setup_manual'); + expect(tree.statusCode).toBe(200); + expect(treeDocs(tree.body)).toEqual(['setup_overview']); + }); +}); + +describe('fail closed, and no wider than it needs', () => { + it('a context with no systemPermissions list reads as unresolved: the Setup page is refused', async () => { + for (const systemPermissions of [undefined, 'setup.access', null]) { + const { rest } = setup(systemPermissions === undefined ? {} : { systemPermissions }); + expect(envelope(await readDoc(rest, 'setup_overview'))).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect(listed((await listDocs(rest)).body)).toEqual(['crm_intro']); + } + }); + + it('anonymous: the doc takes its 401 UNAUTHENTICATED path', async () => { + const res = await readDoc(setup({ anonymous: true }).rest, 'setup_overview'); + expect(envelope(res)).toEqual({ status: 401, code: 'UNAUTHENTICATED' }); + expect(JSON.stringify(res.body)).not.toContain(SETUP_BODY); + }); + + it('a capability gate alone never asks the security service for permission sets', async () => { + const { rest, resolvePermissionSetNames } = setup({ systemPermissions: ['setup.access'] }); + await readDoc(rest, 'setup_overview'); + await listDocs(rest, { include: 'content' }); + expect(resolvePermissionSetNames).not.toHaveBeenCalled(); + }); + + it('control: with no gated book anywhere, every authenticated caller reads every doc (the fast path)', async () => { + const { rest } = setup({ systemPermissions: [], books: [HELP_CENTER] }); + expect(listed((await listDocs(rest)).body)).toEqual(['crm_intro', 'setup_overview']); + }); +}); diff --git a/packages/spec/src/system/book.test.ts b/packages/spec/src/system/book.test.ts index e9dec3b41dd..2874e6e3a27 100644 --- a/packages/spec/src/system/book.test.ts +++ b/packages/spec/src/system/book.test.ts @@ -37,8 +37,19 @@ describe('BookSchema (ADR-0046 §6)', () => { expect(() => BookSchema.parse({ name: 'crm_guide', groups: [{ key: 'Start', label: 'x' }] })).toThrow(); }); it('accepts audience variants', () => { - for (const audience of ['org', 'public', { permissionSet: 'crm_admin' }] as const) { - expect(() => BookSchema.parse({ name: 'b', audience, groups: [] })).not.toThrow(); + for (const audience of ['org', 'public', { permissionSet: 'crm_admin' }, { systemPermission: 'setup.access' }] as const) { + expect(BookSchema.safeParse({ name: 'b', audience, groups: [] }).success).toBe(true); + // Parsed as authored, never narrowed to another arm. + expect(BookSchema.parse({ name: 'b', audience, groups: [] }).audience).toEqual(audience); + } + }); + it('rejects a { systemPermission } audience carrying an unknown key, and one with no string token', () => { + for (const audience of [ + { systemPermission: 'setup.access', label: 'Admins' }, + { systemPermission: ['setup.access'] }, + { systemPermissions: ['setup.access'] }, + ]) { + expect(BookSchema.safeParse({ name: 'b', audience, groups: [] }).success).toBe(false); } }); it('rejects the removed { profile } audience shape (ADR-0090 D2)', () => { @@ -382,6 +393,29 @@ describe('audienceAllows (ADR-0046 §6.7, ADR-0090 vocabulary)', () => { it('permission-set gate FAILS CLOSED when holdings are unknown (ADR-0049)', () => { expect(audienceAllows({ permissionSet: 'crm_admin' }, unresolved)).toBe(false); }); + + // The capability gate: whoever holds the token, through any set — the + // answer an app's `requiredPermissions: [token]` gives. + it('system-permission gate requires holding the named capability, through whichever set', () => { + const gated = { systemPermission: 'setup.access' }; + const orgAdmin = { authenticated: true, permissionSets: ['organization_admin'], systemPermissions: ['setup.access'] }; + const delegatedAdmin = { authenticated: true, permissionSets: ['ops_admin'], systemPermissions: ['setup.access'] }; + const plain = { authenticated: true, permissionSets: ['member_default'], systemPermissions: ['api.read'] }; + expect(audienceAllows(gated, orgAdmin)).toBe(true); + expect(audienceAllows(gated, delegatedAdmin)).toBe(true); + expect(audienceAllows(gated, plain)).toBe(false); + expect(audienceAllows(gated, { authenticated: false, systemPermissions: ['setup.access'] })).toBe(false); + }); + it('system-permission gate reads capabilities, never set names', () => { + // A set NAMED like the token is not the capability. + expect(audienceAllows({ systemPermission: 'setup.access' }, { authenticated: true, permissionSets: ['setup.access'] })).toBe(false); + // And a { permissionSet } gate is not opened by a capability of that name. + expect(audienceAllows({ permissionSet: 'crm_admin' }, { authenticated: true, systemPermissions: ['crm_admin'] })).toBe(false); + }); + it('system-permission gate FAILS CLOSED when capabilities are unknown (ADR-0049)', () => { + expect(audienceAllows({ systemPermission: 'setup.access' }, unresolved)).toBe(false); + expect(audienceAllows({ systemPermission: 'setup.access' }, admin)).toBe(false); + }); }); describe('resolveDocAudiences — union over claiming books (§6.7)', () => { @@ -434,6 +468,23 @@ describe('resolveDocAudiences — union over claiming books (§6.7)', () => { expect(docAudienceAllows(gatedOnly.get('crm_admin_setup'), member)).toBe(false); expect(docAudienceAllows(gatedOnly.get('crm_admin_setup'), { authenticated: false })).toBe(false); }); + it('a doc only a { systemPermission } book claims is read by holders of the capability alone', () => { + const setupBook: Book & { packageId?: string } = { + name: 'setup_manual', + audience: { systemPermission: 'setup.access' }, + groups: [{ key: 'all', label: 'All', include: '*' }], + packageId: 'com.objectstack.setup', + }; + const docs: ResolverDoc[] = [...corpus, { name: 'setup_overview', packageId: 'com.objectstack.setup' }]; + const audiences = resolveDocAudiences([publicBook, adminBook, setupBook], docs); + expect(audiences.get('setup_overview')).toEqual([{ systemPermission: 'setup.access' }]); + // `include: '*'` reaches only the book's own package. + expect(audiences.get('crm_unclaimed')).toEqual(['org']); + const holder = { authenticated: true, systemPermissions: ['setup.access'] }; + const member = { authenticated: true, permissionSets: ['member_default'], systemPermissions: [] }; + expect(docAudienceAllows(audiences.get('setup_overview'), holder)).toBe(true); + expect(docAudienceAllows(audiences.get('setup_overview'), member)).toBe(false); + }); it('an unknown doc (absent from the corpus map) gets the org default', () => { expect(docAudienceAllows(undefined, { authenticated: true })).toBe(true); expect(docAudienceAllows(undefined, { authenticated: false })).toBe(false); From 28328b2472f03a92ca6ae9794d0534dd4e50b7ca Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:14:28 +0000 Subject: [PATCH 3/6] test: pin the capability audience on the MCP docs door; show it in the Studio book preview; document it Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgV8bjXeBN9N25FTesc --- content/docs/ui/doc-pages.mdx | 13 ++++--- .../src/domains/mcp-package-docs.test.ts | 36 ++++++++++++++++++- .../views/metadata-admin/default-schemas.ts | 12 +++++-- .../metadata-admin/previews/BookPreview.tsx | 12 +++++-- .../adminPreviews.i18n-10862-s2.test.tsx | 13 +++++++ ui/packages/i18n/src/namespaces/studio/en.ts | 1 + ui/packages/i18n/src/namespaces/studio/zh.ts | 1 + 7 files changed, 78 insertions(+), 10 deletions(-) diff --git a/content/docs/ui/doc-pages.mdx b/content/docs/ui/doc-pages.mdx index 9e5bf53248c..b2de72f1a29 100644 --- a/content/docs/ui/doc-pages.mdx +++ b/content/docs/ui/doc-pages.mdx @@ -240,14 +240,19 @@ as a preference, not as a limitation. Tags are for membership that cuts across n | `slug` | `string` | — | Portal URL segment; defaults to the name without its prefix | | `icon` | `string` | — | Icon name | | `order` | `number` | — | Orders this book among the portal's books | -| `audience` | `'org' \| 'public' \| { permissionSet }` | — | Who may read it; defaults to `'org'` | +| `audience` | `'org' \| 'public' \| { permissionSet } \| { systemPermission }` | — | Who may read it; defaults to `'org'` | | `groups` | `BookGroup[]` | ✅ | The spine. Two levels total — groups, then entries | `audience` is a reference into the permission model rather than a vocabulary of its own: `'org'` (the default) inherits the package grant and admits any signed-in principal, -`'public'` is anonymously readable and indexable, and `{ permissionSet: 'crm_admin' }` -admits a signed-in principal holding that named set. A caller whose holdings cannot be -resolved is denied — the gate fails closed. +`'public'` is anonymously readable and indexable, `{ permissionSet: 'crm_admin' }` +admits a signed-in principal holding that named set, and +`{ systemPermission: 'crm.read_runbook' }` admits a signed-in principal holding that +capability through any permission set — the same caller an app with +`requiredPermissions: ['crm.read_runbook']` opens for. Use the capability form for the +manual of an app gated on a capability several sets grant: naming one of those sets would +shut out the holders of every other one. A caller whose holdings cannot be resolved is +denied — the gate fails closed. The gate is a **capability** reference, never a distribution one: packages own permission diff --git a/packages/runtime/src/domains/mcp-package-docs.test.ts b/packages/runtime/src/domains/mcp-package-docs.test.ts index 28aa88853bb..c2b21fd7894 100644 --- a/packages/runtime/src/domains/mcp-package-docs.test.ts +++ b/packages/runtime/src/domains/mcp-package-docs.test.ts @@ -119,7 +119,9 @@ function grantQl() { { id: 'g2', user_id: 'ghost', permission_set_id: 'ps_crm_admin', permission_set: 'crm_admin', organization_id: 'orgA' }, { id: 'g3', user_id: 'u1', permission_set_id: 'ps_crm_admin', permission_set: 'crm_admin', organization_id: 'orgB' }, ], - sys_permission_set: [{ id: 'ps_crm_admin', name: 'crm_admin', object_permissions: '{}' }], + // `crm_admin` also grants the `crm.read_rules` capability a + // `{ systemPermission }` manual reads (ADR-0046 §6.7). + sys_permission_set: [{ id: 'ps_crm_admin', name: 'crm_admin', object_permissions: '{}', system_permissions: ['crm.read_rules'] }], sys_position: [], sys_position_permission_set: [], sys_user_position: [], }; const match = (opts: any) => (row: any) => Object.entries(opts?.where ?? {}).every(([k, v]) => @@ -317,6 +319,38 @@ describe('[#35584] on an OAuth grant the audience reads the delegating person\'s }); }); +// [ADR-0046 §6.7] A `{ systemPermission }` manual: the same gate, read off the +// caller's capabilities — through whichever set grants them — and, on an OAuth +// grant, off the delegating person's, never the envelope's. +describe('a manual gated on a capability: found and read by its holders only', () => { + const CAPABILITY_BOOKS = [BOOKS[0], { ...BOOKS[1], audience: { systemPermission: 'crm.read_rules' } }]; + const items = { doc: DOCS, book: CAPABILITY_BOOKS }; + const member = (systemPermissions: unknown) => ({ userId: 'u1', isSystem: false, permissions: [], systemPermissions }); + + it('a session holding the capability finds and reads the page; one without it neither finds nor reads it', async () => { + expect(await reach(await bridgeFor(member(['crm.read_rules']), items))).toEqual(OPEN); + expect(await reach(await bridgeFor(member(['api.read']), items))).toEqual(CLOSED); + }); + + it('the capability is not a set: a session holding a SET named crm_admin, and no capability, stays closed', async () => { + expect(await reach(await bridgeFor({ ...member([]), permissions: ['crm_admin'] }, items))).toEqual(CLOSED); + }); + + it('fails closed when the caller carries no capability list', async () => { + expect(await reach(await bridgeFor({ userId: 'u1', isSystem: false, permissions: [] }, items))).toEqual(CLOSED); + }); + + it('OAuth: the delegating person\'s own grants decide — the holder opens it, a non-holder does not', async () => { + expect(await reach(await bridgeFor(await oauthEnvelope('admin', ['data:read']), items))).toEqual(OPEN); + expect(await reach(await bridgeFor(await oauthEnvelope('u1', ['data:read']), items))).toEqual(CLOSED); + }); + + it('OAuth, no union: the envelope carrying the capability opens nothing the person does not hold', async () => { + const envelope = { ...(await oauthEnvelope('u1', ['data:read'])), systemPermissions: ['crm.read_rules'] }; + expect(await reach(await bridgeFor(envelope, items))).toEqual(CLOSED); + }); +}); + describe('[#35442] search and read details', () => { it('a page no manual claims opens in its package\'s implicit manual; package narrows the search', async () => { const bridge = await bridgeFor('u1'); diff --git a/ui/packages/app-shell/src/views/metadata-admin/default-schemas.ts b/ui/packages/app-shell/src/views/metadata-admin/default-schemas.ts index 89d62fccdd8..7d2df5b6021 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/default-schemas.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/default-schemas.ts @@ -266,9 +266,9 @@ const SCHEMAS: Record> = { audience: { title: 'Audience', description: - "Access audience. 'org' (default) inherits the package grant; 'public' is anonymously readable; { permissionSet } gates by a permission set the reader must hold (ADR-0090).", - // Union of the two scalar literals and the { permissionSet } object — kept lax - // so the permission-set-gated object form round-trips untouched through the form. + "Access audience. 'org' (default) inherits the package grant; 'public' is anonymously readable; { permissionSet } gates by a permission set the reader must hold (ADR-0090); { systemPermission } gates by a capability the reader holds through any permission set (ADR-0046 §6.7).", + // Union of the two scalar literals and the two gated object forms — kept lax + // so either gated form round-trips untouched through the form. oneOf: [ { type: 'string', enum: ['org', 'public'] }, { @@ -277,6 +277,12 @@ const SCHEMAS: Record> = { properties: { permissionSet: { type: 'string', title: 'Permission set' } }, required: ['permissionSet'], }, + { + type: 'object', + title: 'Capability gated', + properties: { systemPermission: { type: 'string', title: 'Capability' } }, + required: ['systemPermission'], + }, ], }, groups: { diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/BookPreview.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/BookPreview.tsx index 31be8c507e5..ec997395fdf 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/BookPreview.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/BookPreview.tsx @@ -37,7 +37,7 @@ import { t as tr, tFormat } from '../i18n.js'; import { PreviewShell, PreviewErrorBoundary, PreviewEmptyState } from './PreviewShell.js'; import { withNodes } from './row-nodes.js'; -type Audience = 'org' | 'public' | { permissionSet: string } | undefined; +type Audience = 'org' | 'public' | { permissionSet: string } | { systemPermission: string } | undefined; type Include = string | { tag: string } | undefined; interface PageNode { @@ -129,13 +129,21 @@ function audienceChip( tone: 'text-emerald-700 bg-emerald-50 border-emerald-200', }; } - if (audience && typeof audience === 'object' && typeof audience.permissionSet === 'string') { + if (audience && typeof audience === 'object' && 'permissionSet' in audience && typeof audience.permissionSet === 'string') { return { icon: , label: tFormat('engine.bookPreview.audience.permissionSet', locale, { name: audience.permissionSet }), tone: 'text-amber-800 bg-amber-50 border-amber-200', }; } + // ADR-0046 §6.7 — readers holding the capability, through any permission set. + if (audience && typeof audience === 'object' && 'systemPermission' in audience && typeof audience.systemPermission === 'string') { + return { + icon: , + label: tFormat('engine.bookPreview.audience.systemPermission', locale, { name: audience.systemPermission }), + tone: 'text-amber-800 bg-amber-50 border-amber-200', + }; + } // 'org' (default) or absent — inherits the package grant. return { icon: , diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/adminPreviews.i18n-10862-s2.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/adminPreviews.i18n-10862-s2.test.tsx index c25c2387c93..f0b47cdb775 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/adminPreviews.i18n-10862-s2.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/adminPreviews.i18n-10862-s2.test.tsx @@ -220,6 +220,19 @@ describe('BookPreview reads the designer locale (objectui#10862)', () => { inLang(lang, ); expectSites(lang, [{ key: 'engine.bookPreview.audience.public' }]); }); + + // ADR-0046 §6.7 — a capability-gated book is not shown as readable by the org. + it(`${lang}: a capability-gated book`, () => { + inLang(lang, ( + + )); + expectSites(lang, [{ key: 'engine.bookPreview.audience.systemPermission', vars: { name: 'setup.access' } }]); + }); } }); diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 835cfdd8888..7f408127786 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -4406,6 +4406,7 @@ const STUDIO_EN: Record = { 'engine.bookPreview.tree': 'Resolved tree', 'engine.bookPreview.audience.public': 'Public', 'engine.bookPreview.audience.permissionSet': 'Permission set: {name}', + 'engine.bookPreview.audience.systemPermission': 'Capability: {name}', 'engine.bookPreview.audience.org': 'Org', 'engine.bookPreview.slug': 'Slug: {slug}', 'engine.bookPreview.noGroups': 'No groups yet', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index acd16589a57..2d3a24cb2f8 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -3963,6 +3963,7 @@ const STUDIO_ZH: Record = { 'engine.bookPreview.tree': '解析后的目录树', 'engine.bookPreview.audience.public': '公开', 'engine.bookPreview.audience.permissionSet': '权限集:{name}', + 'engine.bookPreview.audience.systemPermission': '系统权限:{name}', 'engine.bookPreview.audience.org': '组织', 'engine.bookPreview.slug': 'URL 标识:{slug}', 'engine.bookPreview.noGroups': '尚无分组', From d0d552f974bfbabdf5315dc9a147d16dd8db7d2e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:20:30 +0000 Subject: [PATCH 4/6] chore(spec): regenerate the book reference page and the strictness ledger; record the capability arm on the audience liveness row; changeset; Setup docs dogfood pin Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgV8bjXeBN9N25FTesc --- .../36029-book-audience-system-permission.md | 27 ++++++ content/docs/references/system/book.mdx | 14 ++- .../system.md | 2 +- .../test/setup-docs-audience.dogfood.test.ts | 96 +++++++++++++++++++ packages/spec/liveness/book.json | 6 +- 5 files changed, 140 insertions(+), 5 deletions(-) create mode 100644 .changeset/36029-book-audience-system-permission.md create mode 100644 packages/qa/dogfood/test/setup-docs-audience.dogfood.test.ts diff --git a/.changeset/36029-book-audience-system-permission.md b/.changeset/36029-book-audience-system-permission.md new file mode 100644 index 00000000000..33b02618af1 --- /dev/null +++ b/.changeset/36029-book-audience-system-permission.md @@ -0,0 +1,27 @@ +--- +'@objectstack/spec': minor +'@objectstack/rest': minor +'@objectstack/runtime': minor +'@objectstack/lint': minor +'@objectstack/setup': minor +'@objectstack/studio': minor +'@object-ui/app-shell': minor +'@object-ui/i18n': minor +--- + +feat(spec): a book audience can name a capability, so the Setup and Studio docs open only for callers who can open those apps + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: none — no `skills/` page teaches the book audience forms; `content/docs/ui/doc-pages.mdx` documents the new form in this change + +A book's `audience` (ADR-0046 §6.7) takes a fourth form, `{ systemPermission: 'TOKEN' }`: the book's pages are read by a signed-in caller who holds that capability through any permission set, the same caller an app with `requiredPermissions: ['TOKEN']` opens for. `{ permissionSet }` names one set, so it could not gate a manual on a capability several sets grant (`setup.access` comes with `organization_admin`, `admin_full_access` and any delegated-admin set an application authors). + +- **`@objectstack/spec`.** `BookAudienceSchema` and `BookAudience` gain the arm; it is strict, so a key beside `systemPermission` is refused at parse. `AudienceCaller` gains `systemPermissions`, and `audienceAllows` admits the arm only when that list holds the token; an absent list denies (fail closed). Every other form answers as before. +- **`@objectstack/rest`.** The docs audience reads the caller's own `systemPermissions` (the list every `requiredPermissions` arm of the `/meta` read gate reads) when some book carries the new form, on `GET /meta/doc` (with and without `?include=content`), `GET /meta/doc/:name`, `GET /meta/book`, `GET /meta/book/:name/tree` and the app-nav `doc` entries. New: `anySystemPermissionAudience`, and the optional `resolveAudienceSystemPermissions` port on `MetaReadGateAudienceSources` for a transport whose audience reads someone else's holdings. +- **`@objectstack/runtime`.** The MCP docs tools (`search_package_docs`, `read_package_doc`) gate on the same form; on an OAuth grant they read the delegating person's own capabilities, never the token's ceiling. +- **`@objectstack/setup`, `@objectstack/studio`.** Each package now ships a manual (`setup_manual`, `studio_manual`) claiming every doc of its package, gated on `setup.access` / `studio.access`. Before, those docs were claimed by no book, so they fell back to `org`: listed to administrators only by the Console's docs index, but readable at their address, and through `?include=content`, by every signed-in member. Now a member who cannot open Setup gets `setup_overview` in neither list and a `403 PERMISSION_DENIED` on its read; an administrator reads it as before. The docs' Console address now names the manual (`/apps/com.objectstack.setup/docs/setup/setup_overview`) in place of the package's implicit one; the flat `/docs/setup_overview` permalink still finds it. +- **`@objectstack/lint`.** `capability-reference-unknown` also resolves a book's `audience.systemPermission`, so a misspelled capability (which hides the manual from everyone) warns. +- **`@object-ui/app-shell`, `@object-ui/i18n`.** Studio's book preview shows a capability-gated book as "Capability: TOKEN" instead of "Org", and the book form round-trips the new form. + +Nothing to migrate: no stored or authored value changes meaning. diff --git a/content/docs/references/system/book.mdx b/content/docs/references/system/book.mdx index ff9832d08a0..607ff345a4f 100644 --- a/content/docs/references/system/book.mdx +++ b/content/docs/references/system/book.mdx @@ -52,7 +52,7 @@ const result = BookSchema.parse(data); | **slug** | `string` | optional | Portal URL segment; defaults to name sans prefix | | **icon** | `string` | optional | | | **order** | `number` | optional | Orders books within the portal | -| **audience** | `'org' \| 'public' \| { permissionSet: string }` | optional | Access audience; defaults to 'org' (inherits package grant) | +| **audience** | `'org' \| 'public' \| { permissionSet: string } \| { systemPermission: string }` | optional | Access audience; defaults to 'org' (inherits package grant) | | **groups** | `{ key: string; label: string; order?: number; include?: string \| object; … }[]` | ✅ | The spine: ordered sections. Two levels total. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | @@ -113,6 +113,18 @@ Type: `'public'` --- +#### Option 4 + +Readers holding this capability through any permission set, e.g. `{ systemPermission: 'setup.access' }` + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **systemPermission** | `string` | ✅ | | + +--- + --- diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md index e35ee35f184..22a10369642 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `system/` | 409 | +| `system/` | 410 | diff --git a/packages/qa/dogfood/test/setup-docs-audience.dogfood.test.ts b/packages/qa/dogfood/test/setup-docs-audience.dogfood.test.ts new file mode 100644 index 00000000000..85e2214df81 --- /dev/null +++ b/packages/qa/dogfood/test/setup-docs-audience.dogfood.test.ts @@ -0,0 +1,96 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0046 §6.7] The Setup app's own docs are read by exactly the callers who +// may open the Setup app — through the real `@objectstack/setup` package, on a +// real boot, over HTTP. +// +// `@objectstack/setup` registers `setup_overview` with a manual +// (`setup_manual`) whose audience is `{ systemPermission: 'setup.access' }`, +// the capability the Setup app itself requires. Before that manual, the doc was +// claimed by no book, so its audience fell back to `org`: the Console's docs +// index listed it to administrators only, but any signed-in member read its +// body at its address and through `?include=content`. +// +// Each side is proven against the app gate it is meant to match: the member is +// first shown to be refused the Setup app, the administrator to be served it. +// The unit pins of the gate itself are in `@objectstack/rest` +// (`meta-doc-system-permission-audience.test.ts`). + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { defineStack } from '@objectstack/spec'; +import { createSetupAppPlugin } from '@objectstack/setup'; + +const stackDef = defineStack({ + manifest: { + id: 'com.dogfood.setup-docs-audience', + namespace: 'sda', + version: '0.0.0', + type: 'app', + name: 'Setup Docs Audience Fixture', + description: 'A host with the Setup app package, to read its docs as a member and as an administrator.', + }, + docs: [{ name: 'sda_welcome', label: 'Welcome', content: '# Welcome\n\nThe host app\'s own page.\n' }], +} as any); + +const SETUP_LINE = 'Access is additive'; + +const names = (body: any): string[] => + (Array.isArray(body) ? body : (body?.items ?? body?.data ?? [])).map((d: any) => d?.name); + +describe('objectstack verify: Setup\'s docs open only for callers who can open Setup', () => { + let stack: VerifyStack; + let admin: string; + let member: string; + + beforeAll(async () => { + stack = await bootStack(stackDef, { extraPlugins: [createSetupAppPlugin()] }); + admin = await stack.signIn(); + member = await stack.signUp('setup-docs-member@verify.test'); + }, 120_000); + + afterAll(async () => { + await stack?.stop(); + }); + + const get = async (token: string, path: string) => { + const r = await stack.apiAs(token, 'GET', path); + return { status: r.status, body: (await r.json().catch(() => undefined)) as any }; + }; + + it('precondition: the member is refused the Setup app, the administrator is served it', async () => { + expect((await get(member, '/meta/app/setup')).status).toBe(403); + expect((await get(admin, '/meta/app/setup')).status).toBe(200); + }); + + it('a member without setup.access: the Setup doc is in neither list, and its read is refused', async () => { + const list = await get(member, '/meta/doc'); + expect(list.status).toBe(200); + expect(names(list.body)).toContain('sda_welcome'); + expect(names(list.body)).not.toContain('setup_overview'); + + const withContent = await get(member, '/meta/doc?include=content'); + expect(withContent.status).toBe(200); + expect(names(withContent.body)).not.toContain('setup_overview'); + expect(JSON.stringify(withContent.body)).not.toContain(SETUP_LINE); + + const single = await get(member, '/meta/doc/setup_overview'); + expect(single.status, JSON.stringify(single.body)).toBe(403); + expect(JSON.stringify(single.body)).not.toContain(SETUP_LINE); + }); + + it('control — the administrator lists it, reads its body on both doors, and opens its manual', async () => { + expect(names((await get(admin, '/meta/doc')).body)).toContain('setup_overview'); + + const withContent = await get(admin, '/meta/doc?include=content'); + expect(JSON.stringify(withContent.body)).toContain(SETUP_LINE); + + const single = await get(admin, '/meta/doc/setup_overview'); + expect(single.status, JSON.stringify(single.body)).toBe(200); + expect(JSON.stringify(single.body)).toContain(SETUP_LINE); + + const tree = await get(admin, '/meta/book/setup_manual/tree'); + expect(tree.status, JSON.stringify(tree.body)).toBe(200); + expect(JSON.stringify(tree.body)).toContain('setup_overview'); + }); +}); diff --git a/packages/spec/liveness/book.json b/packages/spec/liveness/book.json index 1cab88c77c8..51fbef4724d 100644 --- a/packages/spec/liveness/book.json +++ b/packages/spec/liveness/book.json @@ -4,7 +4,7 @@ "props": { "name": { "status": "live", - "verifiedAt": "2026-09-27", + "verifiedAt": "2026-11-26", "evidence": "packages/rest/src/meta-item-read-gate.ts#deriveImplicitPackageBook (`bookNamed`: `books.find((b: any) => b && b.name === name) ?? deriveImplicitPackageBook(name, name)` — the tree route's `audience.bookNamed(req.params.name)` matches the book by name and, failing that, synthesizes the implicit per-package book from the same segment — §6.4); packages/spec/src/system/book.zod.ts#resolveBookTree (`return { name: book.name, … }` — the resolved tree carries it back out)", "note": "tree-route identity; an unknown name is treated as a package id and resolved as the implicit per-package book (§6.4). 2026-08-28: RE-ANCHORED (commit 8cb96ec41) and REPOINTED — `rest-server.ts:3098` had rotted onto `patterns: crud.patterns` in the CRUD-endpoint config, ~1,800 lines from the book route. The `_note`'s file-level range (`:3078-3169`) had rotted with it and is replaced by a symbol too. Re-closed by hand against 93ea19bca." }, @@ -41,8 +41,8 @@ "audience": { "status": "live", "verifiedAt": "2026-09-27", - "evidence": "packages/spec/src/system/book.zod.ts#audienceAllows (the gate itself: `public` always, `org`/unset any authenticated principal, `{ permissionSet }` only a holder, unknown shape → false); packages/spec/src/system/book.zod.ts#resolveDocAudiences (`const audience = book.audience ?? 'org'` — every doc's effective audience is the UNION over the books that claim it, unclaimed docs falling back to `org`); packages/rest/src/meta-item-read-gate.ts#audienceAllows (`admitsBook: (book: Book) => audienceAllows(book?.audience, caller)` — the gate the tree route asks as `if (!audience.admitsBook(book))` → 401 anonymous / 403 non-holder, before any tree is built, and the book item read asks on both transports)", - "note": "ENFORCED access gate (§6.7), fail-closed: gates the whole tree (401 anonymous / 403 non-holder), and every doc's effective audience is the union over the books that claim it (resolveDocAudiences) — applied to both doc lists and tree entries. The one security-shaped property on this type, and it is real. 2026-08-28: RE-ANCHORED (commit 8cb96ec41) and REPOINTED — ALL THREE legs were wrong. `rest-server.ts:3113` lands on the comment `// config to read).` and `:2969` on a docblock sentence about `'v1/beta'` splicing a path segment; `book.zod.ts:351` lands on `entries.push(entryFromDoc(d))` inside `resolveBookTree`'s `...` rest-expansion — tree ASSEMBLY, not the gate, ~83 lines from `audienceAllows`. A security-shaped property whose every pointer had drifted, one of them onto a comment, is the case this whole worklist is justified by: the verdict was right, and nothing cited could have shown it. Re-closed by hand against 93ea19bca." + "evidence": "packages/spec/src/system/book.zod.ts#audienceAllows (the gate itself: `public` always, `org`/unset any authenticated principal, `{ permissionSet }` only a holder of the set, `{ systemPermission }` only a holder of the capability, unknown shape → false); packages/spec/src/system/book.zod.ts#resolveDocAudiences (`const audience = book.audience ?? 'org'` — every doc's effective audience is the UNION over the books that claim it, unclaimed docs falling back to `org`); packages/rest/src/meta-item-read-gate.ts#audienceAllows (`admitsBook: (book: Book) => audienceAllows(book?.audience, caller)` — the gate the tree route asks as `if (!audience.admitsBook(book))` → 401 anonymous / 403 non-holder, before any tree is built, and the book item read asks on both transports); packages/rest/src/meta-item-read-gate.ts#resolveAudienceCaller (`caller.systemPermissions` — the caller's own capability list, the one `holdsRequiredPermissions` reads for an app, filled only when a `{ systemPermission }` book exists)", + "note": "ENFORCED access gate (§6.7), fail-closed: gates the whole tree (401 anonymous / 403 non-holder), and every doc's effective audience is the union over the books that claim it (resolveDocAudiences) — applied to both doc lists and tree entries. The one security-shaped property on this type, and it is real. 2026-08-28: RE-ANCHORED (commit 8cb96ec41) and REPOINTED — ALL THREE legs were wrong. `rest-server.ts:3113` lands on the comment `// config to read).` and `:2969` on a docblock sentence about `'v1/beta'` splicing a path segment; `book.zod.ts:351` lands on `entries.push(entryFromDoc(d))` inside `resolveBookTree`'s `...` rest-expansion — tree ASSEMBLY, not the gate, ~83 lines from `audienceAllows`. A security-shaped property whose every pointer had drifted, one of them onto a comment, is the case this whole worklist is justified by: the verdict was right, and nothing cited could have shown it. Re-closed by hand against 93ea19bca. 2026-11-26: the `{ systemPermission }` arm (ADR-0046 §6.7) joins the same gate — a capability the reader holds through any set, so the Setup and Studio manuals open for exactly the callers their apps open for; pinned on every docs door by packages/rest/src/meta-doc-system-permission-audience.test.ts and on the MCP docs door by packages/runtime/src/domains/mcp-package-docs.test.ts." }, "groups": { "children": { From 899b3e2f7cd924e3a6de98b481f3a9dc6f4b00b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:35:51 +0000 Subject: [PATCH 5/6] test(rest): pay the objectql load at collection in the systemPermission audience test; docs: lint resolves book audience capabilities Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgV8bjXeBN9N25FTesc --- content/docs/permissions/capabilities.mdx | 4 ++-- packages/rest/src/meta-doc-system-permission-audience.test.ts | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/content/docs/permissions/capabilities.mdx b/content/docs/permissions/capabilities.mdx index 4a6db28cf68..24ca2d9f60a 100644 --- a/content/docs/permissions/capabilities.mdx +++ b/content/docs/permissions/capabilities.mdx @@ -147,8 +147,8 @@ plain names. Three consequences worth internalising before you pick one: capability name; it is simply held by nobody, so the caller is denied. That is the safe direction, but nothing about the denial says the name exists nowhere. The authoring lint `validateCapabilityReferences` (ADR-0066 ⑨) closes part of - this gap: it resolves every `requiredPermissions` reference against the - capabilities known at author time and **warns** on the unresolved ones. It + this gap: it resolves every `requiredPermissions` reference, and every book's + `audience: { systemPermission }`, against the capabilities known at author time and **warns** on the unresolved ones. It reads every package of the artifact being built, so a grant in a sibling package of the same artifact counts, as it does at run time. It is a warning, not an error, because the lint cannot see capabilities declared by packages diff --git a/packages/rest/src/meta-doc-system-permission-audience.test.ts b/packages/rest/src/meta-doc-system-permission-audience.test.ts index 9f0d2c12eec..affcac26860 100644 --- a/packages/rest/src/meta-doc-system-permission-audience.test.ts +++ b/packages/rest/src/meta-doc-system-permission-audience.test.ts @@ -23,6 +23,9 @@ */ import { describe, it, expect, vi } from 'vitest'; +// Paid at collection, not inside a case's clock: `RestServer` reaches +// `@objectstack/objectql` only through dynamic imports (check:test-source-alias). +import '@objectstack/objectql'; // Explicit `.js` extension: NodeNext resolution (see the sibling nav-gate tests). import { RestServer } from './rest-server.js'; From 99447c4346f0c6dfb7779ca26d2e2c784a858afb Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:30:19 +0000 Subject: [PATCH 6/6] fix(setup,studio): manuals claim their doc namespace, not every package-less doc A package scope leaves out only a doc stamped with another package, so a stored doc bound to no package is in every scope: include '*' made both manuals claim it and gate it on setup.access / studio.access. Claim by setup_* / studio_* instead, pin an unstamped control doc on spec, REST and MCP, and correct the docs, jsdoc and changeset sentences that said otherwise. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgV8bjXeBN9N25FTesc --- .../36029-book-audience-system-permission.md | 6 +-- content/docs/ui/doc-pages.mdx | 5 +++ packages/apps/setup/src/setup-manual.book.ts | 9 +++-- .../apps/studio/src/studio-manual.book.ts | 9 +++-- ...eta-doc-system-permission-audience.test.ts | 40 ++++++++++++++++++- .../src/domains/mcp-package-docs.test.ts | 27 +++++++++++++ packages/spec/src/system/book.test.ts | 17 ++++++-- packages/spec/src/system/book.zod.ts | 10 +++-- 8 files changed, 106 insertions(+), 17 deletions(-) diff --git a/.changeset/36029-book-audience-system-permission.md b/.changeset/36029-book-audience-system-permission.md index 33b02618af1..524e3b7c36a 100644 --- a/.changeset/36029-book-audience-system-permission.md +++ b/.changeset/36029-book-audience-system-permission.md @@ -17,11 +17,11 @@ Skills-docs: none — no `skills/` page teaches the book audience forms; `conten A book's `audience` (ADR-0046 §6.7) takes a fourth form, `{ systemPermission: 'TOKEN' }`: the book's pages are read by a signed-in caller who holds that capability through any permission set, the same caller an app with `requiredPermissions: ['TOKEN']` opens for. `{ permissionSet }` names one set, so it could not gate a manual on a capability several sets grant (`setup.access` comes with `organization_admin`, `admin_full_access` and any delegated-admin set an application authors). -- **`@objectstack/spec`.** `BookAudienceSchema` and `BookAudience` gain the arm; it is strict, so a key beside `systemPermission` is refused at parse. `AudienceCaller` gains `systemPermissions`, and `audienceAllows` admits the arm only when that list holds the token; an absent list denies (fail closed). Every other form answers as before. +- **`@objectstack/spec`.** `BookAudienceSchema` and `BookAudience` gain the arm. It is strict, so `{ systemPermission, label }` is refused at parse; an object that also carries `permissionSet` still parses as the older, non-strict `{ permissionSet }` arm with the other key dropped, as before. `BookAudience` is a wider union now: TypeScript code that reads `.permissionSet` after a bare `typeof audience === 'object'` check narrows by key instead (`'permissionSet' in audience`). `AudienceCaller` gains `systemPermissions`, and `audienceAllows` admits the arm only when that list holds the token; an absent list denies (fail closed). Every other form answers as before. - **`@objectstack/rest`.** The docs audience reads the caller's own `systemPermissions` (the list every `requiredPermissions` arm of the `/meta` read gate reads) when some book carries the new form, on `GET /meta/doc` (with and without `?include=content`), `GET /meta/doc/:name`, `GET /meta/book`, `GET /meta/book/:name/tree` and the app-nav `doc` entries. New: `anySystemPermissionAudience`, and the optional `resolveAudienceSystemPermissions` port on `MetaReadGateAudienceSources` for a transport whose audience reads someone else's holdings. - **`@objectstack/runtime`.** The MCP docs tools (`search_package_docs`, `read_package_doc`) gate on the same form; on an OAuth grant they read the delegating person's own capabilities, never the token's ceiling. -- **`@objectstack/setup`, `@objectstack/studio`.** Each package now ships a manual (`setup_manual`, `studio_manual`) claiming every doc of its package, gated on `setup.access` / `studio.access`. Before, those docs were claimed by no book, so they fell back to `org`: listed to administrators only by the Console's docs index, but readable at their address, and through `?include=content`, by every signed-in member. Now a member who cannot open Setup gets `setup_overview` in neither list and a `403 PERMISSION_DENIED` on its read; an administrator reads it as before. The docs' Console address now names the manual (`/apps/com.objectstack.setup/docs/setup/setup_overview`) in place of the package's implicit one; the flat `/docs/setup_overview` permalink still finds it. +- **`@objectstack/setup`, `@objectstack/studio`.** Each package now ships a manual (`setup_manual`, `studio_manual`) claiming its package's doc namespace (`setup_*`, `studio_*`), gated on `setup.access` / `studio.access`. Before, those docs were claimed by no book, so they fell back to `org`: listed to administrators only by the Console's docs index, but readable at their address, and through `?include=content`, by every signed-in member. Now a member who cannot open Setup gets `setup_overview` in neither list and a `403 PERMISSION_DENIED` on its read; an administrator reads it as before. The docs' Console address now names the manual (`/apps/com.objectstack.setup/docs/setup/setup_overview`) in place of the package's implicit one; the flat `/docs/setup_overview` permalink still finds it. - **`@objectstack/lint`.** `capability-reference-unknown` also resolves a book's `audience.systemPermission`, so a misspelled capability (which hides the manual from everyone) warns. - **`@object-ui/app-shell`, `@object-ui/i18n`.** Studio's book preview shows a capability-gated book as "Capability: TOKEN" instead of "Org", and the book form round-trips the new form. -Nothing to migrate: no stored or authored value changes meaning. +Nothing to migrate: the manuals claim by name, so a stored doc bound to no package (which a package-scoped `include: '*'` would also have claimed) keeps the audience it had. Only docs named under those prefixes change audience: on `main` that is `setup_overview` and `studio_overview`. diff --git a/content/docs/ui/doc-pages.mdx b/content/docs/ui/doc-pages.mdx index b2de72f1a29..02d420d3365 100644 --- a/content/docs/ui/doc-pages.mdx +++ b/content/docs/ui/doc-pages.mdx @@ -254,6 +254,11 @@ manual of an app gated on a capability several sets grant: naming one of those s shut out the holders of every other one. A caller whose holdings cannot be resolved is denied — the gate fails closed. +Claim a gated book's pages by name (a namespace glob such as `include: 'crm_runbook_*'`, or +pinned `pages`), not with `include: '*'`. A package scope leaves out only a doc stamped with +*another* package, so a stored doc bound to no package is in every scope: a catch-all gated +book would claim it as well and take it away from every reader outside the audience. + The gate is a **capability** reference, never a distribution one: packages own permission sets but never positions, so a package gating its own Admin Guide keeps provenance and diff --git a/packages/apps/setup/src/setup-manual.book.ts b/packages/apps/setup/src/setup-manual.book.ts index 5f55f27095e..f0eee1de657 100644 --- a/packages/apps/setup/src/setup-manual.book.ts +++ b/packages/apps/setup/src/setup-manual.book.ts @@ -12,8 +12,11 @@ import type { Book } from '@objectstack/spec/system'; * application authors). A `{ permissionSet }` audience would name one of * those sets and shut out the holders of every other one. * - * Membership is derived (`include: '*'` over this package's own docs), so a - * page this package adds later is gated the same way with no edit here. + * Membership is derived by this package's doc namespace (`include: 'setup_*'`), + * so a page this package adds later under that prefix is gated the same way + * with no edit here. Not `'*'`: a package scope drops only a doc stamped with + * ANOTHER package, so a stored doc bound to no package (ADR-0070) is in every + * scope, and a catch-all would claim it and gate it on `setup.access` too. * Without a book claiming them, the docs fall back to `org` (§3.6): listed * only to admins by the Console's docs index, but readable at their address, * and through `?include=content`, by every member. @@ -23,5 +26,5 @@ export const SETUP_MANUAL_BOOK: Book = { label: 'Setup', slug: 'setup', audience: { systemPermission: 'setup.access' }, - groups: [{ key: 'all', label: 'Documentation', include: '*' }], + groups: [{ key: 'all', label: 'Documentation', include: 'setup_*' }], }; diff --git a/packages/apps/studio/src/studio-manual.book.ts b/packages/apps/studio/src/studio-manual.book.ts index 15efc8c880a..1327d32ef29 100644 --- a/packages/apps/studio/src/studio-manual.book.ts +++ b/packages/apps/studio/src/studio-manual.book.ts @@ -11,13 +11,16 @@ import type { Book } from '@objectstack/spec/system'; * set. A `{ permissionSet }` audience would name one set and shut out the * holders of every other one. * - * Membership is derived (`include: '*'` over this package's own docs), so a - * page this package adds later is gated the same way with no edit here. + * Membership is derived by this package's doc namespace (`include: 'studio_*'`), + * so a page this package adds later under that prefix is gated the same way + * with no edit here. Not `'*'`: a package scope drops only a doc stamped with + * ANOTHER package, so a stored doc bound to no package (ADR-0070) is in every + * scope, and a catch-all would claim it and gate it on `studio.access` too. */ export const STUDIO_MANUAL_BOOK: Book = { name: 'studio_manual', label: 'Studio', slug: 'studio', audience: { systemPermission: 'studio.access' }, - groups: [{ key: 'all', label: 'Documentation', include: '*' }], + groups: [{ key: 'all', label: 'Documentation', include: 'studio_*' }], }; diff --git a/packages/rest/src/meta-doc-system-permission-audience.test.ts b/packages/rest/src/meta-doc-system-permission-audience.test.ts index affcac26860..aa38a7bfaea 100644 --- a/packages/rest/src/meta-doc-system-permission-audience.test.ts +++ b/packages/rest/src/meta-doc-system-permission-audience.test.ts @@ -34,7 +34,15 @@ const SETUP_MANUAL = { label: 'Setup', audience: { systemPermission: 'setup.access' }, _packageId: 'com.objectstack.setup', - groups: [{ key: 'all', label: 'Documentation', include: '*' }], + // The namespace, as the shipped manual does — not '*' (see the unstamped-doc pins). + groups: [{ key: 'all', label: 'Documentation', include: 'setup_*' }], +}; +const STUDIO_MANUAL = { + name: 'studio_manual', + label: 'Studio', + audience: { systemPermission: 'studio.access' }, + _packageId: 'com.objectstack.studio', + groups: [{ key: 'all', label: 'Documentation', include: 'studio_*' }], }; const HELP_CENTER = { name: 'help_center', @@ -74,10 +82,11 @@ interface SetupOpts { /** No resolved session at all. */ anonymous?: boolean; books?: any[]; + docs?: any[]; } function setup(opts: SetupOpts = {}) { - const byType: Record = { book: opts.books ?? [SETUP_MANUAL, HELP_CENTER], doc: DOCS }; + const byType: Record = { book: opts.books ?? [SETUP_MANUAL, HELP_CENTER], doc: opts.docs ?? DOCS }; const protocol: any = { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' } }), getMetaTypes: vi.fn().mockResolvedValue([]), @@ -207,3 +216,30 @@ describe('fail closed, and no wider than it needs', () => { expect(listed((await listDocs(rest)).body)).toEqual(['crm_intro', 'setup_overview']); }); }); + +describe('a stored doc bound to no package keeps the org fallback beside both manuals', () => { + // A stored doc row bound to no package is served with no `_packageId`, and + // a package scope drops only a doc stamped with ANOTHER package — so an + // unstamped doc is in every scope. The manuals claim by namespace; this + // pins that such a doc, claimed by no other book, stays readable by a member. + const LOOSE = { name: 'loose_note', label: 'Loose note', content: 'Unbound page.' }; + const docs = [...DOCS, LOOSE]; + const books = [SETUP_MANUAL, STUDIO_MANUAL, HELP_CENTER]; + const member = () => setup({ systemPermissions: ['api.read'], books, docs }); + + it('the member lists it, with and without content, and reads it', async () => { + expect(listed((await listDocs(member().rest)).body)).toEqual(['crm_intro', 'loose_note']); + const withContent = await listDocs(member().rest, { include: 'content' }); + expect(JSON.stringify(withContent.body)).toContain('Unbound page.'); + expect(JSON.stringify(withContent.body)).not.toContain(SETUP_BODY); + const single = await readDoc(member().rest, 'loose_note'); + expect(single.statusCode).toBe(200); + }); + + it('control: a catch-all manual would claim it and shut the member out', async () => { + const catchAll = { ...SETUP_MANUAL, groups: [{ key: 'all', label: 'Documentation', include: '*' }] }; + const rest = setup({ systemPermissions: ['api.read'], books: [catchAll, HELP_CENTER], docs }).rest; + expect(listed((await listDocs(rest)).body)).toEqual(['crm_intro']); + expect(envelope(await readDoc(rest, 'loose_note'))).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + }); +}); diff --git a/packages/runtime/src/domains/mcp-package-docs.test.ts b/packages/runtime/src/domains/mcp-package-docs.test.ts index c2b21fd7894..90969567807 100644 --- a/packages/runtime/src/domains/mcp-package-docs.test.ts +++ b/packages/runtime/src/domains/mcp-package-docs.test.ts @@ -349,6 +349,33 @@ describe('a manual gated on a capability: found and read by its holders only', ( const envelope = { ...(await oauthEnvelope('u1', ['data:read'])), systemPermissions: ['crm.read_rules'] }; expect(await reach(await bridgeFor(envelope, items))).toEqual(CLOSED); }); + + // A stored doc bound to no package carries no `_packageId`, and so is in + // every package scope: a manual claiming by namespace leaves it alone, a + // catch-all would gate it on the manual's capability. + const LOOSE = { name: 'loose_payment_note', label: '回款备注', content: '# 回款备注\n\n回款登记后核对。\n' }; + const SETUP_MANUAL = (include: string) => ({ + name: 'setup_manual', + slug: 'setup', + label: 'Setup', + audience: { systemPermission: 'setup.access' }, + _packageId: 'com.objectstack.setup', + groups: [{ key: 'all', label: 'Documentation', include }], + }); + const looseReach = async (include: string) => { + const bridge = await bridgeFor(member(['api.read']), { doc: [...DOCS, LOOSE], book: [...BOOKS, SETUP_MANUAL(include)] }); + const found = (await bridge.searchPackageDocs({ terms: ['回款'] }, MAX)).results.map((r: any) => r.name); + const reads = await bridge.readPackageDoc({ name: 'loose_payment_note' }).then(() => true, () => false); + return { found: found.includes('loose_payment_note'), reads }; + }; + + it('an unstamped doc no other manual claims stays found and read by a member beside a namespaced manual', async () => { + expect(await looseReach('setup_*')).toEqual({ found: true, reads: true }); + }); + + it('control: a catch-all manual would claim that doc and shut the member out', async () => { + expect(await looseReach('*')).toEqual({ found: false, reads: false }); + }); }); describe('[#35442] search and read details', () => { diff --git a/packages/spec/src/system/book.test.ts b/packages/spec/src/system/book.test.ts index 2874e6e3a27..0be8f2e5974 100644 --- a/packages/spec/src/system/book.test.ts +++ b/packages/spec/src/system/book.test.ts @@ -472,14 +472,25 @@ describe('resolveDocAudiences — union over claiming books (§6.7)', () => { const setupBook: Book & { packageId?: string } = { name: 'setup_manual', audience: { systemPermission: 'setup.access' }, - groups: [{ key: 'all', label: 'All', include: '*' }], + groups: [{ key: 'all', label: 'All', include: 'setup_*' }], packageId: 'com.objectstack.setup', }; - const docs: ResolverDoc[] = [...corpus, { name: 'setup_overview', packageId: 'com.objectstack.setup' }]; + const docs: ResolverDoc[] = [ + ...corpus, + { name: 'setup_overview', packageId: 'com.objectstack.setup' }, + // A stored doc bound to no package: in EVERY package scope (see the + // "no stamped packageId" pin above), so only the name glob keeps it out. + { name: 'loose_note' }, + ]; const audiences = resolveDocAudiences([publicBook, adminBook, setupBook], docs); expect(audiences.get('setup_overview')).toEqual([{ systemPermission: 'setup.access' }]); - // `include: '*'` reaches only the book's own package. + // Another package's doc is outside the book's package scope … expect(audiences.get('crm_unclaimed')).toEqual(['org']); + // … and an unstamped doc outside its namespace keeps the org fallback. + expect(audiences.get('loose_note')).toEqual(['org']); + // Control: a catch-all `'*'` in the same scope WOULD claim the unstamped doc. + const catchAll = { ...setupBook, groups: [{ key: 'all', label: 'All', include: '*' }] }; + expect(resolveDocAudiences([catchAll], docs).get('loose_note')).toEqual([{ systemPermission: 'setup.access' }]); const holder = { authenticated: true, systemPermissions: ['setup.access'] }; const member = { authenticated: true, permissionSets: ['member_default'], systemPermissions: [] }; expect(docAudienceAllows(audiences.get('setup_overview'), holder)).toBe(true); diff --git a/packages/spec/src/system/book.zod.ts b/packages/spec/src/system/book.zod.ts index 81e8e5a72cf..df524f997ca 100644 --- a/packages/spec/src/system/book.zod.ts +++ b/packages/spec/src/system/book.zod.ts @@ -132,7 +132,9 @@ export type BookGroup = { * - `{ permissionSet }` — the reader holds that ONE named set; * - `{ systemPermission }` — the reader holds that capability (a * `systemPermissions` token, ADR-0066 D1) through ANY set, the same answer - * an app's `requiredPermissions: [token]` gets. This is the form for a + * an app's `requiredPermissions: [token]` gets in a session (on a delegated + * OAuth grant the delegating person's own capabilities decide, whatever the + * token carries — ADR-0090 D10). This is the form for a * manual that belongs to an app gated on a capability several sets grant * (Setup's `setup.access`): a set name would shut out every other holder. */ @@ -484,8 +486,10 @@ export interface AudienceCaller { /** * The capabilities the caller effectively holds — the `systemPermissions` * list the `/meta` read gate's `requiredPermissions` arms read, so a - * `{ systemPermission }` book opens exactly for whoever can open an app - * gated on that token. Absent/undefined means "unknown" and + * `{ systemPermission }` book opens, in a session, exactly for whoever can + * open an app gated on that token. A transport acting for someone else (the + * MCP door on a delegated OAuth grant) fills it with THAT person's + * capabilities, not the token's. Absent/undefined means "unknown" and * `{ systemPermission }` audiences DENY (fail closed, ADR-0049). */ systemPermissions?: readonly string[];