@workbasehq/core 0.2.8 → 0.2.9

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workbasehq/core",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts",
package/src/app.ts CHANGED
@@ -75,7 +75,7 @@ function buildApp(input: InstanceInput, env: RuntimeEnv, options: RuntimeOptions
75
75
  bindings: [ulid(), error.code, status, c.get('correlationId'), new Date().toISOString()], expectRows: 1,
76
76
  }])
77
77
  } else if (status === 403 || status === 409) {
78
- if (c.req.path.startsWith('/auth/')) await identityWrite(env, config, 'security_denied', [{
78
+ if (c.req.path.startsWith('/auth/') && c.req.path !== '/auth/register') await identityWrite(env, config, 'security_denied', [{
79
79
  sql: 'INSERT INTO security_log (id,operation,status,correlation_id,occurred_at) VALUES (?,?,?,?,?)',
80
80
  bindings: [ulid(), `${c.req.method} ${routePath(c, -1)}`, status, c.get('correlationId'), new Date().toISOString()], expectRows: 1,
81
81
  }])
package/src/config.ts CHANGED
@@ -18,7 +18,7 @@ export { Q, Cond }
18
18
  /** SQLite date formatting with column operands; values use the library wire encoding. */
19
19
  export const Fn = { ...LibraryFn, strftime: (format: string, date: string) => Q.expr(`FN(${JSON.stringify(['STRFTIME', Q.value(format).serialize(), Q.expr(date).serialize()])})`) }
20
20
 
21
- export const CORE_VERSION = '0.2.8'
21
+ export const CORE_VERSION = '0.2.9'
22
22
  const navigationIconSchema = z.enum(['LayoutDashboard', 'Users', 'MapPin', 'Coins', 'Wallet', 'ArrowLeftRight', 'Settings', 'Building2', 'Activity', 'Workflow', 'Database', 'Folder'])
23
23
  const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
24
24
  export const serializedExpressionSchema = z.union([z.string().min(1).max(32000), z.record(z.string(), z.unknown()).transform(value => JSON.stringify(value))])
@@ -137,18 +137,27 @@ export function defineInstance(input: Omit<ShorthandInput, 'roles' | 'entities'
137
137
  for (const plugin of resolved.plugins) {
138
138
  if (plugin.configure) contribution = { ...contribution, ...plugin.configure(plugin.configSchema?.parse(pluginConfig[plugin.name])) }
139
139
  }
140
- const config = schema.parse(expand({ ...model, ...input, entities: input.entities ?? model.entities ?? {}, permissions: input.permissions ?? model.permissions ?? {}, ...contribution, roles: contribution.roles ?? input.roles ?? [],
140
+ const expanded = expand({ ...model, ...input, entities: input.entities ?? model.entities ?? {}, permissions: input.permissions ?? model.permissions ?? {}, ...contribution, roles: contribution.roles ?? input.roles ?? [],
141
141
  organizationPermissions: { ...model.organizationPermissions, ...contribution.organizationPermissions, ...input.organizationPermissions },
142
142
  ...(input.pluginConfig || Object.keys(pluginConfig).length ? { pluginConfig } : {}),
143
- }))
143
+ })
144
+ // Append built-ins after shorthand expansion: wildcards/default tables keep their
145
+ // existing entries byte-for-byte. Newly materialized roles receive no grants.
146
+ const authoredRoles = expanded.roles
147
+ const roles = [...authoredRoles]
148
+ for (const role of [expanded.organizationOwnerRole ?? 'owner', 'member']) if (!roles.includes(role)) roles.push(role)
149
+ const config = schema.parse({ ...expanded, roles })
144
150
  for (const name of Object.keys(config.pluginConfig ?? {})) {
145
151
  if (!config.plugins?.some(plugin => plugin.name === name)) throw new Error(`Unknown plugin config: ${name}`)
146
152
  }
147
153
  // Custom roles have no default grants. Preserve sparse explicit/model tables;
148
154
  // implicit tables retain their existing empty entries for custom roles.
149
155
  const defaultRoles = input.organizationPermissions === undefined && model.organizationPermissions === undefined
150
- ? config.roles : config.roles.filter(role => Object.hasOwn(defaultOrganizationPermissions, role))
151
- config.organizationPermissions = { ...Object.fromEntries(defaultRoles.map(role => [role, [...(defaultOrganizationPermissions[role] ?? [])]])), ...config.organizationPermissions }
156
+ ? authoredRoles.filter(role => role !== 'member') : authoredRoles.filter(role => Object.hasOwn(defaultOrganizationPermissions, role))
157
+ // Only absent entries receive legacy defaults; a persisted [] stays empty on reload.
158
+ config.organizationPermissions = { ...Object.fromEntries(defaultRoles.filter(role => !Object.hasOwn(config.organizationPermissions, role))
159
+ .map(role => [role, [...(defaultOrganizationPermissions[role] ?? [])]])), ...config.organizationPermissions }
160
+ if (!authoredRoles.includes(config.organizationOwnerRole) && !Object.hasOwn(config.organizationPermissions, config.organizationOwnerRole)) config.organizationPermissions[config.organizationOwnerRole] = []
152
161
  if (config.organizationOwnerRole !== 'owner' && !config.roles.includes(config.organizationOwnerRole)) throw new Error('Unknown organization owner role')
153
162
  for (const [name, entity] of Object.entries(config.entities)) {
154
163
  if ((reserved.has(name) && !(name === 'users' && config.account?.entity === name)) || name === 'atomic_assert' || name.startsWith('sqlite_') || name.startsWith('d1_')) throw new Error(`Reserved entity: ${name}`)
@@ -3,7 +3,7 @@ import type { InstanceConfig } from '../config'
3
3
  import type { Scope } from '../identity'
4
4
  import type { AtomicOperation } from './types'
5
5
 
6
- export { isOrganizationAdministrator, organizationRoleRank, organizationPermission } from '../organization-permissions'
6
+ export { isOrganizationAdministrator, canGrantRole, organizationPermission } from '../organization-permissions'
7
7
  export function atomicPermission(config: InstanceConfig, scope: Scope, operation: AtomicOperation, input?: unknown) {
8
8
  kernelFor(config).atomicPermission(scope, operation, input)
9
9
  }
@@ -76,7 +76,7 @@ export const initialSchema = (config: InstanceConfig) => configuredSystemSchema(
76
76
  /** Fresh schemas support configured application roles and the explicit users/account extension.
77
77
  * Existing installations keep their append-only migration chain. */
78
78
  function configuredSystemSchema(config: InstanceConfig) {
79
- let sql = systemSchema.replaceAll("'owner','dispatcher','viewer'", [...new Set(['owner', 'dispatcher', 'viewer', ...config.roles])].map(literal).join(','))
79
+ let sql = systemSchema.replace(/ CHECK ?\(role IN \('owner','dispatcher','viewer'\)\)/g, '')
80
80
  if (config.account?.entity === 'users') {
81
81
  const domain = createEntity('users', config.entities.users)
82
82
  .replace('id TEXT PRIMARY KEY,', "id TEXT PRIMARY KEY, email TEXT UNIQUE, password_hash TEXT NOT NULL DEFAULT '', salt TEXT NOT NULL DEFAULT '',")
@@ -3,11 +3,36 @@ import type { Scope } from './types'
3
3
  import { ApiError } from './errors'
4
4
 
5
5
  export const isOrganizationAdministrator = (config: InstanceConfig, role: string) => role === 'owner' || role === config.organizationOwnerRole
6
- /** Preserve the existing role ranks, with the configured owner above ordinary roles. */
7
- export const organizationRoleRank = (config: InstanceConfig, role: string) => isOrganizationAdministrator(config, role) ? 2 : role === 'dispatcher' ? 1 : 0
6
+ /** Shared by resource authorization, live token projection and role granting. */
7
+ export function roleNamePrivileges(role: string): ReadonlySet<string> {
8
+ return new Set(role === 'owner' ? ['audit.read', 'workflows.resume', 'workflows.cancel'] : [])
9
+ }
10
+ /** Role-level authority; row policies, field masks and credential restrictions
11
+ * are enforced separately. Prefixes keep entity and system grants disjoint.
12
+ */
13
+ export function effectiveRolePrivileges(config: InstanceConfig, role: string): ReadonlySet<string> {
14
+ if (!config.roles.includes(role)) return new Set()
15
+ const privileges = new Set([
16
+ ...roleNamePrivileges(role), ...(config.organizationPermissions[role] ?? []),
17
+ // These resource operations are available to every configured membership role.
18
+ 'members.read', 'invitations.read', 'organizations.create', 'members.leave', 'invitations.accept', 'workflows.read',
19
+ ].map(action => `system:${action}`))
20
+ for (const [entity, operations] of Object.entries(config.permissions[role] ?? {})) {
21
+ for (const operation of operations) privileges.add(`entity:${entity}:${operation}`)
22
+ }
23
+ return privileges
24
+ }
25
+ /** A grant may contain only effective privileges held by the issuer.
26
+ * Policies and field masks remain independently enforced at execution time. Unknown
27
+ * roles never authorize a grant, including an otherwise empty target role.
28
+ */
29
+ export function canGrantRole(config: InstanceConfig, actorRole: string, targetRole: string): boolean {
30
+ if (!config.roles.includes(actorRole) || !config.roles.includes(targetRole)) return false
31
+ const issuer = effectiveRolePrivileges(config, actorRole)
32
+ return [...effectiveRolePrivileges(config, targetRole)].every(privilege => issuer.has(privilege))
33
+ }
8
34
  export function organizationPermission(config: InstanceConfig, scope: Scope, action: OrganizationAction) {
9
35
  if (scope.actor.type !== 'user') throw new ApiError(403, 'user_required')
10
36
  if ((action === 'members.read' || action === 'invitations.read') && config.roles.includes(scope.role)) return
11
37
  if (!Object.hasOwn(config.organizationPermissions, scope.role) || !config.organizationPermissions[scope.role].includes(action)) throw new ApiError(403, 'permission_denied')
12
- if (action !== 'members.read' && !action.startsWith('invitations.') && !isOrganizationAdministrator(config, scope.role)) throw new ApiError(403, 'owner_required')
13
38
  }
@@ -1,12 +1,11 @@
1
1
  import type { InstanceConfig, OrganizationAction } from './config'
2
- import { isOrganizationAdministrator, organizationRoleRank } from './execution/permissions'
2
+ import { canGrantRole } from './execution/permissions'
3
3
  import type { Scope } from './identity'
4
4
  import type { AtomicRule, SqlStatement } from './execution/types'
5
5
 
6
- export function issuerGuard(config: InstanceConfig, scope: Scope, action: OrganizationAction, grantRole?: string) {
7
- const roles = Object.entries(config.organizationPermissions).filter(([, grants]) => grants.includes(action)).map(([role]) => role)
8
- .filter(role => action.startsWith('invitations.') || isOrganizationAdministrator(config, role))
9
- .filter(role => grantRole === undefined || organizationRoleRank(config, role) >= organizationRoleRank(config, grantRole))
6
+ export function issuerGuard(config: InstanceConfig, scope: Scope, action: OrganizationAction | undefined, grantRole?: string) {
7
+ const roles = config.roles.filter(role => action === undefined || config.organizationPermissions[role]?.includes(action))
8
+ .filter(role => grantRole === undefined || canGrantRole(config, role, grantRole))
10
9
  return { sql: `EXISTS (SELECT 1 FROM memberships issuer WHERE issuer.organization_id=? AND issuer.user_id=? AND issuer.role IN (${roles.map(() => '?').join(',') || 'NULL'}))`, values: [scope.organizationId, scope.actor.id, ...roles] }
11
10
  }
12
11
  /** Each gate raises an SQL assertion before any later membership, email or audit write. */
@@ -14,7 +13,7 @@ export function organizationRule(name: string, ...statements: SqlStatement[]): A
14
13
  return { name, statements: statements.map(statement => ({ ...statement, expectRows: 1 })) }
15
14
  }
16
15
  export function memberMutationRule(config: InstanceConfig, scope: Scope, userId: string, role: string | null, remove: boolean, leave: boolean): AtomicRule {
17
- const guard = leave ? { sql: '1', values: [] } : issuerGuard(config, scope, remove ? 'members.remove' : 'members.update')
16
+ const guard = leave ? { sql: '1', values: [] } : issuerGuard(config, scope, remove ? 'members.remove' : 'members.update', remove ? undefined : role!)
18
17
  const predicate = `organization_id=? AND user_id=? AND (role<>? OR ?=? OR (SELECT count(*) FROM memberships owners WHERE owners.organization_id=? AND owners.role=?)>1) AND ${guard.sql}`
19
18
  const values = [scope.organizationId, userId, config.organizationOwnerRole, role, config.organizationOwnerRole, scope.organizationId, config.organizationOwnerRole, ...guard.values]
20
19
  return { name: 'last_owner', statements: [{
@@ -1,5 +1,5 @@
1
1
  import { authorizeOperation } from './authorization'
2
- import { isOrganizationAdministrator } from './execution/permissions'
2
+ import { organizationPermission } from './execution/permissions'
3
3
  import { ApiError } from './errors'
4
4
  import { z } from 'zod'
5
5
  import { coreExecutionContext } from './execution/context'
@@ -33,7 +33,8 @@ export function membershipExecutor(config: InstanceConfig, env: RuntimeEnv) {
33
33
  const context = coreExecutionContext(config, scope, new D1AtomicStore(env.DB, { env, config }), new D1AtomicReader(env.DB))
34
34
  const operation = defineAtomicOperation({ name, permission: { system }, input: z.strictObject({}), plan: () => plan })
35
35
  if (['members.update', 'organizations.create', 'invitations.accept'].includes(system)) {
36
- if (context.scope.actor.type !== 'user' || (system === 'members.update' && !isOrganizationAdministrator(config, context.scope.role))) throw new ApiError(403, 'field_forbidden')
36
+ if (context.scope.actor.type !== 'user') throw new ApiError(403, 'field_forbidden')
37
+ if (system === 'members.update') organizationPermission(config, context.scope, system)
37
38
  const capability = Object.freeze({ operation, mode: system === 'members.update' ? 'update' as const : 'create' as const })
38
39
  memberCapabilities.add(capability)
39
40
  memberSlots.set(context, capability)
package/src/policies.ts CHANGED
@@ -5,6 +5,7 @@ import { fieldsFor, fieldType, filterSchema, type Filter } from './query/schema'
5
5
  import type { Predicate, PredicateOperators, TableFilter } from './kernel/plugin'
6
6
  import type { Scope } from './types'
7
7
  import { ApiError } from './errors'
8
+ import { roleNamePrivileges } from './organization-permissions'
8
9
  import { quote } from './migrations/schema'
9
10
  import { kernelFor } from './kernel/registry'
10
11
 
@@ -149,7 +150,7 @@ export function rbacRoles(scope: Scope): string[] {
149
150
  }
150
151
  /** System audit access requires an owner credential and a live owner issuer. */
151
152
  export function hasOwnerRole(scope: Scope): boolean {
152
- return (scope.actor.type !== 'agent' || projections.has(scope)) && rbacRoles(scope).every(role => role === 'owner')
153
+ return (scope.actor.type !== 'agent' || projections.has(scope)) && rbacRoles(scope).every(role => roleNamePrivileges(role).has('audit.read'))
153
154
  }
154
155
  export function policyFilter(config: InstanceConfig, entity: string, scope: Scope): TableFilter {
155
156
  const filters = rbacRoles(scope).map(role => rolePolicyFilter(config, entity, scope, role))