@bitakit/core 0.2.9 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -16,11 +16,31 @@ rarely call the runtime directly: files in `src/plugins/<id>/` are discovered, a
16
16
  | `actions/<name>.ts` | `defineAction({ title, enabled, execute, ... })` | `<plugin>.<name>` |
17
17
  | `events.ts` | `defineEvents({ changed: event<T>() })` | `<plugin>.changed` |
18
18
  | `settings.ts` | `defineSettings({ name: setting({ default }) }, page)` | `<plugin>.<name>` |
19
+ | `permissions.ts` | `definePermissions({ content: ['read', 'edit'] })` | `<resource>` |
19
20
  | `slots/<name>.ts` | `defineSlot({ accepts, policy?, payload? })` | `<plugin>.<name>` |
20
21
  | `interceptors/<name>.ts` | `defineInterceptor({ action or service, before, after })` | — |
21
22
  | `configs/<name>.ts` | `defineConfig({ defaults, schema? })` | `<plugin>.<name>` |
22
23
  | `setup.ts` | `Setup` function (`scope.slots.attach`, cleanup) | — |
23
24
 
25
+ The app declares its base roles once in `src/roles.ts` with `defineRoles({ ... }, { customRoles })`.
26
+
27
+ ## Roles and permissions
28
+
29
+ - Core holds only the vocabulary: `definePermissions`, `defineRoles`, the composed catalog and
30
+ its checks. It stores nothing and authorizes nothing; the authorization provider (for example
31
+ the Better Auth adapter) translates the declarations and decides every check on the server.
32
+ - A plugin declares the resources and operations it owns, never roles. One resource has one
33
+ owning plugin.
34
+ - Only the app declares base roles (`src/roles.ts`): `standard` extends the provider's built-in
35
+ `owner`, `admin` or `member`; `label` and `description` are defaults that translations
36
+ override; `grants` lists operations from the catalog (typed by `bitakit generate`). Declaration
37
+ order is display order, never a permission hierarchy.
38
+ - `bitakit generate` writes `bitakit.gen.access.ts` with the composed `accessConfiguration`
39
+ (server-safe data) for authorization adapters.
40
+ - Conflicts fail before the app runs, at generation and again at startup: a resource claimed
41
+ twice, a grant of an unknown resource or operation, a standard role extended twice, roles in a
42
+ plugin. Nothing is resolved by registration order or merging.
43
+
24
44
  ## Slots and replaceable parts
25
45
 
26
46
  - `policy: 'list'` (default): every contribution renders. `'keyed'`: outlets pick one by key.
package/dist/core.d.ts CHANGED
@@ -5,6 +5,8 @@ export type { EventsDefinition, EventSpec, EventsOf, CancelableOf } from './even
5
5
  export type * from './events/types.js';
6
6
  export type { GeneratedName, CheckedName } from './names.js';
7
7
  export { EventService } from './events/service.js';
8
+ export { definePermissions, defineRoles, isPermissionsDefinition, isRolesDefinition, standardRoles, composePermissions, composeAccessConfiguration, roleProblems, AccessConfigurationError, } from './permissions.js';
9
+ export type { PermissionMap, RoleMap, PermissionSpec, PermissionsDefinition, StandardRole, RoleSpec, RolesOptions, RolesDefinition, PermissionResource, PermissionCatalog, AccessConfiguration, PermissionsOf, RoleIdsOf, } from './permissions.js';
8
10
  export { defineSettings, setting, isSettingsDefinition, isSettingSpec, parseSetting, } from './settings/define.js';
9
11
  export type { SettingSpec, SettingScope, SettingControl, SettingOption, SettingsDefinition, SettingsSectionOptions, SettingsMap, SettingKey, SettingValue, SettingsOf, } from './settings/define.js';
10
12
  export { SettingsStore, type SettingState, type SaveResult, type SettingsIdentity, type SettingEntry, } from './settings/store.js';
package/dist/core.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { defineService, defineAction, definePlugin, dialogOf, isActionSpec, isServiceDefinition, } from './definitions.js';
2
2
  export { defineEvents, event, isEventsDefinition } from './events/define.js';
3
3
  export { EventService } from './events/service.js';
4
+ export { definePermissions, defineRoles, isPermissionsDefinition, isRolesDefinition, standardRoles, composePermissions, composeAccessConfiguration, roleProblems, AccessConfigurationError, } from './permissions.js';
4
5
  export { defineSettings, setting, isSettingsDefinition, isSettingSpec, parseSetting, } from './settings/define.js';
