@sudoke/kernel 0.2.0 → 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/package.json +1 -1
- package/src/gate.ts +8 -8
- package/src/index.ts +3 -1
- package/src/mcp.ts +38 -7
- package/src/protocol.ts +2 -2
- package/src/queries.ts +32 -4
- package/src/state.ts +1 -0
- package/src/visibility.ts +97 -0
package/package.json
CHANGED
package/src/gate.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { maskSecrets, storageOf } from './storage.js'
|
|
|
5
5
|
import { appPolicy } from './policy.js'
|
|
6
6
|
import { applyDomainEvent } from './projections.js'
|
|
7
7
|
import { completeAssembly, errorCodeOf, eventContractOf, lookupCommand, transitionRulesOf } from './registry.js'
|
|
8
|
+
import { delegationScopeEntries, roleAllowsCommand } from './visibility.js'
|
|
8
9
|
import type { PolicyRefusal } from './policy.js'
|
|
9
10
|
import { GateError, type CommandDefinition, type DomainEvent, type Identity, type RecoveryHint } from './types.js'
|
|
10
11
|
|
|
@@ -70,10 +71,8 @@ async function delegationAllows(
|
|
|
70
71
|
def: CommandDefinition<any>,
|
|
71
72
|
input: unknown,
|
|
72
73
|
): Promise<boolean> {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
return cmd === '*' || cmd === commandName
|
|
76
|
-
})
|
|
74
|
+
// Entry selection is shared with the catalog visibility derivation (visibility.ts) — one predicate, no drift
|
|
75
|
+
const entries = delegationScopeEntries(del.scopes, commandName)
|
|
77
76
|
if (entries.length === 0) return false
|
|
78
77
|
if (entries.some((sc) => !sc.includes(':'))) return true
|
|
79
78
|
const targetId = def.scope !== 'none' ? def.targetOf?.(input as any) : undefined
|
|
@@ -314,8 +313,9 @@ async function validateStatic(def: CommandDefinition<any>, name: string, rawInpu
|
|
|
314
313
|
{ code: 'gate.delegation_denied' },
|
|
315
314
|
)
|
|
316
315
|
|
|
317
|
-
// 3 policy: role × scope — business interpretation of scope (hierarchy·inheritance included) is left to the app policy (S-01)
|
|
318
|
-
|
|
316
|
+
// 3 policy: role × scope — business interpretation of scope (hierarchy·inheritance included) is left to the app policy (S-01).
|
|
317
|
+
// The role predicate is shared with the catalog visibility derivation (visibility.ts)
|
|
318
|
+
if (!roleAllowsCommand(def, identity.role))
|
|
319
319
|
throw new GateError(3, 'policy', `Only roles [${def.allowedRoles.join('/')}] may run this command (current role: ${identity.role})`, {
|
|
320
320
|
code: 'gate.role_denied',
|
|
321
321
|
})
|
|
@@ -360,8 +360,8 @@ async function reauthorize(def: CommandDefinition<any>, name: string, input: any
|
|
|
360
360
|
})
|
|
361
361
|
// 3 role·scope — the assignment scope (scopes) used for the decision is also recalculated with current values
|
|
362
362
|
// (an assignment revoked after the request applies immediately). Calculated only for scoped commands — pulling in
|
|
363
|
-
// unscoped commands would entangle the minimal policy-free assembly test.
|
|
364
|
-
if (!def
|
|
363
|
+
// unscoped commands would entangle the minimal policy-free assembly test. Role predicate shared with visibility.ts
|
|
364
|
+
if (!roleAllowsCommand(def, current.role))
|
|
365
365
|
throw new GateError(3, 'policy', `Role recheck failed at execution time — allowed: [${def.allowedRoles.join('/')}] (current: ${current.role})`, {
|
|
366
366
|
code: 'gate.role_denied',
|
|
367
367
|
})
|
package/src/index.ts
CHANGED
|
@@ -15,10 +15,12 @@ export type { AppPolicy, PolicyRefusal } from './policy.js'
|
|
|
15
15
|
export { registerAppProjector, applyDomainEvent, eventPayloadBefore, rebuildProjections } from './projections.js'
|
|
16
16
|
export type { AppProjector, ProjectContext, ProjectionHandler } from './projections.js'
|
|
17
17
|
export { registerAppProtocol, protocolPreamble, PROTOCOL_BATCH, PROTOCOL_DELEGATION_TOKENS, PROTOCOL_EVENT_SUBSCRIPTION, PROTOCOL_LARGE_JOBS } from './protocol.js'
|
|
18
|
-
export { registerQuery, lookupQuery, allQueries, contractViolations, executeQuery, describeShape } from './queries.js'
|
|
18
|
+
export { registerQuery, lookupQuery, allQueries, contractViolations, executeQuery, describeShape, queryAccessOf } from './queries.js'
|
|
19
19
|
export type { QueryDefinition, QueryOutcome, QueryRefusal } from './queries.js'
|
|
20
20
|
export { registerRoles, registerCommand, lookupCommand, allCommands, inputShapeOf, catalogMeta, registerTransitionMachine, transitionRulesOf, allTransitionMachines, registerEventContracts, eventContractOf, allEventContractTypes, registerErrorCodes, errorCodeOf, allErrorCodes, catalogConsistencyErrors, completeAssembly, sealRegistries } from './registry.js'
|
|
21
21
|
export type { TransitionRule } from './registry.js'
|
|
22
|
+
export { roleAllowsCommand, delegationScopeEntries, commandAccessOf, visibleCatalogMeta, visibleQueriesFor, visibleTransitionMachinesFor } from './visibility.js'
|
|
23
|
+
export type { CommandAccess, CommandRestriction } from './visibility.js'
|
|
22
24
|
export { registriesSealed, resetKernelForTests } from './state.js'
|
|
23
25
|
export { registerStorage, storageOf, db, readLedger, maskSecrets, USER_STATUS_ACTIVE, USER_STATUS_DEPRECATED } from './storage.js'
|
|
24
26
|
export type { IdempotencyHit, LedgerReadRow, LedgerRow, SqlDialect, SqlStatement, StoragePort, StoredDelegation, StoredUser, UserStatus } from './storage.js'
|
package/src/mcp.ts
CHANGED
|
@@ -8,14 +8,20 @@
|
|
|
8
8
|
* The app provides only the server identity (name·version·catalog version). Commands and queries
|
|
9
9
|
* come from the kernel registry; protocol guidance comes from the common preamble plus the injected app section.
|
|
10
10
|
* Tool parameter descriptions come from the command schema's .describe(); roles and examples come from the catalog.
|
|
11
|
+
*
|
|
12
|
+
* Visibility: every tool stays registered (a hidden tool called anyway is refused by the gate), but the
|
|
13
|
+
* tool LIST and the catalog tool answer with only what the current identity may use — re-derived from the
|
|
14
|
+
* visibility module at each list/call, so role changes and delegation revocations apply to the next request.
|
|
11
15
|
*/
|
|
12
16
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
|
|
17
|
+
import { ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'
|
|
13
18
|
import { z } from 'zod'
|
|
14
19
|
import { executeCommand } from './gate.js'
|
|
15
20
|
import { identityFromToken, unauthenticated } from './auth.js'
|
|
16
21
|
import { allQueries, describeShape, executeQuery } from './queries.js'
|
|
17
22
|
import { protocolPreamble } from './protocol.js'
|
|
18
|
-
import { allCommands, allErrorCodes,
|
|
23
|
+
import { allCommands, allErrorCodes, inputShapeOf } from './registry.js'
|
|
24
|
+
import { commandAccessOf, visibleCatalogMeta, visibleQueriesFor, visibleTransitionMachinesFor } from './visibility.js'
|
|
19
25
|
|
|
20
26
|
// Identify rejections use the same contract as gate refusals (code·recovery included) — same source as REST 401 (auth.ts)
|
|
21
27
|
const denied = (reason: string) => JSON.stringify(unauthenticated(reason))
|
|
@@ -84,15 +90,16 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
|
|
|
84
90
|
}
|
|
85
91
|
|
|
86
92
|
// Catalog guidance tool — the first gate for agents that arrive without source code
|
|
87
|
-
// (what can be done + how refusals are handled + who am I)
|
|
93
|
+
// (what can be done + how refusals are handled + who am I). The document is personal: it lists
|
|
94
|
+
// only what the current identity may use, derived with the same predicates as the tool list.
|
|
88
95
|
server.registerTool(
|
|
89
96
|
'catalog',
|
|
90
|
-
{ description: 'Returns
|
|
97
|
+
{ description: 'Returns the commands·queries the CURRENT identity may use (name·description·roles·example·fields·output shape·error codes·target restrictions), the transition tables, the error-code dictionary, protocol guidance, and the current identity' },
|
|
91
98
|
async () => {
|
|
92
|
-
// Command guidance derives from catalogMeta (same source as REST /api/catalog) + the tool name
|
|
93
|
-
const cmds = catalogMeta().map((d) => ({ ...d, tool: toolNameOf(d.name) }))
|
|
94
99
|
// The identity is re-read at call time (role·assignment·delegation revocation reflected immediately)
|
|
95
100
|
const live = await liveIdentity()
|
|
101
|
+
// Command guidance derives from the visibility module (same source as REST /api/catalog) + the tool name
|
|
102
|
+
const cmds = visibleCatalogMeta(live).map((d) => ({ ...d, tool: toolNameOf(d.name) }))
|
|
96
103
|
return {
|
|
97
104
|
content: [{
|
|
98
105
|
type: 'text',
|
|
@@ -100,16 +107,17 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
|
|
|
100
107
|
ok: true,
|
|
101
108
|
version: appInfo.catalogVersion,
|
|
102
109
|
protocol: protocolPreamble(),
|
|
103
|
-
transitions:
|
|
110
|
+
transitions: visibleTransitionMachinesFor(live),
|
|
104
111
|
errorCodes: allErrorCodes(),
|
|
105
112
|
identity: live,
|
|
106
113
|
commands: cmds,
|
|
107
|
-
queries:
|
|
114
|
+
queries: visibleQueriesFor(live).map((q) => ({
|
|
108
115
|
name: q.name,
|
|
109
116
|
tool: `query_${q.name}`,
|
|
110
117
|
description: q.description,
|
|
111
118
|
clientScoped: q.clientScoped,
|
|
112
119
|
public: q.public ?? false,
|
|
120
|
+
...(q.allowedRoles ? { allowedRoles: q.allowedRoles } : {}),
|
|
113
121
|
params: Object.fromEntries(Object.entries(q.params ?? {}).map(([k, v]) => [k, describeShape(v)])),
|
|
114
122
|
output: describeShape(q.output),
|
|
115
123
|
})),
|
|
@@ -119,5 +127,28 @@ export async function buildMcpServer(appInfo: McpAppInfo, authHeader: string | u
|
|
|
119
127
|
},
|
|
120
128
|
)
|
|
121
129
|
|
|
130
|
+
// Tool-list visibility — wraps the SDK's installed tools/list handler so the answer carries only the
|
|
131
|
+
// tools the *current* identity may use. The identity is re-read at every list request (role change·
|
|
132
|
+
// delegation revocation apply to the next list, in both stdio and HTTP transports). The 'catalog'
|
|
133
|
+
// tool stays listed for any identity — it is the manual that explains a denial.
|
|
134
|
+
// Implementation note: McpServer installs its tools/list handler on the underlying Server at the first
|
|
135
|
+
// registerTool; the low-level setRequestHandler replaces it (pre-connect). The stored handler comes from
|
|
136
|
+
// the SDK's internal request-handler map — if that private shape ever changes, the wrap is skipped with a
|
|
137
|
+
// loud warning and the list stays unfiltered (the gate still refuses every hidden call at run time).
|
|
138
|
+
const lowLevel = (server as unknown as { server?: any }).server
|
|
139
|
+
const installed = lowLevel?._requestHandlers?.get?.('tools/list')
|
|
140
|
+
if (typeof installed === 'function') {
|
|
141
|
+
lowLevel.setRequestHandler(ListToolsRequestSchema, async (request: unknown, extra: unknown) => {
|
|
142
|
+
const res: any = await installed(request, extra)
|
|
143
|
+
const identity = await identityFromToken(authHeader)
|
|
144
|
+
const allowed = new Set<string>(['catalog'])
|
|
145
|
+
for (const def of allCommands()) if (commandAccessOf(def, identity).visible) allowed.add(toolNameOf(def.name))
|
|
146
|
+
for (const q of visibleQueriesFor(identity)) allowed.add(`query_${q.name}`)
|
|
147
|
+
return { ...res, tools: (res?.tools ?? []).filter((t: { name?: string }) => allowed.has(String(t?.name))) }
|
|
148
|
+
})
|
|
149
|
+
} else {
|
|
150
|
+
console.warn('[sudoke/kernel] tools/list visibility filter unavailable — the SDK handler was not found; listing unfiltered (the gate still enforces every call)')
|
|
151
|
+
}
|
|
152
|
+
|
|
122
153
|
return server
|
|
123
154
|
}
|
package/src/protocol.ts
CHANGED
|
@@ -12,8 +12,8 @@ const baseProtocol: readonly string[] = [
|
|
|
12
12
|
'A refusal with canForce:true is a warning — resend the same input with force:true to execute it. Never try to force a refusal that lacks canForce.',
|
|
13
13
|
'Each command publishes output (the shape of a successful result) and errors (the business error codes it can raise) in the catalog — the full code dictionary, including gate-common codes, is in catalog.errorCodes.',
|
|
14
14
|
'Every change is recorded in the ledger (event log) — history is never rewritten or deleted.',
|
|
15
|
-
'
|
|
16
|
-
'Queries publish their params and output —
|
|
15
|
+
'The catalog is personal: it lists only the commands·queries your current identity may use (role ∩ delegation scope). A command absent from your catalog is still refused if called directly (stage 2/3). restriction.target-policy = each call\'s target is re-approved at run time; restriction.delegation-targets = your delegation covers only the listed targets. See the identity field for who you are.',
|
|
16
|
+
'Queries publish their params and output — and allowedRoles when declared (absent = every role). Check them before building screens or tools (no need to discover shapes by calling).',
|
|
17
17
|
'The catalog document carries a version (semver) — check it on connect; if it differs from what you learned, read the catalog again. On a MAJOR bump, re-check the fields of the commands you know.',
|
|
18
18
|
'Attach a requestKey to writes that may be retried — a resend with the same key returns the stored result (prevents double creation).',
|
|
19
19
|
'dryRun:true passes validation (stages 1-7) without executing.',
|
package/src/queries.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
|
-
import type { Identity, RecoveryHint } from './types.js'
|
|
2
|
+
import type { Identity, RecoveryHint, Role } from './types.js'
|
|
3
3
|
import { unauthenticated } from './auth.js'
|
|
4
4
|
import { completeAssembly } from './registry.js'
|
|
5
5
|
import { assertOpenFor, defaultKernelState, frozenCopyOf } from './state.js'
|
|
@@ -19,6 +19,10 @@ export interface QueryDefinition {
|
|
|
19
19
|
clientScoped: boolean
|
|
20
20
|
/** Callable without login (allowlist — only explicit true) */
|
|
21
21
|
public?: boolean
|
|
22
|
+
/** Allowed roles — declared once, enforced by executeQuery and published in the catalog with the same
|
|
23
|
+
* field. Omitted = open to every registered role (the historical behavior). Contradicts public:true
|
|
24
|
+
* (a public query is callable by anyone), so declaring both fails the assembly */
|
|
25
|
+
allowedRoles?: readonly Role[]
|
|
22
26
|
/** Query parameters — derived into MCP tool input and the catalog */
|
|
23
27
|
params?: Record<string, z.ZodTypeAny>
|
|
24
28
|
/** Output contract — smoke fails when a declared field is missing from real results or has a different type */
|
|
@@ -32,6 +36,11 @@ export interface QueryDefinition {
|
|
|
32
36
|
export function registerQuery(def: QueryDefinition): void {
|
|
33
37
|
assertOpenFor(defaultKernelState, `registerQuery ${def.name}`)
|
|
34
38
|
if (defaultKernelState.queries.has(def.name)) throw new Error(`Query registered twice: ${def.name}`)
|
|
39
|
+
if (def.public === true && def.allowedRoles)
|
|
40
|
+
throw new Error(`public and allowedRoles contradict each other: ${def.name} — a public query is callable without login by anyone`)
|
|
41
|
+
for (const r of def.allowedRoles ?? [])
|
|
42
|
+
if (!defaultKernelState.roles.has(r))
|
|
43
|
+
throw new Error(`Query references an unregistered role: ${def.name} → '${r}' — register it with registerRoles first`)
|
|
35
44
|
defaultKernelState.queries.set(def.name, frozenCopyOf({ ...def }))
|
|
36
45
|
}
|
|
37
46
|
|
|
@@ -59,11 +68,28 @@ export interface QueryRefusal {
|
|
|
59
68
|
|
|
60
69
|
export type QueryOutcome = { ok: true; result: unknown } | QueryRefusal
|
|
61
70
|
|
|
71
|
+
/** Role gate for queries — the same allowedRoles declaration the catalog publishes. Returns a
|
|
72
|
+
* stage-3 refusal in the gate shape, or null when allowed. Exported so read paths that call query
|
|
73
|
+
* handlers directly (outside executeQuery) can enforce the identical contract — the declaration
|
|
74
|
+
* stays the single judge. Public queries and missing identities pass (login is checked separately) */
|
|
75
|
+
export function queryAccessOf(def: QueryDefinition, identity: Identity | null): QueryRefusal | null {
|
|
76
|
+
if (!def.allowedRoles || !identity) return null
|
|
77
|
+
if (def.allowedRoles.includes(identity.role)) return null
|
|
78
|
+
return {
|
|
79
|
+
ok: false,
|
|
80
|
+
stage: 3,
|
|
81
|
+
stageName: 'policy',
|
|
82
|
+
reason: `Only roles [${def.allowedRoles.join('/')}] may use this query (current role: ${identity.role})`,
|
|
83
|
+
code: 'query.role_denied',
|
|
84
|
+
recovery: { action: 'stop' },
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
62
88
|
/**
|
|
63
89
|
* Query execution — the read-side common entry beside the gate: params are parsed against the definition's
|
|
64
|
-
* contract, the public allowlist
|
|
65
|
-
* shape (code·recovery) just like commands. Business row scoping (clientScoped filtering)
|
|
66
|
-
* handler — the kernel does not know rows.
|
|
90
|
+
* contract, the public allowlist·identity requirement·role declaration are enforced, and failures come back
|
|
91
|
+
* in the refusal shape (code·recovery) just like commands. Business row scoping (clientScoped filtering)
|
|
92
|
+
* stays with the app handler — the kernel does not know rows.
|
|
67
93
|
*/
|
|
68
94
|
export async function executeQuery(name: string, params: Record<string, unknown>, identity: Identity | null): Promise<QueryOutcome> {
|
|
69
95
|
completeAssembly() // the first call completes an unsealed assembly — same as the write entries
|
|
@@ -71,6 +97,8 @@ export async function executeQuery(name: string, params: Record<string, unknown>
|
|
|
71
97
|
if (!def)
|
|
72
98
|
return { ok: false, stage: 0, stageName: 'registry', reason: `Unknown query: ${name}`, code: 'query.unknown', recovery: { action: 'stop' } }
|
|
73
99
|
if (!def.public && !identity) return unauthenticated('Login required — this query is not public')
|
|
100
|
+
const deniedRole = queryAccessOf(def, identity)
|
|
101
|
+
if (deniedRole) return deniedRole
|
|
74
102
|
let parsed: Record<string, string>
|
|
75
103
|
try {
|
|
76
104
|
parsed = def.params ? (z.object(def.params).parse(params ?? {}) as Record<string, string>) : ({} as Record<string, string>)
|
package/src/state.ts
CHANGED
|
@@ -68,6 +68,7 @@ const KERNEL_COMMON_ERROR_CODES: Record<string, ErrorCodeDefinition> = {
|
|
|
68
68
|
'gate.precondition_error': { description: 'Unclassified precondition error — the domain should throw GateError with a registered code (stage 5)', recovery: 'stop' },
|
|
69
69
|
'gate.invariant_error': { description: 'Unclassified invariant error — the domain should throw GateError with a registered code (stage 6)', recovery: 'stop' },
|
|
70
70
|
'query.unknown': { description: 'Call to an unregistered query', recovery: 'stop' },
|
|
71
|
+
'query.role_denied': { description: 'Query role not allowed (stage 3 policy)', recovery: 'stop' },
|
|
71
72
|
'query.params_invalid': { description: 'Query params violate the query contract', recovery: 'fix_input' },
|
|
72
73
|
'query.execution_failed': { description: 'Query handler error (often transient — safe to retry)', recovery: 'retry' },
|
|
73
74
|
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Permission visibility — the single derivation that decides which registered commands·queries·
|
|
3
|
+
* transition rules a given identity may be told about. The gate enforces permissions at run time
|
|
4
|
+
* (stage 2 delegation · stage 3 policy); this module answers the catalog-side question "what may
|
|
5
|
+
* this identity see in its manual?" using the SAME predicates, shared by construction:
|
|
6
|
+
*
|
|
7
|
+
* - roleAllowsCommand·delegationScopeEntries are the gate's own checks, extracted as pure
|
|
8
|
+
* functions so the gate and every catalog surface (REST /api/catalog · MCP catalog tool · MCP
|
|
9
|
+
* tool list) can never drift apart.
|
|
10
|
+
* - Derivation is read-only: it inspects definitions and the identity object only — no targetOf,
|
|
11
|
+
* no app-policy calls, no storage reads, no command execution, no dry-run, no audit. Building
|
|
12
|
+
* a catalog for any identity is side-effect free.
|
|
13
|
+
*
|
|
14
|
+
* The kernel knows no role names or business rules: role vocabulary and scope-kind meaning stay
|
|
15
|
+
* with the app (registerRoles · app policy). Delegation target restrictions surface the raw scope
|
|
16
|
+
* suffixes — interpreting what a target names is the reader's (app policy's) job.
|
|
17
|
+
*/
|
|
18
|
+
import type { CommandDefinition, Identity, Role } from './types.js'
|
|
19
|
+
import type { TransitionRule } from './registry.js'
|
|
20
|
+
import { allCommands, allTransitionMachines, catalogMeta } from './registry.js'
|
|
21
|
+
import { allQueries, type QueryDefinition } from './queries.js'
|
|
22
|
+
|
|
23
|
+
/** Stage-3 role predicate — the gate refuses with its own message when this returns false */
|
|
24
|
+
export function roleAllowsCommand(def: CommandDefinition<any>, role: Role): boolean {
|
|
25
|
+
return def.allowedRoles.includes(role)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Scope entries attached to a command ('*' or an exact name match) — the selection half of the
|
|
29
|
+
* gate's delegation check (G-05: entries of other commands never mix in). Target-restricted
|
|
30
|
+
* entries ('cmd:target') are included as-is; what a target refers to is the app policy's business */
|
|
31
|
+
export function delegationScopeEntries(scopes: readonly string[], commandName: string): string[] {
|
|
32
|
+
return scopes.filter((sc) => {
|
|
33
|
+
const cmd = sc.includes(':') ? sc.slice(0, sc.indexOf(':')) : sc
|
|
34
|
+
return cmd === '*' || cmd === commandName
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Target restriction attached to a visible command — how the catalog says "allowed, but not everywhere" */
|
|
39
|
+
export type CommandRestriction =
|
|
40
|
+
/** scope kind ≠ 'none': every call's target is re-approved by the app policy at run time */
|
|
41
|
+
| { type: 'target-policy' }
|
|
42
|
+
/** the delegation covers only these targets (raw scope suffixes, interpreted by the app policy) */
|
|
43
|
+
| { type: 'delegation-targets'; targets: string[] }
|
|
44
|
+
|
|
45
|
+
export type CommandAccess = { visible: false } | { visible: true; restriction?: CommandRestriction }
|
|
46
|
+
|
|
47
|
+
/** Whether (and under what restriction) an identity may be told about a command. Pure — no input,
|
|
48
|
+
* no targetOf, no policy call: a delegation with only target-restricted entries is announced as
|
|
49
|
+
* restricted rather than proven per-target (proving needs an input; the gate re-checks at execution) */
|
|
50
|
+
export function commandAccessOf(def: CommandDefinition<any>, identity: Identity | null): CommandAccess {
|
|
51
|
+
if (!identity) return { visible: false }
|
|
52
|
+
if (!roleAllowsCommand(def, identity.role)) return { visible: false }
|
|
53
|
+
if (identity.delegation) {
|
|
54
|
+
const entries = delegationScopeEntries(identity.delegation.scopes, def.name)
|
|
55
|
+
if (entries.length === 0) return { visible: false }
|
|
56
|
+
if (!entries.some((sc) => !sc.includes(':')))
|
|
57
|
+
return {
|
|
58
|
+
visible: true,
|
|
59
|
+
restriction: { type: 'delegation-targets', targets: entries.map((sc) => sc.slice(sc.indexOf(':') + 1)) },
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return def.scope !== 'none' ? { visible: true, restriction: { type: 'target-policy' } } : { visible: true }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Personal catalog guidance — catalogMeta() entries for the commands this identity may use,
|
|
66
|
+
* annotated with the target restriction. catalogMeta() and allCommands() walk the same ordered
|
|
67
|
+
* registry, so indexes pair 1:1. Deriving writes nothing (registry·ledger·audit untouched) */
|
|
68
|
+
export function visibleCatalogMeta(identity: Identity | null) {
|
|
69
|
+
const meta = catalogMeta()
|
|
70
|
+
return allCommands().flatMap((def, i) => {
|
|
71
|
+
const access = commandAccessOf(def, identity)
|
|
72
|
+
return access.visible
|
|
73
|
+
? [{ ...meta[i], ...(access.restriction ? { restriction: access.restriction } : {}) }]
|
|
74
|
+
: []
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Queries this identity may be told about — allowedRoles (omitted = open to every role, the
|
|
79
|
+
* historical behavior) is the same declaration executeQuery enforces */
|
|
80
|
+
export function visibleQueriesFor(identity: Identity | null): QueryDefinition[] {
|
|
81
|
+
if (!identity) return allQueries().filter((q) => q.public === true)
|
|
82
|
+
return allQueries().filter((q) => !q.allowedRoles || q.allowedRoles.includes(identity.role))
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Transition rules this identity may act on — a rule stays when its command is visible to the
|
|
86
|
+
* identity AND the rule's roles include the identity's role. Machines with no remaining rule are
|
|
87
|
+
* dropped entirely (an empty table would read as "everything forbidden" instead of "nothing to say") */
|
|
88
|
+
export function visibleTransitionMachinesFor(identity: Identity | null): Record<string, readonly TransitionRule[]> {
|
|
89
|
+
if (!identity) return {}
|
|
90
|
+
const visible = new Set(allCommands().filter((def) => commandAccessOf(def, identity).visible).map((def) => def.name))
|
|
91
|
+
const out: Record<string, readonly TransitionRule[]> = {}
|
|
92
|
+
for (const [machine, rules] of Object.entries(allTransitionMachines())) {
|
|
93
|
+
const kept = rules.filter((r) => visible.has(r.command) && r.roles.includes(identity!.role))
|
|
94
|
+
if (kept.length > 0) out[machine] = kept
|
|
95
|
+
}
|
|
96
|
+
return out
|
|
97
|
+
}
|