@workbasehq/core 0.2.13 → 0.2.15
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/audit.ts +3 -2
- package/src/config.ts +1 -1
- package/src/console-contract.ts +1 -0
- package/src/console-model.ts +6 -0
- package/src/console-presentation.ts +1 -1
- package/src/infra/README.md +9 -0
- package/src/infra/provision-plan.ts +4 -1
- package/src/infra/provision.ts +1 -0
- package/src/ops.ts +1 -1
- package/src/organization-permissions.ts +3 -1
- package/src/organization-rules.ts +7 -0
- package/src/policies.ts +1 -0
- package/src/query/compiler.ts +13 -0
- package/src/query/schema.ts +13 -3
- package/src/types.ts +1 -1
- package/src/user-link-fields.ts +7 -0
- package/src/user-links.ts +17 -9
package/package.json
CHANGED
package/src/audit.ts
CHANGED
|
@@ -26,8 +26,9 @@ export async function auditActorLabels(db: D1Database, organizationId: string, e
|
|
|
26
26
|
? { ...event, actor: { ...event.actor, label: labels.get(event.actor.id) ?? event.actor.id } } : event)
|
|
27
27
|
}
|
|
28
28
|
export function requireInternal(env: RuntimeEnv, token: string | undefined) {
|
|
29
|
-
|
|
30
|
-
if (!
|
|
29
|
+
const configured = env.OPS_TOKEN ?? env.INTERNAL_TOKEN
|
|
30
|
+
if (!configured) throw new ApiError(503, 'internal_token_not_configured')
|
|
31
|
+
if (!token || !equalHash(configured, token)) throw new ApiError(403, 'internal_token_required')
|
|
31
32
|
}
|
|
32
33
|
export async function outboxStats(db: D1Database, now = Date.now()) {
|
|
33
34
|
const row = await db.prepare('SELECT count(*) AS backlog,min(created_at) AS oldest FROM audit_outbox WHERE delivered_at IS NULL').first<{ backlog: number; oldest: string | null }>()
|
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.
|
|
21
|
+
export const CORE_VERSION = '0.2.15'
|
|
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))])
|
package/src/console-contract.ts
CHANGED
|
@@ -127,6 +127,7 @@ export interface ConsoleModelRelation {
|
|
|
127
127
|
through?: { entity: string; field: string; createCommand: string; deleteCommand: string }
|
|
128
128
|
}
|
|
129
129
|
export interface ConsoleModelEntity extends Omit<ConsoleEntityDisplay, 'fields'> {
|
|
130
|
+
rowInvitations?: boolean
|
|
130
131
|
fields: Record<string, ConsoleModelField>
|
|
131
132
|
columns: string[]
|
|
132
133
|
listColumns?: string[]
|
package/src/console-model.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { canGrantRole, organizationPermission } from './organization-permissions'
|
|
1
2
|
import { z } from 'zod'
|
|
2
3
|
import { bodyValidator } from './config'
|
|
3
4
|
import { capabilities } from './capabilities'
|
|
@@ -35,10 +36,15 @@ export function consoleModel(kernel: KernelRegistry, scope: Scope): ConsoleModel
|
|
|
35
36
|
if (Array.isArray(schema.required)) schema.required = schema.required.filter(field => Object.hasOwn(schema.properties as object, field))
|
|
36
37
|
return consoleInputSchema(schema, node => authority.schema(node) && literalGrants.get(node) !== false)
|
|
37
38
|
}
|
|
39
|
+
let rowInvitations = false
|
|
40
|
+
if (kernel.providers.has('members') && authority.read(name, 'id') && Object.values(entity.fields).some(field => field.userLink)) {
|
|
41
|
+
try { kernel.permission(scope, name, 'create'); kernel.resourcePermission(scope, 'invitations.create'); organizationPermission(config, scope, 'invitations.create'); rowInvitations = canGrantRole(config, scope.role, 'member') } catch {}
|
|
42
|
+
}
|
|
38
43
|
const display = authority.canRead(name) && config.ui?.entities[name] ? presentation.display(name, config.ui.entities[name]) : undefined
|
|
39
44
|
const displayField = entity.displayField && authority.read(name, entity.displayField) ? entity.displayField : undefined
|
|
40
45
|
return [name, {
|
|
41
46
|
...display,
|
|
47
|
+
...(rowInvitations ? { rowInvitations: true } : {}),
|
|
42
48
|
fields: Object.fromEntries(fieldsFor(config, name).filter(field => authority.read(name, field)).map(field => {
|
|
43
49
|
const definition = entity.fields[field]
|
|
44
50
|
const type = fieldType(config, name, field)
|
|
@@ -125,7 +125,7 @@ export function consolePresentation(kernel: KernelRegistry, scope: Scope, author
|
|
|
125
125
|
})
|
|
126
126
|
return {
|
|
127
127
|
entities, pages,
|
|
128
|
-
navigation: source.navigation.filter(item => !!item.page !== !!item.entity && permits(item.grant) && (!item.roles || item.roles.includes(scope.role)) && (!item.page || pages.some(page => page.id === item.page))
|
|
128
|
+
navigation: source.navigation.filter(item => (scope.role !== 'member' || item.placement === 'sidebar' && !!item.entity) && !!item.page !== !!item.entity && permits(item.grant) && (!item.roles || item.roles.includes(scope.role)) && (!item.page || pages.some(page => page.id === item.page))
|
|
129
129
|
&& (!item.entity || canRead(item.entity) && (!item.view || entities[item.entity]?.list?.views?.some(view => view.id === item.view)))).map(item => ({ ...pick(item, ['id', 'placement', 'label', 'icon', 'order', 'roles', 'page', 'entity', 'view']),
|
|
130
130
|
...(item.grant ? { grant: safeGrant(item.grant) } : {}),
|
|
131
131
|
...(item.group ? { group: pick(item.group, ['id', 'label', 'order', 'icon']) } : {}) })),
|
package/src/infra/README.md
CHANGED
|
@@ -73,10 +73,19 @@ The API does not discover the account subdomain or generate an auth secret.
|
|
|
73
73
|
| `email?: { from }` | Native `EMAIL` send binding restricted to this sender, plus `EMAIL_FROM` |
|
|
74
74
|
| `webhook?: { url, allowedHosts, service?, events? }` | Explicit URL/host allowlist, optional existing Worker service name and event filter |
|
|
75
75
|
| `internalToken?` | Optional secret `INTERNAL_TOKEN` for protected operations |
|
|
76
|
+
| `opsToken?` | Optional secret `OPS_TOKEN` for protected operations; takes precedence over `INTERNAL_TOKEN` |
|
|
76
77
|
| `accountId?`, `projectRoot?` | Override account environment value or path root; SST normally runs in the app root |
|
|
77
78
|
| `protect?` | Protect/retain primary resources; defaults to true for `production` |
|
|
78
79
|
| `migrationTriggers?` | Extra fingerprints for imported application/plugin verification code |
|
|
79
80
|
|
|
81
|
+
Protected `/internal/*` endpoints keep the `X-Internal-Token` header. Set
|
|
82
|
+
`opsToken` (or the runtime `OPS_TOKEN` binding) to use a dedicated operations
|
|
83
|
+
secret. Once `OPS_TOKEN` is set, only its value is accepted; the legacy
|
|
84
|
+
`INTERNAL_TOKEN` value is rejected with 403. Without `OPS_TOKEN`, `INTERNAL_TOKEN`
|
|
85
|
+
continues to work unchanged. With neither configured, these endpoints return 503.
|
|
86
|
+
Both provisioning options may be supplied during transition; `/internal/ops`
|
|
87
|
+
reports only boolean presence flags for these bindings.
|
|
88
|
+
|
|
80
89
|
Config modules are trusted application code. Relative paths resolve from
|
|
81
90
|
`projectRoot`, defaulting to `process.cwd()` (the app root inside SST). Secrets
|
|
82
91
|
accept Pulumi Outputs/SST secret values and are marked secret in Pulumi state.
|
|
@@ -24,6 +24,8 @@ export interface ProvisionOptions {
|
|
|
24
24
|
email?: { from: string }
|
|
25
25
|
webhook?: { url: Input<string>; allowedHosts: Input<string>; service?: Input<string>; events?: string }
|
|
26
26
|
internalToken?: Input<string>
|
|
27
|
+
/** Secret OPS_TOKEN for protected operations; takes precedence over INTERNAL_TOKEN. */
|
|
28
|
+
opsToken?: Input<string>
|
|
27
29
|
/** Defaults to CLOUDFLARE_DEFAULT_ACCOUNT_ID. Credentials stay in the deploy environment. */
|
|
28
30
|
accountId?: string
|
|
29
31
|
/** Defaults to the SST app root (process.cwd() inside SST run()). */
|
|
@@ -112,7 +114,7 @@ export async function createProvisionPlan(options: ProvisionOptions): Promise<Pr
|
|
|
112
114
|
try {
|
|
113
115
|
if (!(await stat(handler)).isFile() || !(await stat(configPath)).isFile() || !(await stat(migrationsDir)).isDirectory() || (assetsDir && !(await stat(assetsDir)).isDirectory())) throw 0
|
|
114
116
|
} catch { throw new ProvisionDiagnostic('provision_inputs_unreadable') }
|
|
115
|
-
const secrets = [options.authSecret, options.internalToken, options.webhook?.url, options.webhook?.allowedHosts, options.webhook?.service]
|
|
117
|
+
const secrets = [options.authSecret, options.internalToken, options.opsToken, options.webhook?.url, options.webhook?.allowedHosts, options.webhook?.service]
|
|
116
118
|
.filter((value): value is string => typeof value === 'string' && value.length > 0)
|
|
117
119
|
const schema = await provisionConfigSchema(root, configPath, migrationsDir, secrets)
|
|
118
120
|
try {
|
|
@@ -132,6 +134,7 @@ export async function createProvisionPlan(options: ProvisionOptions): Promise<Pr
|
|
|
132
134
|
...(assetsDir ? ['ASSETS'] : []), ...(options.email ? ['EMAIL', 'EMAIL_FROM'] : []),
|
|
133
135
|
...(options.webhook ? ['WEBHOOK_URL', 'WEBHOOK_ALLOWED_HOSTS', ...(options.webhook.service ? ['WEBHOOK_SERVICE'] : []), ...(options.webhook.events ? ['WEBHOOK_EVENTS'] : [])] : []),
|
|
134
136
|
...(options.internalToken ? ['INTERNAL_TOKEN'] : []),
|
|
137
|
+
...(options.opsToken ? ['OPS_TOKEN'] : []),
|
|
135
138
|
],
|
|
136
139
|
migration: {
|
|
137
140
|
command: '"$WB_NODE_BINARY" "$WB_MIGRATION_BIN" migrate "$WB_DATABASE_ID" "$WB_MIGRATIONS_DIRECTORY" --config "$WB_CONFIG_MODULE"',
|
package/src/infra/provision.ts
CHANGED
|
@@ -73,6 +73,7 @@ export async function provision(options: ProvisionOptions): Promise<ProvisionRes
|
|
|
73
73
|
{ name: 'EVENTS_QUEUE', type: 'queue', queueName: events.nodes.queue.queueName },
|
|
74
74
|
{ name: 'BETTER_AUTH_SECRET', type: 'secret_text', text: secret(options.authSecret, true) },
|
|
75
75
|
...(options.internalToken ? [{ name: 'INTERNAL_TOKEN', type: 'secret_text', text: secret(options.internalToken) }] : []),
|
|
76
|
+
...(options.opsToken ? [{ name: 'OPS_TOKEN', type: 'secret_text', text: secret(options.opsToken) }] : []),
|
|
76
77
|
...(options.webhook ? [
|
|
77
78
|
{ name: 'WEBHOOK_URL', type: 'secret_text', text: secret(options.webhook.url) },
|
|
78
79
|
{ name: 'WEBHOOK_ALLOWED_HOSTS', type: 'secret_text', text: secret(options.webhook.allowedHosts) },
|
package/src/ops.ts
CHANGED
|
@@ -29,6 +29,6 @@ export async function opsStatus(env: RuntimeEnv, config: InstanceConfig) {
|
|
|
29
29
|
} catch { /* Presence alone cannot prove the binding target is healthy. */ }
|
|
30
30
|
return { queries: queryMetrics(env.DB), ...(await relayMetrics(env)), lastRun: await lastRelayRun(env), webhookServiceHealthy, schema: await schemaStatus(env, config),
|
|
31
31
|
tables: { DB: await tables(env.DB) },
|
|
32
|
-
bindings: { EVENTS_QUEUE: typeof env.EVENTS_QUEUE?.sendBatch === 'function', DB: !!env.DB, AUDIT_KV: !!env.AUDIT_KV, WEBHOOK_SERVICE: typeof env.WEBHOOK_SERVICE?.fetch === 'function', INTERNAL_TOKEN: !!env.INTERNAL_TOKEN, WEBHOOK_URL: !!env.WEBHOOK_URL, WEBHOOK_ALLOWED_HOSTS: !!env.WEBHOOK_ALLOWED_HOSTS, BETTER_AUTH_SECRET: !!env.BETTER_AUTH_SECRET, AUTH_BASE_URL: !!env.AUTH_BASE_URL },
|
|
32
|
+
bindings: { EVENTS_QUEUE: typeof env.EVENTS_QUEUE?.sendBatch === 'function', DB: !!env.DB, AUDIT_KV: !!env.AUDIT_KV, WEBHOOK_SERVICE: typeof env.WEBHOOK_SERVICE?.fetch === 'function', INTERNAL_TOKEN: !!env.INTERNAL_TOKEN, OPS_TOKEN: !!env.OPS_TOKEN, WEBHOOK_URL: !!env.WEBHOOK_URL, WEBHOOK_ALLOWED_HOSTS: !!env.WEBHOOK_ALLOWED_HOSTS, BETTER_AUTH_SECRET: !!env.BETTER_AUTH_SECRET, AUTH_BASE_URL: !!env.AUTH_BASE_URL },
|
|
33
33
|
}
|
|
34
34
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { rbacRoles, hasActorProjection } from './policies'
|
|
1
2
|
import type { InstanceConfig, OrganizationAction } from './config'
|
|
2
3
|
import type { Scope } from './types'
|
|
3
4
|
import { ApiError } from './errors'
|
|
@@ -32,7 +33,8 @@ export function canGrantRole(config: InstanceConfig, actorRole: string, targetRo
|
|
|
32
33
|
return [...effectiveRolePrivileges(config, targetRole)].every(privilege => issuer.has(privilege))
|
|
33
34
|
}
|
|
34
35
|
export function organizationPermission(config: InstanceConfig, scope: Scope, action: OrganizationAction) {
|
|
35
|
-
if (scope.actor.type !== 'user') throw new ApiError(403, 'user_required')
|
|
36
|
+
if (scope.actor.type !== 'user' && !(scope.actor.type === 'agent' && ['invitations.create', 'invitations.read', 'invitations.revoke'].includes(action))) throw new ApiError(403, 'user_required')
|
|
37
|
+
if (scope.actor.type === 'agent' && (!hasActorProjection(scope) || rbacRoles(scope).some(role => !config.roles.includes(role) || action !== 'invitations.read' && !config.organizationPermissions[role]?.includes(action)))) throw new ApiError(403, 'permission_denied')
|
|
36
38
|
if ((action === 'members.read' || action === 'invitations.read') && config.roles.includes(scope.role)) return
|
|
37
39
|
if (!Object.hasOwn(config.organizationPermissions, scope.role) || !config.organizationPermissions[scope.role].includes(action)) throw new ApiError(403, 'permission_denied')
|
|
38
40
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { rbacRoles } from './policies'
|
|
1
2
|
import type { InstanceConfig, OrganizationAction } from './config'
|
|
2
3
|
import { canGrantRole } from './execution/permissions'
|
|
3
4
|
import type { Scope } from './identity'
|
|
@@ -8,6 +9,12 @@ export function issuerGuard(config: InstanceConfig, scope: Scope, action: Organi
|
|
|
8
9
|
const roles = config.roles.filter(role => action === undefined || config.organizationPermissions[role]?.includes(action))
|
|
9
10
|
.filter(role => grantRole === undefined || canGrantRole(config, role, grantRole))
|
|
10
11
|
.filter(roleFilter)
|
|
12
|
+
if (scope.actor.type === 'agent') {
|
|
13
|
+
return { sql: `EXISTS (SELECT 1 FROM access_tokens credential JOIN memberships issuer ON issuer.organization_id=credential.organization_id AND issuer.user_id=credential.issuer_id
|
|
14
|
+
WHERE credential.id=? AND credential.organization_id=? AND credential.role=? AND credential.revoked_at IS NULL AND credential.expires_at>?
|
|
15
|
+
AND issuer.role=? AND issuer.role IN (${roles.map(() => '?').join(',') || 'NULL'}))`,
|
|
16
|
+
values: [scope.actor.tokenId ?? scope.actor.id, scope.organizationId, scope.role, new Date().toISOString(), rbacRoles(scope).at(-1)!, ...roles] }
|
|
17
|
+
}
|
|
11
18
|
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] }
|
|
12
19
|
}
|
|
13
20
|
/** Each gate raises an SQL assertion before any later membership, email or audit write. */
|
package/src/policies.ts
CHANGED
|
@@ -181,6 +181,7 @@ function constantPredicate(node: Predicate): boolean | undefined {
|
|
|
181
181
|
return undefined
|
|
182
182
|
}
|
|
183
183
|
/** A token's live role caps its issuer's live membership; it cannot outlive a role loss. */
|
|
184
|
+
export const hasActorProjection = (scope: Scope) => projections.has(scope)
|
|
184
185
|
export function rbacRoles(scope: Scope): string[] {
|
|
185
186
|
const principal = projections.get(scope)?.role
|
|
186
187
|
return principal && principal !== scope.role ? [scope.role, String(principal)] : [scope.role]
|
package/src/query/compiler.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { userLinks } from '../user-link-fields'
|
|
1
2
|
import { DisplayPartsExpression, needsDisplayParts, partsAlias } from './display-parts'
|
|
2
3
|
import { expressionInfo, readableComputed, rebindExpression, type ExpressionInfo } from './expressions'
|
|
3
4
|
import { ApiError } from '../errors'
|
|
@@ -27,6 +28,17 @@ class ScopedCondition extends Condition {
|
|
|
27
28
|
: this.filter.kind === 'all' ? '1=1' : '0=1'
|
|
28
29
|
}
|
|
29
30
|
}
|
|
31
|
+
/** Access state is derived only for authorized root rows; credentials never enter projections. */
|
|
32
|
+
class RowAccessCondition extends Condition {
|
|
33
|
+
constructor(private kernel: KernelRegistry, private scope: Scope, private query: QueryInput) { super() }
|
|
34
|
+
toSQL(flavor: ISQLFlavor) {
|
|
35
|
+
const link = userLinks(this.kernel.config).find(link => link.entity === this.query.entity)!
|
|
36
|
+
const bind = (v: unknown) => value(v).toSQL(flavor)
|
|
37
|
+
const root = `SELECT 1 FROM ${quote(link.entity)} access_row WHERE access_row.organization_id=${bind(this.scope.organizationId)} AND access_row.id="row"."id" AND access_row.${quote(link.field)} IS NOT NULL`
|
|
38
|
+
const invitation = `(SELECT CASE WHEN accepted_at IS NOT NULL OR revoked_at IS NOT NULL OR declined_at IS NOT NULL THEN 'no_account' WHEN expired_at IS NOT NULL OR expires_at<=strftime('%Y-%m-%dT%H:%M:%fZ','now') THEN 'expired' ELSE 'invited' END FROM invitations WHERE organization_id=${bind(this.scope.organizationId)} AND target_entity=${bind(this.query.entity)} AND target_row="row"."id" ORDER BY created_at DESC,id DESC LIMIT 1)`
|
|
39
|
+
return `(CASE WHEN EXISTS (${root}) THEN 'signed_in' ELSE coalesce(${invitation},'no_account') END)=${bind(this.query.rowAccess)}`
|
|
40
|
+
}
|
|
41
|
+
}
|
|
30
42
|
class ContainsCondition extends Condition {
|
|
31
43
|
constructor(private column: string, private text: string, private insensitive = false) { super() }
|
|
32
44
|
toSQL(flavor: ISQLFlavor) {
|
|
@@ -483,6 +495,7 @@ export function compileRoot(kernel: KernelRegistry, scope: Scope, query: QueryIn
|
|
|
483
495
|
labeled = labeled.field(display ? Q.raw(`json_extract(${quote('labels')}."${labelAlias(key)}", '$.row.${display}')`) : Q.raw('NULL'), sortAlias(key))
|
|
484
496
|
}
|
|
485
497
|
let ast = labelKeys.length ? Q.select().from(labeled, 'row').field('row.*') : source
|
|
498
|
+
if (query.rowAccess) ast = ast.where(new RowAccessCondition(kernel, scope, query))
|
|
486
499
|
const order = queryOrder(query).map(o => ({ ...o, field: orderField(o) }))
|
|
487
500
|
function searchCondition(key: string, text: string, locale: 'en' | 'cs' = 'en'): Condition {
|
|
488
501
|
const path = labelPath(kernel.config, query.entity, key)
|
package/src/query/schema.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { organizationPermission } from '../organization-permissions'
|
|
2
|
+
import { userLinks } from '../user-link-fields'
|
|
1
3
|
import { z } from 'zod'
|
|
2
4
|
import { baseFields, type Field, type InstanceConfig } from '../config'
|
|
3
5
|
import type { KernelRegistry } from '../kernel/registry'
|
|
@@ -12,7 +14,8 @@ export type Scalar = string | number | boolean | null
|
|
|
12
14
|
export interface Filter { [key: string]: unknown }
|
|
13
15
|
export interface Order { field: string; dir: 'asc' | 'desc'; label?: boolean }
|
|
14
16
|
export interface Selection { labels?: string[]; select?: string[]; where?: Filter; orderBy?: Order[]; limit?: number; include?: Record<string, Selection> }
|
|
15
|
-
export
|
|
17
|
+
export type RowAccessState = 'no_account' | 'invited' | 'expired' | 'signed_in'
|
|
18
|
+
export interface QueryInput extends Selection { rowAccess?: RowAccessState; contextList?: { entity: string; list: string; id: string }; search?: { text: string; fields: string[]; locale?: 'en' | 'cs' }; labelWhere?: Record<string, { contains: string; locale?: 'en' | 'cs' }>; entity: string; limit: number; cursor?: string }
|
|
16
19
|
export const fieldsFor = (config: InstanceConfig, entity: string) => [...baseFields, ...Object.keys(config.entities[entity].fields)]
|
|
17
20
|
export function fieldType(config: InstanceConfig, entity: string, field: string): Field['type'] {
|
|
18
21
|
return config.entities[entity].fields[field]?.type ?? (field === 'version' ? 'int' : ['created_at', 'updated_at'].includes(field) ? 'datetime' : 'string')
|
|
@@ -83,6 +86,7 @@ export function querySchema(config: InstanceConfig, entity: string, rest = false
|
|
|
83
86
|
}
|
|
84
87
|
shape.search = z.strictObject({ text: z.string().min(1).max(2000), fields: z.array(z.enum([...new Set([...names, ...labelNames])] as [string, ...string[]])).min(1).max(names.length + labelNames.length).refine(v => new Set(v).size === v.length), locale: z.enum(['en', 'cs']).optional() }).optional()
|
|
85
88
|
shape.contextList = z.strictObject({ entity: z.string().regex(/^[a-z][a-z0-9_]*$/).max(100), list: z.string().regex(/^[a-z][a-z0-9_]*$/).max(100), id: z.string().min(1).max(2000) }).optional()
|
|
89
|
+
shape.rowAccess = z.enum(['no_account', 'invited', 'expired', 'signed_in']).optional()
|
|
86
90
|
shape.entity = z.literal(name); shape.cursor = z.string().min(1).max(L.cursorBytes).optional()
|
|
87
91
|
}
|
|
88
92
|
return z.strictObject(shape)
|
|
@@ -129,12 +133,18 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
|
|
|
129
133
|
if (!parsed.success) {
|
|
130
134
|
const issue = parsed.error.issues[0]
|
|
131
135
|
// Unknown client keys/values never become error text or paths.
|
|
132
|
-
const known = new Set(['entity', 'select', 'where', 'search', 'text', 'fields', 'locale', 'labelWhere', 'labels', 'label', 'orderBy', 'field', 'dir', 'limit', 'cursor', 'include', 'and', 'or', 'not', 'some', 'none',
|
|
136
|
+
const known = new Set(['entity', 'rowAccess', 'select', 'where', 'search', 'text', 'fields', 'locale', 'labelWhere', 'labels', 'label', 'orderBy', 'field', 'dir', 'limit', 'cursor', 'include', 'and', 'or', 'not', 'some', 'none',
|
|
133
137
|
...Object.values(kernel.config.entities).flatMap(e => [...Object.keys(e.fields), ...Object.keys(e.relations)]), ...baseFields,
|
|
134
138
|
...operatorsFor('string')])
|
|
135
139
|
invalid(issue.path.map(p => typeof p === 'number' ? p : known.has(String(p)) ? String(p) : '?'))
|
|
136
140
|
}
|
|
137
141
|
const query = parsed.data as QueryInput
|
|
142
|
+
if (query.rowAccess) {
|
|
143
|
+
if (!kernel.providers.has('members') || !userLinks(kernel.config).some(link => link.entity === entity)) invalid(['rowAccess'])
|
|
144
|
+
kernel.resourcePermission(scope, 'invitations.read')
|
|
145
|
+
organizationPermission(kernel.config, scope, 'invitations.read')
|
|
146
|
+
kernel.readPermission(scope, entity)
|
|
147
|
+
}
|
|
138
148
|
if (query.contextList) {
|
|
139
149
|
const context = query.contextList
|
|
140
150
|
// Resolve from trusted configuration using the same plugin-over-model precedence as the registry.
|
|
@@ -149,7 +159,7 @@ export function validateQuery(kernel: KernelRegistry, scope: Scope, input: unkno
|
|
|
149
159
|
// This predicate goes through normal field masks, policy-scoped sources and cursor hashing.
|
|
150
160
|
delete query.contextList
|
|
151
161
|
}
|
|
152
|
-
const cost: QueryCost = { depth: 0, relations: 0, fieldRows: 0, exists: 0, nodes: 0 }
|
|
162
|
+
const cost: QueryCost = { depth: 0, relations: 0, fieldRows: 0, exists: query.rowAccess ? 2 : 0, nodes: 0 }
|
|
153
163
|
// Every compiled client table source masks each readable FK once. Visibility
|
|
154
164
|
// probes only test the target's scoped predicate, so do not recursively mask it.
|
|
155
165
|
function foreignKeyCost(name: string) {
|
package/src/types.ts
CHANGED
|
@@ -11,7 +11,7 @@ export interface IdentitySettings {
|
|
|
11
11
|
localPassword?: boolean
|
|
12
12
|
oidc?: { issuer: string; clientId: string; clientSecret: string }
|
|
13
13
|
}
|
|
14
|
-
export interface RuntimeEnv extends SchemaEnvironment, EmailEnvironment { CONFIG_EDITOR_URL?: string; CONFIG_EDITOR_TOKEN?: string; ASSETS?: Fetcher; BUILD_SHA?: string; BUILD_AT?: string; AUTH_BASE_URL?: string; BETTER_AUTH_SECRET?: string; OIDC_ISSUER?: string; OIDC_CLIENT_ID?: string; OIDC_CLIENT_SECRET?: string; DEV_LOCAL_IDENTITY?: string; IDENTITY?: IdentitySettings; DB: D1Database; AUDIT_KV: KVNamespace; EVENTS_QUEUE?: Queue<AuditOutboxRow>; INTERNAL_TOKEN?: string; WEBHOOK_URL?: string; WEBHOOK_EVENTS?: string; WEBHOOK_ALLOWED_HOSTS?: string; WEBHOOK_SERVICE?: Fetcher }
|
|
14
|
+
export interface RuntimeEnv extends SchemaEnvironment, EmailEnvironment { CONFIG_EDITOR_URL?: string; CONFIG_EDITOR_TOKEN?: string; ASSETS?: Fetcher; BUILD_SHA?: string; BUILD_AT?: string; AUTH_BASE_URL?: string; BETTER_AUTH_SECRET?: string; OIDC_ISSUER?: string; OIDC_CLIENT_ID?: string; OIDC_CLIENT_SECRET?: string; DEV_LOCAL_IDENTITY?: string; IDENTITY?: IdentitySettings; DB: D1Database; AUDIT_KV: KVNamespace; EVENTS_QUEUE?: Queue<AuditOutboxRow>; INTERNAL_TOKEN?: string; OPS_TOKEN?: string; WEBHOOK_URL?: string; WEBHOOK_EVENTS?: string; WEBHOOK_ALLOWED_HOSTS?: string; WEBHOOK_SERVICE?: Fetcher }
|
|
15
15
|
export type { ResolvedActor } from './authorization'
|
|
16
16
|
import type { ResolvedActor } from './authorization'
|
|
17
17
|
export type { Actor, Scope } from './identity'
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { InstanceConfig } from './config'
|
|
2
|
+
|
|
3
|
+
/** Read-only link metadata, independent of the privileged account-link writers. */
|
|
4
|
+
export function userLinks(config: InstanceConfig) {
|
|
5
|
+
return Object.entries(config.entities).flatMap(([entity, definition]) => Object.entries(definition.fields)
|
|
6
|
+
.filter(([, field]) => field.userLink).map(([field]) => ({ entity, field })))
|
|
7
|
+
}
|
package/src/user-links.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { userLinks } from './user-link-fields'
|
|
2
|
+
export { userLinks } from './user-link-fields'
|
|
1
3
|
// Core-only account-link writers. No raw SQL or capability is exposed to clients.
|
|
2
4
|
import { z } from 'zod'
|
|
3
5
|
import type { InstanceConfig } from './config'
|
|
@@ -24,10 +26,7 @@ function writer(statement: GuardedStatement, mode: 'link' | 'cleanup'): GuardedS
|
|
|
24
26
|
export const userLinkWriter = (statement: GuardedStatement) => writers.get(statement)
|
|
25
27
|
// Only these core-minted statements can substitute a prepared-role policy filter.
|
|
26
28
|
export const userLinkPolicyFilter = (statement: GuardedStatement) => livePolicies.get(statement)
|
|
27
|
-
|
|
28
|
-
return Object.entries(config.entities).flatMap(([entity, definition]) => Object.entries(definition.fields)
|
|
29
|
-
.filter(([, field]) => field.userLink).map(([field]) => ({ entity, field })))
|
|
30
|
-
}
|
|
29
|
+
|
|
31
30
|
export function assertUnprotectedFields(definition: Pick<InstanceConfig['entities'][string], 'fields'>, fields: string[]) {
|
|
32
31
|
if (fields.some(field => definition.fields[field]?.userLink)) throw new ApiError(400, 'protected_field')
|
|
33
32
|
}
|
|
@@ -48,24 +47,33 @@ export function linkAccountRow(ctx: LinkContext, entity: string, rowId: string,
|
|
|
48
47
|
diagnose: { sql: `SELECT ${unique} AS ok`, bindings: [ctx.scope.organizationId, userId, rowId] }, failureCode: 'account_already_linked',
|
|
49
48
|
}, invitation ? 'cleanup' : 'link')] }
|
|
50
49
|
}
|
|
50
|
+
function revokeAccountInvitations(scope: Scope, userId: string): GuardedStatement {
|
|
51
|
+
return writer({ sql: `UPDATE invitations SET revoked_at=? WHERE organization_id=? AND accepted_at IS NULL AND revoked_at IS NULL
|
|
52
|
+
AND lower(trim(email))=(SELECT lower(trim(email)) FROM users WHERE id=? AND organization_id=?)`,
|
|
53
|
+
bindings: [new Date().toISOString(), scope.organizationId, userId, scope.organizationId] }, 'cleanup')
|
|
54
|
+
}
|
|
51
55
|
/** Config-derived registry, scoped to the removed membership's organization. */
|
|
52
56
|
export function clearAccountLinks(config: InstanceConfig, scope: Scope, userId: string): GuardedStatement[] {
|
|
53
|
-
return userLinks(config).map(({ entity, field }) => writer({
|
|
57
|
+
return [revokeAccountInvitations(scope, userId), ...userLinks(config).map(({ entity, field }) => writer({
|
|
54
58
|
sql: `UPDATE ${quote(entity)} SET ${quote(field)}=NULL,updated_at=?,version=version+1 WHERE organization_id=? AND ${quote(field)}=?`,
|
|
55
59
|
bindings: [new Date().toISOString(), scope.organizationId, userId],
|
|
56
|
-
}, 'cleanup'))
|
|
60
|
+
}, 'cleanup'))]
|
|
57
61
|
}
|
|
58
62
|
/** Remove access clears ALL links of the account selected by this row. The source
|
|
59
63
|
* is cleared last so every statement reads the same selector inside the batch. */
|
|
60
64
|
export function unlinkAccountRow(ctx: LinkContext, entity: string, rowId: string): AtomicRule {
|
|
61
65
|
const field = linkField(ctx.config, entity)
|
|
62
66
|
const links = userLinks(ctx.config).sort((a, b) => Number(a.entity === entity) - Number(b.entity === entity))
|
|
63
|
-
return { name: 'account_unlink', statements:
|
|
67
|
+
return { name: 'account_unlink', statements: [writer({
|
|
68
|
+
sql: `UPDATE invitations SET revoked_at=? WHERE organization_id=? AND accepted_at IS NULL AND revoked_at IS NULL
|
|
69
|
+
AND lower(trim(email))=(SELECT lower(trim(email)) FROM users WHERE organization_id=? AND id=(SELECT ${field} FROM ${quote(entity)} WHERE organization_id=? AND id=?))`,
|
|
70
|
+
bindings: [ctx.now, ctx.scope.organizationId, ctx.scope.organizationId, ctx.scope.organizationId, rowId],
|
|
71
|
+
}, 'cleanup'), ...links.map(link => writer({
|
|
64
72
|
sql: `UPDATE ${quote(link.entity)} SET ${quote(link.field)}=NULL,updated_at=?,version=version+1 WHERE organization_id=? AND ${quote(link.field)}=(SELECT ${field} FROM ${quote(entity)} WHERE organization_id=? AND id=?)`,
|
|
65
73
|
bindings: [ctx.now, ctx.scope.organizationId, ctx.scope.organizationId, rowId],
|
|
66
|
-
}, 'cleanup')) }
|
|
74
|
+
}, 'cleanup'))] }
|
|
67
75
|
}
|
|
68
|
-
/**
|
|
76
|
+
/** The recipient route supplies only the persisted invitation target. */
|
|
69
77
|
export function invitationAccountLink(ctx: LinkContext, invitation: { entity?: string | null; row?: string | null }, userId: string): AtomicRule[] {
|
|
70
78
|
return invitation.entity && invitation.row ? [linkAccountRow(ctx, invitation.entity, invitation.row, userId, true)] : []
|
|
71
79
|
}
|