@workbasehq/core 0.2.15 → 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 +18 -3
- package/src/access-evaluator.ts +72 -0
- package/src/access-guards.ts +35 -0
- package/src/access-inputs.ts +62 -0
- package/src/access-lock/cli.ts +34 -0
- package/src/access-lock.ts +183 -0
- package/src/access.ts +209 -0
- package/src/account-action-conditions.ts +27 -0
- package/src/account-command.ts +8 -0
- package/src/admin-ui.tsx +3 -2
- package/src/app.ts +3 -3
- package/src/canonical.ts +6 -0
- package/src/capabilities.ts +5 -3
- package/src/commands.ts +14 -8
- package/src/config.ts +105 -69
- package/src/console-build.ts +37 -0
- package/src/console-contract.ts +4 -0
- package/src/console-model.ts +2 -0
- package/src/console.ts +3 -3
- package/src/crud.ts +13 -7
- package/src/dev-mailbox.ts +35 -0
- package/src/display-identity.ts +12 -0
- package/src/execution/atomic.ts +17 -3
- package/src/execution/policies.ts +14 -6
- package/src/execution/policy-receipts.ts +6 -5
- package/src/execution/post-commit.ts +11 -0
- package/src/execution/types.ts +1 -1
- package/src/index.ts +2 -0
- package/src/infra/README.md +39 -3
- package/src/infra/d1-migrations.ts +4 -3
- package/src/infra/instance-migrations.ts +26 -5
- package/src/infra/provision-config-main.mjs +3 -3
- package/src/infra/provision-diagnostics.ts +4 -0
- package/src/infra/provision-plan.ts +34 -5
- package/src/infra/provision.ts +26 -4
- package/src/infra/schema.ts +1 -1
- package/src/kernel/invitation-mail-port.ts +26 -0
- package/src/kernel/mail-outbox-port.ts +4 -2
- package/src/kernel/migrations.ts +38 -15
- package/src/kernel/plugin.ts +2 -0
- package/src/kernel/predicate.ts +15 -3
- package/src/kernel/registry.ts +69 -12
- package/src/member-bootstrap.ts +65 -0
- package/src/member-identities.ts +42 -0
- package/src/migrations/diagnostics.ts +6 -1
- package/src/migrations/model-b.ts +2 -1
- package/src/migrations/operational-evidence.ts +51 -0
- package/src/migrations/planner.ts +12 -1
- package/src/migrations/rebuild.ts +17 -12
- package/src/migrations/reset-era.ts +29 -0
- package/src/migrations/schema-bundle.ts +43 -0
- package/src/migrations/schema-cli.ts +74 -0
- package/src/migrations/schema-git.ts +36 -0
- package/src/migrations/schema-lock.ts +159 -0
- package/src/migrations/schema-plan.ts +94 -0
- package/src/migrations/schema.ts +73 -48
- package/src/migrations/sdk-baseline.ts +35 -0
- package/src/migrations/system-schema.ts +39 -0
- package/src/model-inputs.ts +25 -0
- package/src/openapi/cli.ts +72 -0
- package/src/openapi/generate.ts +166 -0
- package/src/openapi/input-projection.ts +131 -0
- package/src/openapi/public-paths.ts +80 -0
- package/src/openapi/routes.ts +29 -0
- package/src/ops.ts +4 -2
- package/src/organization-name.ts +35 -0
- package/src/organization-permissions.ts +10 -0
- package/src/organizations.ts +72 -3
- package/src/policies.ts +22 -6
- package/src/public-projection.ts +108 -0
- package/src/public-schema.ts +5 -43
- package/src/query/input-schema.ts +89 -0
- package/src/query/limits.ts +1 -1
- package/src/query/schema.ts +11 -89
- package/src/record-action-routes.ts +87 -0
- package/src/record-actions-data.ts +17 -0
- package/src/record-actions.ts +61 -0
- package/src/record-read.ts +20 -0
- package/src/row-access.ts +11 -0
- package/src/row-invitations.ts +29 -0
- package/src/schema/README.md +323 -0
- package/src/schema/declaration.ts +5 -0
- package/src/schema/load.ts +423 -0
- package/src/schema/lock-format.ts +117 -0
- package/src/schema/physical-names.ts +30 -0
- package/src/schema/revision.ts +16 -0
- package/src/schema/source-location.ts +3 -0
- package/src/schema-compatibility.ts +2 -2
- package/src/schema.ts +171 -0
- package/src/types.ts +1 -1
- package/src/user-link-eligibility.ts +36 -0
- package/src/user-links.ts +27 -16
- package/src/worker-access-actions.ts +89 -0
- package/src/worker-access.ts +61 -0
- package/src/workflow-runtime.ts +109 -22
- package/src/bootstrap.ts +0 -23
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@workbasehq/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": "./src/index.ts",
|
|
@@ -24,22 +24,37 @@
|
|
|
24
24
|
"./kernel/schema-check": "./src/kernel/schema-check.ts",
|
|
25
25
|
"./kernel/plugin": "./src/kernel/plugin.ts",
|
|
26
26
|
"./worker-fetch": "./src/worker-fetch.ts",
|
|
27
|
+
"./dev-mailbox": "./src/dev-mailbox.ts",
|
|
27
28
|
"./schema-compatibility": "./src/schema-compatibility.ts",
|
|
28
29
|
"./migrations/versions": "./src/migrations/versions.ts",
|
|
29
30
|
"./config-proposals": "./src/config-proposals.ts",
|
|
30
31
|
"./policies": "./src/policies.ts",
|
|
31
32
|
"./identity-providers": "./src/identity-providers.ts",
|
|
32
33
|
"./console-contract": "./src/console-contract.ts",
|
|
34
|
+
"./console-build": "./src/console-build.ts",
|
|
35
|
+
"./organization-name": "./src/organization-name.ts",
|
|
33
36
|
"./organization-permissions": "./src/organization-permissions.ts",
|
|
34
37
|
"./session-contract": "./src/session-contract.ts",
|
|
35
38
|
"./infra": "./src/infra/index.ts",
|
|
36
39
|
"./infra/provision": "./src/infra/provision.ts",
|
|
37
|
-
"./query/expressions": "./src/query/expressions.ts"
|
|
40
|
+
"./query/expressions": "./src/query/expressions.ts",
|
|
41
|
+
"./schema": "./src/schema.ts",
|
|
42
|
+
"./access/lock": "./src/access-lock.ts",
|
|
43
|
+
"./access/lock/cli": "./src/access-lock/cli.ts",
|
|
44
|
+
"./migrations/schema-plan": "./src/migrations/schema-plan.ts",
|
|
45
|
+
"./openapi/generate": "./src/openapi/generate.ts",
|
|
46
|
+
"./migrations/schema-lock": "./src/migrations/schema-lock.ts",
|
|
47
|
+
"./migrations/schema-cli": "./src/migrations/schema-cli.ts",
|
|
48
|
+
"./schema/load": "./src/schema/load.ts",
|
|
49
|
+
"./schema/physical-names": "./src/schema/physical-names.ts",
|
|
50
|
+
"./openapi/routes": "./src/openapi/routes.ts",
|
|
51
|
+
"./openapi/cli": "./src/openapi/cli.ts"
|
|
38
52
|
},
|
|
39
53
|
"dependencies": {
|
|
40
54
|
"hono": "4.13.13",
|
|
41
55
|
"zod": "4.6.7",
|
|
42
|
-
"@jakub.knejzlik/ts-query": "0.15.0"
|
|
56
|
+
"@jakub.knejzlik/ts-query": "0.15.0",
|
|
57
|
+
"typescript": "^6.0.0"
|
|
43
58
|
},
|
|
44
59
|
"files": [
|
|
45
60
|
"src",
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { EffectiveAccessPolicy, EffectiveEntityPolicy } from './access'
|
|
2
|
+
import type { Operation } from './config'
|
|
3
|
+
import type { Scope } from './types'
|
|
4
|
+
import type { TableFilter } from './kernel/plugin'
|
|
5
|
+
import { actorMembershipRole } from './policies'
|
|
6
|
+
|
|
7
|
+
/** Held-role grants form a union; an explicit `deny` for any held role wins.
|
|
8
|
+
* `none` contributes no grant. Unknown roles fail closed. This union applies
|
|
9
|
+
* only WITHIN one authority layer; credential and issuer layers intersect below.
|
|
10
|
+
*/
|
|
11
|
+
export function effectiveEntityGrants(policy: EffectiveAccessPolicy, roles: string[], entity: string, operation: Operation): EffectiveEntityPolicy[] {
|
|
12
|
+
if (roles.some(role => !policy.roles.includes(role))) return []
|
|
13
|
+
const rules = policy.entities.filter(rule => rule.entity === entity && rule.operation === operation && roles.includes(rule.role))
|
|
14
|
+
return rules.some(rule => rule.decision === 'deny') ? [] : rules.filter(rule => rule.decision === 'allow')
|
|
15
|
+
}
|
|
16
|
+
const systemTargets: Record<string, string> = {
|
|
17
|
+
members: 'memberships', invitations: 'invitations', tokens: 'access_tokens', organizations: 'organizations',
|
|
18
|
+
audit: 'audit_events', workflows: 'workflow_runs',
|
|
19
|
+
}
|
|
20
|
+
export function effectiveSystemGrant(policy: EffectiveAccessPolicy, roles: string[], action: string): boolean {
|
|
21
|
+
if (roles.some(role => !policy.roles.includes(role))) return false
|
|
22
|
+
const rules = policy.system.filter(rule => roles.includes(rule.role) && rule.action === action)
|
|
23
|
+
if (rules.some(rule => rule.decision === 'deny') || !rules.some(rule => rule.decision === 'allow')) return false
|
|
24
|
+
// Recipients consume an issued grant; acceptance does not grant invitation CRUD.
|
|
25
|
+
// The recipient route separately verifies the signed-in account's e-mail.
|
|
26
|
+
if (action === 'invitations.accept') return true
|
|
27
|
+
return rules.some(rule => effectiveEntityGrants(policy, roles, rule.target.entity, rule.target.operation).length > 0)
|
|
28
|
+
}
|
|
29
|
+
export function systemAccessTarget(action: string): { entity: string; operation: Operation } {
|
|
30
|
+
const [resource, verb] = action.split('.')
|
|
31
|
+
const target = systemTargets[resource]
|
|
32
|
+
const operation: Operation = ['create', 'accept'].includes(verb) ? 'create' : ['remove', 'revoke', 'leave'].includes(verb) ? 'delete' : verb === 'read' ? 'read' : 'update'
|
|
33
|
+
return { entity: target, operation }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Build authority once for every compiled-policy consumer. A session has one
|
|
37
|
+
* layer; a credential and its live issuer have independent layers, even when
|
|
38
|
+
* their role names match. A missing issuer contributes an empty, denying layer.
|
|
39
|
+
* Operation-name allowlists remain an additional kernel check.
|
|
40
|
+
*/
|
|
41
|
+
export function effectiveAuthority(policy: EffectiveAccessPolicy, scope: Scope) {
|
|
42
|
+
const principal = actorMembershipRole(scope)
|
|
43
|
+
return effectiveAuthorityLayers(policy, scope.actor.type === 'agent'
|
|
44
|
+
? [[scope.role], principal ? [principal] : []] : [[scope.role]])
|
|
45
|
+
}
|
|
46
|
+
/** Each layer unions its held-role grants (explicit deny wins); every layer must
|
|
47
|
+
* allow. Keep row, field, command and system composition on this same boundary.
|
|
48
|
+
*/
|
|
49
|
+
export function effectiveAuthorityLayers(policy: EffectiveAccessPolicy, layers: string[][]) {
|
|
50
|
+
const grants = (entity: string, operation: Operation) => layers.map(roles => effectiveEntityGrants(policy, roles, entity, operation))
|
|
51
|
+
const entityAllowed = (entity: string, operation: Operation) => layers.length > 0 && grants(entity, operation).every(rules => rules.length > 0)
|
|
52
|
+
const systemAllowed = (action: string) => layers.length > 0 && layers.every(roles => effectiveSystemGrant(policy, roles, action))
|
|
53
|
+
return {
|
|
54
|
+
permits: (grant: { system: string } | { entity: string; operation: Operation }) => 'system' in grant
|
|
55
|
+
? systemAllowed(grant.system) : entityAllowed(grant.entity, grant.operation),
|
|
56
|
+
fields(entity: string): string[] {
|
|
57
|
+
const masks = grants(entity, 'read').map(rules => new Set(rules.flatMap(rule => rule.fields ?? [])))
|
|
58
|
+
return [...(masks[0] ?? [])].filter(field => masks.every(mask => mask.has(field))).sort()
|
|
59
|
+
},
|
|
60
|
+
filter(entity: string, operation: Operation, compile: (rule: EffectiveEntityPolicy) => TableFilter): TableFilter {
|
|
61
|
+
const filters = grants(entity, operation).map(rules => {
|
|
62
|
+
const allowed = rules.map(compile)
|
|
63
|
+
if (allowed.some(filter => filter.kind === 'all')) return { kind: 'all' } as const
|
|
64
|
+
const predicates = allowed.flatMap(filter => filter.kind === 'where' ? [filter.predicate] : [])
|
|
65
|
+
return predicates.length ? { kind: 'where', predicate: { any: predicates } } as const : { kind: 'none' } as const
|
|
66
|
+
})
|
|
67
|
+
if (!filters.length || filters.some(filter => filter.kind === 'none')) return { kind: 'none' }
|
|
68
|
+
const predicates = filters.flatMap(filter => filter.kind === 'where' ? [filter.predicate] : [])
|
|
69
|
+
return predicates.length ? { kind: 'where', predicate: { all: predicates } } : { kind: 'all' }
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { DeclarationError } from './schema/declaration'
|
|
2
|
+
import type { EffectiveAccessPolicy } from './access'
|
|
3
|
+
import type { AtomicOperation } from './execution/types'
|
|
4
|
+
import type { WorkbasePlugin } from './kernel/plugin'
|
|
5
|
+
import { isBuiltinPlugin } from './kernel/builtin-source'
|
|
6
|
+
|
|
7
|
+
/** Resolve code-owned guards once at composition. Audits serialize the same data
|
|
8
|
+
* used by the command port; executable hooks are explicitly opaque, never omitted.
|
|
9
|
+
*/
|
|
10
|
+
export function accessGuards(policy: EffectiveAccessPolicy, names: readonly string[], commands: readonly AtomicOperation<any>[], plugins: readonly WorkbasePlugin[]): EffectiveAccessPolicy {
|
|
11
|
+
const registry = new Map(commands.map(command => [command.name, command]))
|
|
12
|
+
for (const action of policy.actions) {
|
|
13
|
+
const fail = (message: string): never => { throw new DeclarationError([...action.source.split('.'), 'command'], message) }
|
|
14
|
+
if (!names.includes(action.command)) fail(`Action command outside config.commands: ${action.command}`)
|
|
15
|
+
const command = registry.get(action.command)
|
|
16
|
+
if (!command) fail(`Unknown action command: ${action.command}`)
|
|
17
|
+
if ('system' in command!.permission) fail(`System-permission action command: ${action.command}`)
|
|
18
|
+
}
|
|
19
|
+
const canonical = (permission: AtomicOperation['permission']) => 'system' in permission
|
|
20
|
+
? { system: permission.system } : { entity: permission.entity, operation: permission.operation }
|
|
21
|
+
const key = (permission: AtomicOperation['permission']) => JSON.stringify(canonical(permission))
|
|
22
|
+
return { ...policy,
|
|
23
|
+
guards: [...new Set([...names, ...registry.keys()])].sort().map(name => {
|
|
24
|
+
const command = registry.get(name)
|
|
25
|
+
return { name, permission: command ? canonical(command.permission) : null,
|
|
26
|
+
additionalPermissions: (command?.additionalPermissions ?? []).map(canonical).sort((a, b) => key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0),
|
|
27
|
+
// A registered command's prepare/plan can contain further executable checks.
|
|
28
|
+
opaque: true as const,
|
|
29
|
+
}
|
|
30
|
+
}),
|
|
31
|
+
opaqueHooks: plugins.flatMap(plugin => (['tableFilter', 'fieldMask', 'commandGuard'] as const)
|
|
32
|
+
.filter(hook => plugin[hook] && !(isBuiltinPlugin(plugin) && plugin.authorization && plugin.policyInConfig))
|
|
33
|
+
.map(hook => `${plugin.name}.${hook}`)).sort(),
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { KernelRegistry } from './kernel/registry'
|
|
2
|
+
import { isBuiltinPlugin } from './kernel/builtin-source'
|
|
3
|
+
import type { AtomicOperation } from './execution/types'
|
|
4
|
+
import { canonical } from './canonical'
|
|
5
|
+
|
|
6
|
+
export type AccessKernel = Pick<KernelRegistry, 'config' | 'plugins' | 'providers' | 'permissionsActive' | 'authorizationTrust' | 'workflows' | 'workflowRegistrations'>
|
|
7
|
+
/** Snapshot selected declarative inputs from the same composed objects enforcement reads.
|
|
8
|
+
* Curated, not exhaustive: see docs/sdk/access-lock.md § Scope for what is not covered.
|
|
9
|
+
* Account/issuer helpers and opaque plugin ports retain their existing contracts;
|
|
10
|
+
* moving those into the grant compiler would change its execution boundary.
|
|
11
|
+
* No grants or predicates are recompiled here. Executable bodies remain opaque.
|
|
12
|
+
*/
|
|
13
|
+
export function enforcementInputs(kernel: AccessKernel) {
|
|
14
|
+
const { config } = kernel
|
|
15
|
+
const identity = (plugin: KernelRegistry['plugins'][number]) => ({ name: plugin.name, version: plugin.version })
|
|
16
|
+
const permission = (value: AtomicOperation['permission']) => 'system' in value
|
|
17
|
+
? { system: value.system } : { entity: value.entity, operation: value.operation }
|
|
18
|
+
const operation = (value: AtomicOperation<any>) => ({ name: value.name, permission: permission(value.permission),
|
|
19
|
+
additionalPermissions: (value.additionalPermissions ?? []).map(permission).sort((a, b) => {
|
|
20
|
+
const x = JSON.stringify(canonical(a)); const y = JSON.stringify(canonical(b))
|
|
21
|
+
return x < y ? -1 : x > y ? 1 : 0
|
|
22
|
+
}), opaque: true as const })
|
|
23
|
+
return {
|
|
24
|
+
// Occurrences are distinct even when operations share a command name. This
|
|
25
|
+
// projection never registers guards or changes commandGuard lookup semantics.
|
|
26
|
+
workflows: Object.fromEntries([...kernel.workflows].map(([name, workflow]) => {
|
|
27
|
+
const registration = kernel.workflowRegistrations.get(name)!
|
|
28
|
+
return [name, { version: workflow.version,
|
|
29
|
+
registration: { kind: registration.kind, ...(registration.plugin ? { plugin: registration.plugin } : {}) },
|
|
30
|
+
stepOrder: (workflow.steps ?? []).map(step => step.id),
|
|
31
|
+
steps: Object.fromEntries((workflow.steps ?? []).map(step => [step.id, {
|
|
32
|
+
forward: operation(step.operation), compensation: step.compensate ? operation(step.compensate.operation) : null,
|
|
33
|
+
}])),
|
|
34
|
+
}]
|
|
35
|
+
})),
|
|
36
|
+
authorization: { trust: kernel.authorizationTrust, permissionsActive: kernel.permissionsActive,
|
|
37
|
+
providers: Object.fromEntries([...kernel.providers].map(([contract, plugins]) => [contract, plugins.map(identity).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)])) },
|
|
38
|
+
plugins: [...kernel.plugins].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).map(plugin => ({ ...identity(plugin),
|
|
39
|
+
builtin: isBuiltinPlugin(plugin), authorization: !!plugin.authorization, policyInConfig: !!plugin.policyInConfig,
|
|
40
|
+
hooks: (['tableFilter', 'fieldMask', 'commandGuard'] as const).filter(hook => plugin[hook]),
|
|
41
|
+
})),
|
|
42
|
+
account: config.account ?? null, organizationOwnerRole: config.organizationOwnerRole,
|
|
43
|
+
// Compatibility projections are also read by live issuer guards/receipts.
|
|
44
|
+
roles: [...config.roles].sort(), permissions: config.permissions, policies: config.policies, organizationPermissions: config.organizationPermissions,
|
|
45
|
+
// labelPath reads this mapping even though the surrounding UI is presentation.
|
|
46
|
+
ui: { entities: Object.fromEntries(Object.entries(config.ui?.entities ?? {}).flatMap(([name, ui]) =>
|
|
47
|
+
ui.list?.relatedColumns ? [[name, { list: { relatedColumns: ui.list.relatedColumns } }]] : [])) },
|
|
48
|
+
entities: Object.fromEntries(Object.entries(config.entities).map(([name, entity]) => [name, {
|
|
49
|
+
commandsOnly: !!entity.commandsOnly, relations: entity.relations,
|
|
50
|
+
// Keep the same normalized selector and structured wire that the runtime
|
|
51
|
+
// expression/label resolvers consume. Ref targets and computed wires below
|
|
52
|
+
// cover subsequent hops; no second dependency or grant compiler is needed.
|
|
53
|
+
...(entity.displayField ? { displayField: entity.displayField } : {}),
|
|
54
|
+
...(entity.label ? { label: entity.label.serialize() } : {}),
|
|
55
|
+
fields: Object.fromEntries(Object.entries(entity.fields).map(([field, definition]) => [field, {
|
|
56
|
+
type: definition.type, entity: definition.entity, computed: definition.computed,
|
|
57
|
+
readOnly: !!definition.readOnly, sensitive: !!definition.sensitive, userLink: !!definition.userLink,
|
|
58
|
+
values: definition.values ? [...definition.values].sort() : undefined,
|
|
59
|
+
}])),
|
|
60
|
+
}])),
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { resolve } from 'node:path'
|
|
2
|
+
import { pathToFileURL } from 'node:url'
|
|
3
|
+
import { KernelRegistry } from '../kernel/registry'
|
|
4
|
+
import { isSchemaConfig } from '../schema'
|
|
5
|
+
import { configSources } from '../schema/load'
|
|
6
|
+
import { syncAccessLock } from '../access-lock'
|
|
7
|
+
|
|
8
|
+
/** Trusted config modules may register plugins and commands; compose before auditing. */
|
|
9
|
+
export async function runAccessCli(args: readonly string[]): Promise<number> {
|
|
10
|
+
const options = { config: 'config.ts', root: '.', directory: '.', write: false }
|
|
11
|
+
for (let i = 0; i < args.length; i++) {
|
|
12
|
+
const arg = args[i]
|
|
13
|
+
if (arg === '--write') options.write = true
|
|
14
|
+
else if (['--config', '--root', '--directory'].includes(arg) && args[i + 1] && !args[i + 1].startsWith('--')) {
|
|
15
|
+
options[arg.slice(2) as 'config' | 'root' | 'directory'] = args[++i]
|
|
16
|
+
} else throw new Error('Usage: check:access [--config config.ts] [--root .] [--directory .] [--write]')
|
|
17
|
+
}
|
|
18
|
+
const root = resolve(options.root)
|
|
19
|
+
const file = resolve(root, options.config)
|
|
20
|
+
const config = (await import(pathToFileURL(file).href)).default
|
|
21
|
+
if (!config || typeof config !== 'object') throw new Error('Config must default-export an instance configuration')
|
|
22
|
+
// Skip before composing legacy modules: their old runtime behavior stays untouched.
|
|
23
|
+
if (!isSchemaConfig(config)) {
|
|
24
|
+
console.log('check:access: skip legacy defineInstance config (no access lock)')
|
|
25
|
+
return 0
|
|
26
|
+
}
|
|
27
|
+
const result = await syncAccessLock({ ...options, root, kernel: new KernelRegistry(config), sources: configSources(file) })
|
|
28
|
+
console.log(result.message)
|
|
29
|
+
return result.ok ? 0 : 1
|
|
30
|
+
}
|
|
31
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
32
|
+
try { process.exitCode = await runAccessCli(process.argv.slice(2)) }
|
|
33
|
+
catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1 }
|
|
34
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/** Build-time audit only. Records the composed policy plus selected enforcement inputs;
|
|
2
|
+
* not a complete model of authorization (see docs/sdk/access-lock.md § Scope). */
|
|
3
|
+
import { realpathSync } from 'node:fs'
|
|
4
|
+
import { readFile, writeFile } from 'node:fs/promises'
|
|
5
|
+
import { isAbsolute, relative, resolve, sep } from 'node:path'
|
|
6
|
+
import { enforcementInputs, type AccessKernel } from './access-inputs'
|
|
7
|
+
import type { SourceMap } from './schema/source-location'
|
|
8
|
+
|
|
9
|
+
export interface AccessLockOptions {
|
|
10
|
+
root: string
|
|
11
|
+
sources: SourceMap
|
|
12
|
+
}
|
|
13
|
+
export interface AccessLockFiles { json: string; md: string }
|
|
14
|
+
import { canonical } from './canonical'
|
|
15
|
+
export { canonical } from './canonical'
|
|
16
|
+
const json = (value: unknown) => JSON.stringify(canonical(value))
|
|
17
|
+
const cell = (value: string) => value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('|', '|').replaceAll('`', '`').replaceAll('\n', '<br>')
|
|
18
|
+
|
|
19
|
+
export function serializeAccessLock(kernel: AccessKernel, options: AccessLockOptions): AccessLockFiles {
|
|
20
|
+
const policy = kernel.config.effectiveAccess
|
|
21
|
+
if (!policy) throw new Error('Access lock requires a composed effectiveAccess policy')
|
|
22
|
+
const inputs = enforcementInputs(kernel)
|
|
23
|
+
const root = realpathSync(resolve(options.root))
|
|
24
|
+
const locations: Record<string, { file: string; line: number }> = {}
|
|
25
|
+
const locate = (key: string, fallback = key) => {
|
|
26
|
+
let path = options.sources[key] ? key : fallback
|
|
27
|
+
while (!options.sources[path] && path) path = path.split('.').slice(0, -1).join('.')
|
|
28
|
+
const source = options.sources[path]
|
|
29
|
+
if (!source) throw new Error(`Missing source location for ${key}; provide the config source map`)
|
|
30
|
+
const file = relative(root, resolve(root, source.file)).split(sep).join('/')
|
|
31
|
+
if (isAbsolute(file) || file === '..' || file.startsWith('../')) throw new Error(`Source for ${key} is outside the repository root`)
|
|
32
|
+
locations[key] = { file, line: source.line }
|
|
33
|
+
return `${file}:${source.line}`
|
|
34
|
+
}
|
|
35
|
+
const lines = ['# Access lock', '', 'Generated from kernel.config.effectiveAccess. Regenerate with `bun run access:lock`.', '',
|
|
36
|
+
'Held-role grants form a union; explicit deny wins and none supplies no grant. Independent authority layers combine by intersection.', '',
|
|
37
|
+
'Source locations identify the rule or its enclosing registration declaration. Executable code remains opaque.', '',
|
|
38
|
+
'## Entity operations', '', '| Role | Entity | Read | Create | Update | Delete |', '| --- | --- | --- | --- | --- | --- |']
|
|
39
|
+
const groups = new Map<string, Map<string, string>>()
|
|
40
|
+
for (const rule of policy.entities) {
|
|
41
|
+
const key = json([rule.role, rule.entity])
|
|
42
|
+
const group = groups.get(key) ?? new Map<string, string>(); groups.set(key, group)
|
|
43
|
+
const details = [rule.decision, `where=${json(rule.where)}`, `fields=${json(rule.fields)}`,
|
|
44
|
+
`predicates=${json(rule.predicates)}`, `dependencies=${json(rule.dependencies)}`, locate(rule.source)]
|
|
45
|
+
group.set(rule.operation, cell(details.join('; ')))
|
|
46
|
+
for (const name of rule.predicates) locate(`access.predicates.${name}`)
|
|
47
|
+
}
|
|
48
|
+
for (const [key, operations] of [...groups].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
|
|
49
|
+
const [role, entity] = JSON.parse(key)
|
|
50
|
+
lines.push(`| ${cell(role)} | ${cell(entity)} | ${['read', 'create', 'update', 'delete'].map(op => operations.get(op) ?? 'missing').join(' | ')} |`)
|
|
51
|
+
}
|
|
52
|
+
lines.push('', '## System and account privileges', '', '| Role | Action | Decision | Target | Source |', '| --- | --- | --- | --- | --- |')
|
|
53
|
+
for (const rule of policy.system) lines.push(`| ${cell(rule.role)} | ${cell(rule.action)} | ${rule.decision} | ${cell(json(rule.target))} | ${cell(locate(rule.source))} |`)
|
|
54
|
+
if (policy.accountLinks) {
|
|
55
|
+
lines.push('', '## Account link invitation roles', '')
|
|
56
|
+
for (const [entity, mapping] of Object.entries(policy.accountLinks)) lines.push(`- ${cell(entity)}: ${cell(mapping.invitationRole)} (${cell(locate(`access.accountLinks.${entity}.invitationRole`))})`)
|
|
57
|
+
}
|
|
58
|
+
lines.push('', '## Record actions', '', '| Entity | Action | Command | Conditions | Dependencies | Source |', '| --- | --- | --- | --- | --- | --- |')
|
|
59
|
+
for (const action of policy.actions) lines.push(`| ${cell(action.entity)} | ${cell(action.name)} | ${cell(action.command)} | ${cell(json(action.conditions))} | ${cell(json(action.dependencies))} | ${cell(locate(action.source))} |`)
|
|
60
|
+
lines.push('', '## Registered command guards', '', '| Command | Permission | Additional permissions | Executable checks | Registration source |', '| --- | --- | --- | --- | --- |')
|
|
61
|
+
for (const guard of policy.guards) lines.push(`| ${cell(guard.name)} | ${cell(json(guard.permission))} | ${cell(json(guard.additionalPermissions))} | opaque | ${cell(locate(`guards.${guard.name}`, 'commands'))} |`)
|
|
62
|
+
lines.push('', '## Workflow operation occurrences', '', '| Workflow | Step (in execution order) | Role | Operation | Permission | Additional permissions | Executable checks | Registration source |', '| --- | --- | --- | --- | --- | --- | --- | --- |')
|
|
63
|
+
for (const [name, workflow] of Object.entries(canonical(inputs.workflows) as typeof inputs.workflows)) {
|
|
64
|
+
const registration = kernel.workflowRegistrations.get(name)!
|
|
65
|
+
const source = (key: string, fallback: string) => {
|
|
66
|
+
// Explicit occurrence/workflow mappings override enclosing registrations.
|
|
67
|
+
let mapped = key
|
|
68
|
+
while (mapped.startsWith('workflows.') && !options.sources[mapped]) mapped = mapped.split('.').slice(0, -1).join('.')
|
|
69
|
+
return locate(key, options.sources[mapped] ? mapped : fallback)
|
|
70
|
+
}
|
|
71
|
+
const registrationLocation = source(`workflows.${name}`, registration.source)
|
|
72
|
+
lines.push(`| ${cell(name)} (v${cell(workflow.version)}; ${cell(json(workflow.registration))}) | | | | | | | ${cell(registrationLocation)} |`)
|
|
73
|
+
workflow.stepOrder.forEach((id, index) => {
|
|
74
|
+
for (const role of ['forward', 'compensation'] as const) {
|
|
75
|
+
const operation = workflow.steps[id][role]
|
|
76
|
+
if (!operation) continue
|
|
77
|
+
const location = source(`workflows.${name}.steps.${id}.${role}`,
|
|
78
|
+
`${registration.source}.steps.${index}.${role === 'forward' ? 'operation' : 'compensate.operation'}`)
|
|
79
|
+
lines.push(`| ${cell(name)} | ${index + 1}. ${cell(id)} | ${role} | ${cell(operation.name)} | ${cell(json(operation.permission))} | ${cell(json(operation.additionalPermissions))} | opaque | ${cell(location)} |`)
|
|
80
|
+
}
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
if (!Object.keys(inputs.workflows).length) lines.push('None registered.')
|
|
84
|
+
lines.push('', '## Opaque executable hooks', '')
|
|
85
|
+
for (const hook of policy.opaqueHooks) lines.push(`- ${cell(hook)}: opaque (${cell(locate(`hooks.${hook}`, 'plugins'))})`)
|
|
86
|
+
if (!policy.opaqueHooks.length) lines.push('None registered.')
|
|
87
|
+
lines.push('', '## Named predicate sources', '')
|
|
88
|
+
const predicates = [...new Set(policy.entities.flatMap(rule => rule.predicates))].sort()
|
|
89
|
+
for (const name of predicates) lines.push(`- ${cell(name)}: ${cell(locate(`access.predicates.${name}`))}`)
|
|
90
|
+
if (!predicates.length) lines.push('None used.')
|
|
91
|
+
lines.push('', '## Enforcement inputs', '', 'Selected resolved kernel/config inputs used alongside the compiled grants (curated, not exhaustive; see docs/sdk/access-lock.md § Scope). Executable bodies remain opaque.', '', '| Input | Resolved value |', '| --- | --- |')
|
|
92
|
+
for (const [key, value] of Object.entries(canonical(inputs) as Record<string, unknown>)) {
|
|
93
|
+
if (key === 'entities') for (const [entity, definition] of Object.entries(value as Record<string, Record<string, unknown>>)) {
|
|
94
|
+
for (const [part, data] of Object.entries(definition)) {
|
|
95
|
+
const source = part === 'displayField' || part === 'label' ? ` (${cell(locate(`entities.${entity}.${part}`))})` : ''
|
|
96
|
+
lines.push(`| ${cell(`${entity} / ${part}`)} | ${cell(json(data))}${source} |`)
|
|
97
|
+
}
|
|
98
|
+
} else if (key === 'ui') {
|
|
99
|
+
for (const [entity, ui] of Object.entries(canonical(inputs.ui.entities) as typeof inputs.ui.entities)) {
|
|
100
|
+
for (const [column, binding] of Object.entries(canonical(ui.list.relatedColumns) as typeof ui.list.relatedColumns)) {
|
|
101
|
+
const path = `ui.entities.${entity}.list.relatedColumns.${column}`
|
|
102
|
+
lines.push(`| ${cell(path)} | ${cell(json(binding))} (${cell(locate(path))}) |`)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
} else if (key !== 'workflows') lines.push(`| ${cell(key)} | ${cell(json(value))} |`)
|
|
106
|
+
}
|
|
107
|
+
// Compact JSON keeps the full normalized representation together; no derived grants.
|
|
108
|
+
return { json: json({ effectiveAccess: policy, enforcementInputs: inputs, sources: locations }) + '\n', md: lines.join('\n') + '\n' }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function diff(previous: string, current: string): string[] {
|
|
112
|
+
try {
|
|
113
|
+
const before = JSON.parse(previous); const after = JSON.parse(current)
|
|
114
|
+
const changes: string[] = []
|
|
115
|
+
const inputSource = (path: string) => {
|
|
116
|
+
let key = path.replace(/^enforcement inputs \/ /, '').split(' / ').join('.')
|
|
117
|
+
while (!after.sources[key] && !before.sources[key] && key) key = key.split('.').slice(0, -1).join('.')
|
|
118
|
+
const source = after.sources[key] ?? before.sources[key]
|
|
119
|
+
return source ? ` (${source.file}:${source.line})` : ''
|
|
120
|
+
}
|
|
121
|
+
function inputs(old: any, next: any, path: string) {
|
|
122
|
+
if (json(old) === json(next)) return
|
|
123
|
+
if (path === 'enforcement inputs / workflows') {
|
|
124
|
+
for (const name of [...new Set([...Object.keys(old ?? {}), ...Object.keys(next ?? {})])].sort()) {
|
|
125
|
+
const child = `${path} / ${name}`
|
|
126
|
+
if (!old?.[name] || !next?.[name]) changes.push(`${next?.[name] ? '+' : '-'} workflow ${name}${inputSource(child)}`)
|
|
127
|
+
else inputs(old[name], next[name], child)
|
|
128
|
+
}
|
|
129
|
+
return
|
|
130
|
+
}
|
|
131
|
+
if (old && next && typeof old === 'object' && typeof next === 'object' && !Array.isArray(old) && !Array.isArray(next)) {
|
|
132
|
+
for (const key of [...new Set([...Object.keys(old), ...Object.keys(next)])].sort()) inputs(old[key], next[key], `${path} / ${key}`)
|
|
133
|
+
} else changes.push(`~ ${path}: ${json(old) ?? 'missing'} -> ${json(next) ?? 'missing'}${inputSource(path)}`)
|
|
134
|
+
}
|
|
135
|
+
for (const [section, key] of [
|
|
136
|
+
['entities', (r: any) => `${r.role} / ${r.entity} / ${r.operation}`],
|
|
137
|
+
['system', (r: any) => `${r.role} / ${r.target.entity} / ${r.target.operation} (${r.action})`],
|
|
138
|
+
['actions', (r: any) => `action ${r.entity} / ${r.name}`],
|
|
139
|
+
['guards', (r: any) => `command ${r.name}`],
|
|
140
|
+
] as const) {
|
|
141
|
+
const old = new Map<string, unknown>((before.effectiveAccess[section] ?? []).map((r: any) => [key(r), r]))
|
|
142
|
+
const next = new Map<string, unknown>((after.effectiveAccess[section] ?? []).map((r: any) => [key(r), r]))
|
|
143
|
+
for (const id of [...new Set([...old.keys(), ...next.keys()])].sort()) {
|
|
144
|
+
if (json(old.get(id)) !== json(next.get(id))) changes.push(`${old.has(id) ? next.has(id) ? '~' : '-' : '+'} ${id}`)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (json(before.effectiveAccess.opaqueHooks) !== json(after.effectiveAccess.opaqueHooks)) changes.push('~ opaque executable hooks')
|
|
148
|
+
if (json(before.effectiveAccess.roles) !== json(after.effectiveAccess.roles)) changes.push('~ configured roles')
|
|
149
|
+
inputs(before.effectiveAccess.accountLinks, after.effectiveAccess.accountLinks, 'account link invitation roles')
|
|
150
|
+
inputs(before.enforcementInputs, after.enforcementInputs, 'enforcement inputs')
|
|
151
|
+
if (json(before.sources) !== json(after.sources)) changes.push('~ source locations')
|
|
152
|
+
return changes.slice(0, 12).concat(changes.length > 12 ? [`… ${changes.length - 12} more changes`] : [])
|
|
153
|
+
} catch { return ['Invalid access.lock.json; regenerate it'] }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Checks never create directories or touch either lock, including missing/invalid locks. */
|
|
157
|
+
export async function syncAccessLock(options: AccessLockOptions & {
|
|
158
|
+
kernel: AccessKernel
|
|
159
|
+
directory?: string
|
|
160
|
+
write?: boolean
|
|
161
|
+
}): Promise<{ ok: boolean; message: string }> {
|
|
162
|
+
if (!options.kernel.config.effectiveAccess) {
|
|
163
|
+
if (options.kernel.config.baseline === 'workbase-sdk') throw new Error('Schema config is missing compiled effectiveAccess')
|
|
164
|
+
return { ok: true, message: 'check:access: skip legacy defineInstance config (no access lock)' }
|
|
165
|
+
}
|
|
166
|
+
const files = serializeAccessLock(options.kernel, options)
|
|
167
|
+
const directory = resolve(options.root, options.directory ?? '.')
|
|
168
|
+
const names = ['access.lock.json', 'access.lock.md'] as const
|
|
169
|
+
if (options.write) {
|
|
170
|
+
for (const [i, content] of [files.json, files.md].entries()) await writeFile(resolve(directory, names[i]), content)
|
|
171
|
+
return { ok: true, message: 'access:lock: regenerated access.lock.json and access.lock.md' }
|
|
172
|
+
}
|
|
173
|
+
const previous = await Promise.all(names.map(async name => {
|
|
174
|
+
try { return await readFile(resolve(directory, name), 'utf8') }
|
|
175
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; throw error }
|
|
176
|
+
}))
|
|
177
|
+
const missing = names.filter((_, i) => previous[i] === undefined)
|
|
178
|
+
if (missing.length) return { ok: false, message: `check:access: missing ${missing.join(', ')}; run bun run access:lock` }
|
|
179
|
+
const stale = names.filter((_, i) => previous[i] !== [files.json, files.md][i])
|
|
180
|
+
if (!stale.length) return { ok: true, message: 'check:access: lock files match the compiled policy and listed inputs' }
|
|
181
|
+
return { ok: false, message: [`check:access: stale ${stale.join(', ')}; run bun run access:lock`,
|
|
182
|
+
...(previous[0] !== files.json ? diff(previous[0]!, files.json) : [])].join('\n') }
|
|
183
|
+
}
|