5
6
  export { SettingsStore, } from './settings/store.js';
6
7
  export { settingsStorage, settingsOwner, createMemorySettingsStorage, createLocalSettingsStorage, } from './settings/storage.js';
@@ -319,6 +319,8 @@ export type Plugin = {
319
319
  slots?: SlotDefinitions | readonly SlotDefinition[];
320
320
  events?: EventsDefinition<any>;
321
321
  settings?: SettingsDefinition<any>;
322
+ /** Resources and operations this module owns (`permissions.ts`); never roles. */
323
+ permissions?: import('./permissions.js').PermissionsDefinition;
322
324
  config?: ConfigValues | ConfigDefinition;
323
325
  interceptors?: readonly InterceptorSpec[];
324
326
  setup?: Setup;
@@ -331,6 +333,8 @@ export type Plugin = {
331
333
  export declare function definePlugin<const T extends Plugin>(plugin: T): T;
332
334
  export type BitaKitRuntimeConfig = Omit<Plugin, 'id' | 'dependencies' | 'parent'> & {
333
335
  appId?: string;
336
+ /** The app's base roles (`src/roles.ts`); only the app declares roles. */
337
+ roles?: import('./permissions.js').RolesDefinition;
334
338
  dependencies?: readonly string[];
335
339
  /** Receives synchronous throws and async rejections from event handlers. */
336
340
  onEventError?: import('./events/types.js').EventErrorHandler;
@@ -1,5 +1,6 @@
1
1
  import { type Contribution, type ServiceDefinition, type ActionEntry } from './definitions.js';
2
2
  import { type ResolvedSlotDefinition, type SlotEntry } from './slots/define.js';
3
+ import { type PermissionsDefinition, type RolesDefinition } from './permissions.js';
3
4
  import type { ContractName } from './service-key.js';
4
5
  import { type InterceptorSpec } from './interceptors/define.js';
5
6
  import { type CancelableOf, type EventsDefinition, type EventsOf } from './events/define.js';
@@ -26,6 +27,10 @@ export declare function discoverInterceptors(files: readonly DiscoveredFile[]):
26
27
  export declare function discoverEvents(files: readonly DiscoveredFile[]): EventsDefinition | undefined;
27
28
  /** The one `settings.ts` of a module. */
28
29
  export declare function discoverSettings(files: readonly DiscoveredFile[]): SettingsDefinition | undefined;
30
+ /** A module's `permissions.ts`: one file, `definePermissions({ ... })`; the source is kept for diagnostics. */
31
+ export declare function discoverPermissions(files: readonly DiscoveredFile[]): PermissionsDefinition | undefined;
32
+ /** The app's `roles.ts`: one file, `defineRoles({ ... })`; the source is kept for diagnostics. */
33
+ export declare function discoverRoles(files: readonly DiscoveredFile[]): RolesDefinition | undefined;
29
34
  /** File assembly rejects overlapping leaves; intentional overrides happen later in ConfigService. */
30
35
  export declare function discoverConfig(files: readonly DiscoveredFile[]): ConfigValues | ConfigDefinition;
31
36
  type Join<A extends string, B extends string> = A extends '' ? B : B extends '' ? A : `${A}.${B}`;
@@ -4,6 +4,7 @@ import { resolveContribution } from './conventions.js';
4
4
  import { actionIdPattern } from './conventions.js';
5
5
  import { isSlotDefinition } from './slots/define.js';
6
6
  import { BitaKitStartupError } from './startup-error.js';
7
+ import { isPermissionsDefinition, isRolesDefinition, } from './permissions.js';
7
8
  import { defineInterceptor } from './interceptors/define.js';
8
9
  import { isEventsDefinition, } from './events/define.js';
9
10
  import { isConfigDefinition, isConfigObject, } from './config-service.js';
@@ -126,6 +127,28 @@ export function discoverSettings(files) {
126
127
  throw new Error(`${file.source} must default-export defineSettings({ ... }).`);
127
128
  return file.value;
128
129
  }
130
+ /** A module's `permissions.ts`: one file, `definePermissions({ ... })`; the source is kept for diagnostics. */
131
+ export function discoverPermissions(files) {
132
+ if (!files.length)
133
+ return undefined;
134
+ if (files.length > 1)
135
+ throw new Error(`A module declares its permissions in one file: ${files.map((file) => file.source).join(', ')}`);
136
+ const [file] = files;
137
+ if (!isPermissionsDefinition(file.value))
138
+ throw new Error(`${file.source} must default-export definePermissions({ ... }).`);
139
+ return Object.freeze({ ...file.value, source: file.source });
140
+ }
141
+ /** The app's `roles.ts`: one file, `defineRoles({ ... })`; the source is kept for diagnostics. */
142
+ export function discoverRoles(files) {
143
+ if (!files.length)
144
+ return undefined;
145
+ if (files.length > 1)
146
+ throw new Error(`The app declares its roles in one file: ${files.map((file) => file.source).join(', ')}`);
147
+ const [file] = files;
148
+ if (!isRolesDefinition(file.value))
149
+ throw new Error(`${file.source} must default-export defineRoles({ ... }).`);
150
+ return Object.freeze({ ...file.value, source: file.source });
151
+ }
129
152
  /** File assembly rejects overlapping leaves; intentional overrides happen later in ConfigService. */
130
153
  export function discoverConfig(files) {
131
154
  const schemaRoot = files.find((file) => !file.path && isConfigDefinition(file.value));
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Resources and their operations a plugin owns, for example `{ content: ['read', 'edit', 'publish'] }`.
3
+ * Generated declarations extend it, so role grants are typed against the discovered catalog.
4
+ */
5
+ export interface PermissionMap {
6
+ }
7
+ /** Role IDs of the app's `roles.ts`; generated declarations extend it. */
8
+ export interface RoleMap {
9
+ }
10
+ export type PermissionSpec = Readonly<Record<string, readonly string[]>>;
11
+ export type PermissionsDefinition<Spec extends PermissionSpec = PermissionSpec> = {
12
+ readonly kind: 'permissions';
13
+ readonly permissions: Spec;
14
+ /** Project-relative file, set by discovery for diagnostics. */
15
+ readonly source?: string;
16
+ };
17
+ /**
18
+ * Declares the resources and operations a plugin owns, in its `permissions.ts`. A plugin declares
19
+ * capabilities only; which roles receive them is the app's decision in `roles.ts`.
20
+ */
21
+ export declare function definePermissions<const Spec extends PermissionSpec>(permissions: Spec): PermissionsDefinition<Spec>;
22
+ export declare function isPermissionsDefinition(value: unknown): value is PermissionsDefinition;
23
+ /** A provider's built-in organization roles a base role can extend. */
24
+ export type StandardRole = 'owner' | 'admin' | 'member';
25
+ export declare const standardRoles: readonly StandardRole[];
26
+ type KnownGrants = keyof PermissionMap extends never ? Readonly<Record<string, readonly string[]>> : {
27
+ readonly [Resource in keyof PermissionMap]?: readonly PermissionMap[Resource][];
28
+ };
29
+ export type RoleSpec = {
30
+ /** Extends the provider's built-in role with the explicit grants below. */
31
+ readonly standard?: StandardRole;
32
+ /** Default label; a translation `roles.<id>.label` wins. */
33
+ readonly label?: string;
34
+ /** Default explanation; a translation `roles.<id>.description` wins. */
35
+ readonly description?: string;
36
+ /** Operations per resource this role receives, from the discovered permission catalog. */
37
+ readonly grants?: KnownGrants;
38
+ };
39
+ export type RolesOptions = {
40
+ /** Let organizations create their own roles through the provider's dynamic roles. */
41
+ readonly customRoles?: boolean;
42
+ };
43
+ export type RolesDefinition<Roles extends Readonly<Record<string, RoleSpec>> = Readonly<Record<string, RoleSpec>>> = {
44
+ readonly kind: 'roles';
45
+ /** In declaration order: display order only, never a permission hierarchy. */
46
+ readonly roles: Roles;
47
+ readonly options: RolesOptions;
48
+ /** Project-relative file, set by discovery for diagnostics. */
49
+ readonly source?: string;
50
+ };
51
+ /**
52
+ * Declares the app's base roles in `src/roles.ts`. Roles are app configuration: plugins declare
53
+ * permissions, never roles, and base roles are read-only for organizations.
54
+ */
55
+ export declare function defineRoles<const Roles extends Readonly<Record<string, RoleSpec>>>(roles: Roles, options?: RolesOptions): RolesDefinition<Roles>;
56
+ export declare function isRolesDefinition(value: unknown): value is RolesDefinition;
57
+ /** Generated typing: the resources and operations of one `permissions.ts`. */
58
+ export type PermissionsOf<T> = T extends PermissionsDefinition<infer Spec> ? {
59
+ -readonly [Resource in keyof Spec]: Spec[Resource][number];
60
+ } : {};
61
+ /** Generated typing: the role IDs of the app's `roles.ts`. */
62
+ export type RoleIdsOf<T> = T extends RolesDefinition<infer Roles> ? {
63
+ -readonly [Id in keyof Roles]: true;
64
+ } : {};
65
+ /** One resource of the composed catalog with its owning module. */
66
+ export type PermissionResource = {
67
+ readonly owner: string;
68
+ readonly source?: string;
69
+ readonly actions: readonly string[];
70
+ };
71
+ export type PermissionCatalog = Readonly<Record<string, PermissionResource>>;
72
+ /** Configuration errors of roles and permissions, collected so every problem is reported at once. */
73
+ export declare class AccessConfigurationError extends Error {
74
+ readonly problems: readonly string[];
75
+ constructor(problems: readonly string[]);
76
+ }
77
+ /**
78
+ * Composes the modules' permission declarations into one catalog. A resource has exactly one
79
+ * owning module; a second claim is an error, never resolved by order or merging.
80
+ */
81
+ export declare function composePermissions(declarations: readonly {
82
+ owner: string;
83
+ definition: PermissionsDefinition;
84
+ }[]): PermissionCatalog;
85
+ /**
86
+ * Checks the app's base roles against the catalog: every granted resource and operation must be
87
+ * declared. Returns the problems instead of fixing anything.
88
+ */
89
+ export declare function roleProblems(roles: RolesDefinition, catalog: PermissionCatalog): string[];
90
+ /** Composed, validated access configuration: the permission catalog and the app's base roles. */
91
+ export type AccessConfiguration = {
92
+ readonly permissions: PermissionCatalog;
93
+ readonly roles?: RolesDefinition;
94
+ };
95
+ /** Composes and validates everything at once; throws one error listing every problem. */
96
+ export declare function composeAccessConfiguration(input: {
97
+ permissions: readonly {
98
+ owner: string;
99
+ definition: PermissionsDefinition;
100
+ }[];
101
+ roles?: RolesDefinition;
102
+ }): AccessConfiguration;
103
+ export {};
@@ -0,0 +1,172 @@
1
+ // Roles and permissions as configuration (0.3). Core owns only the vocabulary: the declaration shapes, their
2
+ // validation and the composed catalog. It has no provider dependency, stores nothing and authorizes nothing; an
3
+ // authorization provider (for example the Better Auth adapter) translates the declarations into its own configuration
4
+ // and remains the authority on every check.
5
+ const identifier = /^[a-z][a-zA-Z0-9-]*$/;
6
+ const show = (values) => values.map((value) => `"${value}"`).join(', ');
7
+ /**
8
+ * Declares the resources and operations a plugin owns, in its `permissions.ts`. A plugin declares
9
+ * capabilities only; which roles receive them is the app's decision in `roles.ts`.
10
+ */
11
+ export function definePermissions(permissions) {
12
+ if (!permissions || typeof permissions !== 'object' || Array.isArray(permissions))
13
+ throw new Error("definePermissions expects a record: definePermissions({ content: ['read', 'edit'] }).");
14
+ const resources = Object.keys(permissions);
15
+ if (!resources.length)
16
+ throw new Error('definePermissions needs at least one resource.');
17
+ for (const resource of resources) {
18
+ if (!identifier.test(resource))
19
+ throw new Error(`Invalid permission resource "${resource}". Start with a lowercase letter; use letters, digits and "-".`);
20
+ const actions = permissions[resource];
21
+ if (!Array.isArray(actions) || !actions.length)
22
+ throw new Error(`Permission resource "${resource}" needs a non-empty list of operations.`);
23
+ for (const action of actions)
24
+ if (typeof action !== 'string' || !identifier.test(action))
25
+ throw new Error(`Invalid operation "${String(action)}" of permission resource "${resource}". Start with a lowercase letter; use letters, digits and "-".`);
26
+ if (new Set(actions).size !== actions.length)
27
+ throw new Error(`Permission resource "${resource}" lists an operation twice.`);
28
+ }
29
+ return Object.freeze({
30
+ kind: 'permissions',
31
+ permissions: Object.freeze(Object.fromEntries(resources.map((resource) => [resource, Object.freeze([...permissions[resource]])]))),
32
+ });
33
+ }
34
+ export function isPermissionsDefinition(value) {
35
+ return (!!value && typeof value === 'object' && value.kind === 'permissions');
36
+ }
37
+ export const standardRoles = Object.freeze(['owner', 'admin', 'member']);
38
+ /**
39
+ * Declares the app's base roles in `src/roles.ts`. Roles are app configuration: plugins declare
40
+ * permissions, never roles, and base roles are read-only for organizations.
41
+ */
42
+ export function defineRoles(roles, options = {}) {
43
+ if (!roles || typeof roles !== 'object' || Array.isArray(roles))
44
+ throw new Error("defineRoles expects a record: defineRoles({ viewer: { grants: { content: ['read'] } } }).");
45
+ const ids = Object.keys(roles);
46
+ if (!ids.length)
47
+ throw new Error('defineRoles needs at least one role.');
48
+ const standards = new Map();
49
+ for (const id of ids) {
50
+ if (!identifier.test(id))
51
+ throw new Error(`Invalid role "${id}". Start with a lowercase letter; use letters, digits and "-".`);
52
+ const spec = roles[id];
53
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec))
54
+ throw new Error(`Role "${id}" must be an object, for example { grants: { ... } }.`);
55
+ const unknownKeys = Object.keys(spec).filter((key) => !['standard', 'label', 'description', 'grants'].includes(key));
56
+ if (unknownKeys.length)
57
+ throw new Error(`Role "${id}" has unknown fields ${show(unknownKeys)}. Use standard, label, description and grants.`);
58
+ if (spec.standard !== undefined) {
59
+ if (!standardRoles.includes(spec.standard))
60
+ throw new Error(`Role "${id}" extends unknown standard role "${String(spec.standard)}". Use ${show(standardRoles)}.`);
61
+ const other = standards.get(spec.standard);
62
+ if (other)
63
+ throw new Error(`Roles "${other}" and "${id}" both extend the standard role "${spec.standard}". Each standard role is extended once.`);
64
+ standards.set(spec.standard, id);
65
+ }
66
+ for (const field of ['label', 'description'])
67
+ if (spec[field] !== undefined && (typeof spec[field] !== 'string' || !spec[field].trim()))
68
+ throw new Error(`The ${field} of role "${id}" must be a non-empty text.`);
69
+ if (spec.grants !== undefined) {
70
+ if (!spec.grants || typeof spec.grants !== 'object' || Array.isArray(spec.grants))
71
+ throw new Error(`The grants of role "${id}" must be a record of operation lists.`);
72
+ for (const [resource, actions] of Object.entries(spec.grants)) {
73
+ if (!Array.isArray(actions) || !actions.length)
74
+ throw new Error(`Role "${id}" grants "${resource}" without operations. List them or remove the resource.`);
75
+ if (new Set(actions).size !== actions.length)
76
+ throw new Error(`Role "${id}" grants an operation of "${resource}" twice.`);
77
+ }
78
+ }
79
+ }
80
+ if (options.customRoles !== undefined && typeof options.customRoles !== 'boolean')
81
+ throw new Error('defineRoles: the customRoles option is true or false.');
82
+ return Object.freeze({
83
+ kind: 'roles',
84
+ roles: Object.freeze(Object.fromEntries(ids.map((id) => {
85
+ const spec = roles[id];
86
+ return [
87
+ id,
88
+ Object.freeze({
89
+ ...spec,
90
+ ...(spec.grants
91
+ ? {
92
+ grants: Object.freeze(Object.fromEntries(Object.entries(spec.grants).map(([resource, actions]) => [resource, Object.freeze([...actions])]))),
93
+ }
94
+ : {}),
95
+ }),
96
+ ];
97
+ }))),
98
+ options: Object.freeze({ ...options }),
99
+ });
100
+ }
101
+ export function isRolesDefinition(value) {
102
+ return !!value && typeof value === 'object' && value.kind === 'roles';
103
+ }
104
+ /** Configuration errors of roles and permissions, collected so every problem is reported at once. */
105
+ export class AccessConfigurationError extends Error {
106
+ problems;
107
+ constructor(problems) {
108
+ super(`Roles and permissions are misconfigured:\n- ${problems.join('\n- ')}`);
109
+ this.name = 'AccessConfigurationError';
110
+ this.problems = problems;
111
+ }
112
+ }
113
+ const where = (owner, source) => source ? `"${owner}" (${source})` : `"${owner}"`;
114
+ /**
115
+ * Composes the modules' permission declarations into one catalog. A resource has exactly one
116
+ * owning module; a second claim is an error, never resolved by order or merging.
117
+ */
118
+ export function composePermissions(declarations) {
119
+ const catalog = Object.create(null);
120
+ const problems = [];
121
+ for (const { owner, definition } of declarations) {
122
+ if (!isPermissionsDefinition(definition)) {
123
+ problems.push(`${where(owner, definition?.source)} must default-export definePermissions({ ... }) in permissions.ts.`);
124
+ continue;
125
+ }
126
+ for (const [resource, actions] of Object.entries(definition.permissions)) {
127
+ const claimed = catalog[resource];
128
+ if (claimed) {
129
+ problems.push(`Permission resource "${resource}" is declared by ${where(claimed.owner, claimed.source)} and ${where(owner, definition.source)}. A resource has one owning plugin: rename one resource, or keep it in one plugin and use it from the other.`);
130
+ continue;
131
+ }
132
+ catalog[resource] = Object.freeze({ owner, source: definition.source, actions });
133
+ }
134
+ }
135
+ if (problems.length)
136
+ throw new AccessConfigurationError(problems);
137
+ return Object.freeze(catalog);
138
+ }
139
+ /**
140
+ * Checks the app's base roles against the catalog: every granted resource and operation must be
141
+ * declared. Returns the problems instead of fixing anything.
142
+ */
143
+ export function roleProblems(roles, catalog) {
144
+ const problems = [];
145
+ const file = roles.source ? ` in ${roles.source}` : '';
146
+ const known = Object.keys(catalog);
147
+ for (const [id, spec] of Object.entries(roles.roles)) {
148
+ for (const [resource, actions] of Object.entries((spec.grants ?? {}))) {
149
+ const declared = catalog[resource];
150
+ if (!declared) {
151
+ problems.push(`Role "${id}"${file} grants unknown resource "${resource}". Declared resources: ${known.length ? show(known) : 'none'}. Fix the grant or declare the resource in the owning plugin's permissions.ts.`);
152
+ continue;
153
+ }
154
+ const unknown = actions.filter((action) => !declared.actions.includes(action));
155
+ if (unknown.length)
156
+ problems.push(`Role "${id}"${file} grants unknown operations ${show(unknown)} of "${resource}" (declared by ${where(declared.owner, declared.source)}: ${show(declared.actions)}).`);
157
+ }
158
+ }
159
+ return problems;
160
+ }
161
+ /** Composes and validates everything at once; throws one error listing every problem. */
162
+ export function composeAccessConfiguration(input) {
163
+ const permissions = composePermissions(input.permissions);
164
+ if (input.roles !== undefined && !isRolesDefinition(input.roles))
165
+ throw new AccessConfigurationError([
166
+ `${input.roles?.source ?? 'roles.ts'} must default-export defineRoles({ ... }).`,
167
+ ]);
168
+ const problems = input.roles ? roleProblems(input.roles, permissions) : [];
169
+ if (problems.length)
170
+ throw new AccessConfigurationError(problems);
171
+ return Object.freeze({ permissions, ...(input.roles ? { roles: input.roles } : {}) });
172
+ }
package/dist/runtime.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { resolveName } from './name-resolution.js';
2
2
  import { EventService, createEventScope } from './events/service.js';
3
3
  import { normalizeSlots, validateSlotDeclarations } from './slots/normalize.js';
4
+ import { AccessConfigurationError, composeAccessConfiguration, isPermissionsDefinition, } from './permissions.js';
4
5
  import { SlotRuntime } from './slots/runtime.js';
5
6
  import { ConfigService } from './config-service.js';
6
7
  import { contributionPath, contributionSource, preserveContributionPath, setContributionPath, } from './contribution-origin.js';
@@ -72,6 +73,10 @@ function normalize(module, appId) {
72
73
  });
73
74
  if (module.settings !== undefined && !isSettingsDefinition(module.settings))
74
75
  throw new Error('settings must be declared with defineSettings({ ... }) in settings.ts.');
76
+ if (module.permissions !== undefined && !isPermissionsDefinition(module.permissions))
77
+ throw new Error('permissions must be declared with definePermissions({ ... }) in permissions.ts.');
78
+ if (!isApp && module.roles !== undefined)
79
+ throw new Error("Base roles belong to the app's src/roles.ts; a plugin declares permissions, never roles.");
75
80
  if (module.parent === id)
76
81
  throw new Error('A plugin cannot be its own parent.');
77
82
  return {
@@ -93,6 +98,31 @@ function normalize(module, appId) {
93
98
  throw attributed(error, id, 'Plugin definition', appId);
94
99
  }
95
100
  }
101
+ /**
102
+ * Roles and permissions are configuration: every module's permissions compose into one catalog
103
+ * and the app's base roles may only grant declared operations. Problems stop the start with one
104
+ * error naming each conflict; nothing is resolved by registration order.
105
+ */
106
+ function validateAccessDeclarations(modules, appId) {
107
+ const app = modules.find((module) => module.id === appId);
108
+ try {
109
+ composeAccessConfiguration({
110
+ permissions: modules
111
+ .filter((module) => module.permissions !== undefined)
112
+ .map((module) => ({ owner: module.id, definition: module.permissions })),
113
+ roles: app?.roles,
114
+ });
115
+ }
116
+ catch (error) {
117
+ if (error instanceof AccessConfigurationError)
118
+ throw new BitaKitStartupError(error.message, appId, {
119
+ app: true,
120
+ cause: error,
121
+ source: app?.roles?.source,
122
+ });
123
+ throw error;
124
+ }
125
+ }
96
126
  /** Installed plugins owned, directly or through other children, by any of `ids`. */
97
127
  function descendantsOf(installed, ids) {
98
128
  const found = [];
@@ -295,6 +325,7 @@ export class BitaKitRuntime {
295
325
  ];
296
326
  this.order = orderPlugins(this.modules, this.appId);
297
327
  validateSlotDeclarations(this.modules, this.appId);
328
+ validateAccessDeclarations(this.modules, this.appId);
298
329
  this.events = new EventService(config.onEventError);
299
330
  const publishLifecycle = this.events.reserve('runtime');
300
331
  this.lifecycleState = createLifecycleState(this.modules.map((module) => module.id), this.serviceEntries().filter((entry) => !Object.hasOwn(this.providedServices, entry.id)), (snapshot) => publishLifecycle('runtime.lifecycle', snapshot), (error) => this.reportLifecycleError(error));
@@ -1284,6 +1315,7 @@ export class BitaKitRuntime {
1284
1315
  const declarations = [app, ...nextInstalled.map((plugin) => normalize(plugin, this.appId))];
1285
1316
  orderPlugins(all, this.appId);
1286
1317
  validateSlotDeclarations(declarations, this.appId);
1318
+ validateAccessDeclarations(all, this.appId);
1287
1319
  validatePluginPages(all, layoutFamilies(all));
1288
1320
  // Failed updates may have already disposed a projection's scope. Recover its recorded
1289
1321
  // failure cohort when the host retries one of those owners, without restarting other failures.
@@ -1436,6 +1468,7 @@ export class BitaKitRuntime {
1436
1468
  ];
1437
1469
  orderPlugins(all, this.appId);
1438
1470
  validateSlotDeclarations(all, this.appId);
1471
+ validateAccessDeclarations(all, this.appId);
1439
1472
  validatePluginPages(all, layoutFamilies(all));
1440
1473
  // A projection that captured the composition is an explicit consumer of every revision.
1441
1474
  affected = updateClosure(all, [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bitakit/core",
3
- "version": "0.2.9",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "files": [
@@ -42,7 +42,7 @@
42
42
  "zustand": "^5.0.0"
43
43
  },
44
44
  "peerDependencies": {
45
- "@bitakit/discovery": "^0.2.5",
45
+ "@bitakit/discovery": "^0.3.0",
46
46
  "jiti": "^2.7.0"
47
47
  },
48
48
  "peerDependenciesMeta": {
@@ -54,7 +54,7 @@
54
54
  }
55
55
  },
56
56
  "devDependencies": {
57
- "@bitakit/discovery": "^0.2.6",
57
+ "@bitakit/discovery": "^0.3.0",
58
58
  "jiti": "^2.7.0",
59
59
  "typescript": "^5.9.3"
60
60
  },