@workbasehq/core 0.2.15 → 0.3.1
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/src/schema.ts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { assertSchemaLockBound } from './schema/revision'
|
|
2
|
+
export { bindSchemaLock } from './schema/revision'
|
|
3
|
+
export { createPhysicalNameResolver } from './schema/physical-names'
|
|
4
|
+
export { bindOpenApi } from './openapi/routes'
|
|
5
|
+
import { recordActionsSchema, type ActionWhen } from './record-actions-data'
|
|
6
|
+
export { actionReasonKeys } from './record-actions-data'
|
|
7
|
+
import { effectiveSystemGrant } from './access-evaluator'
|
|
8
|
+
import { entityAccessSchema, compileAccess, defineAccess, type AccessInput } from './access'
|
|
9
|
+
import { validatePolicies } from './policies'
|
|
10
|
+
export { defineAccess, compileAccess, accessEntities, accessOperations, accessSystemActions, ACCESS_EXPANSION_LIMITS } from './access'
|
|
11
|
+
export type { AccessInput, EntityAccess, EffectiveAccessPolicy } from './access'
|
|
12
|
+
import { z } from 'zod'
|
|
13
|
+
import { fieldSchema, serializedExpressionSchema, normalizeInstance, organizationActions, type InstanceConfig, type InstanceInput } from './config'
|
|
14
|
+
|
|
15
|
+
import { DeclarationError, type DeclarationPath } from './schema/declaration'
|
|
16
|
+
export { DeclarationError, type DeclarationPath } from './schema/declaration'
|
|
17
|
+
const identifier = z.string().regex(/^[a-z][a-z0-9_]*$/)
|
|
18
|
+
const relationSchema = z.strictObject({
|
|
19
|
+
field: identifier, entity: identifier, many: z.boolean().optional(),
|
|
20
|
+
through: z.strictObject({ entity: identifier, field: identifier, createCommand: z.string().min(1), deleteCommand: z.string().min(1) }).optional(),
|
|
21
|
+
})
|
|
22
|
+
// Field validation and normalized field types are shared with the kernel.
|
|
23
|
+
// Strict objects prevent inline labels and plugin lifecycle hooks from being silently stripped.
|
|
24
|
+
export const declarationSchema = z.strictObject({
|
|
25
|
+
renameFrom: identifier.optional(),
|
|
26
|
+
fields: z.record(identifier, fieldSchema.strict()),
|
|
27
|
+
relations: z.record(identifier, relationSchema).optional(),
|
|
28
|
+
displayField: z.union([serializedExpressionSchema, z.literal(false)]).optional(),
|
|
29
|
+
checks: z.array(z.strictObject({ left: identifier, op: z.enum(['<=', '>=']), right: identifier })).optional(),
|
|
30
|
+
commandsOnly: z.boolean().optional(),
|
|
31
|
+
access: entityAccessSchema.optional(),
|
|
32
|
+
actions: recordActionsSchema.optional(),
|
|
33
|
+
})
|
|
34
|
+
export type EntityInput = z.input<typeof declarationSchema>
|
|
35
|
+
declare const entityBrand: unique symbol
|
|
36
|
+
export type EntityDeclaration<T extends EntityInput = EntityInput> = T & { readonly [entityBrand]: true }
|
|
37
|
+
const entities = new WeakSet<object>()
|
|
38
|
+
|
|
39
|
+
function parse<T>(schema: z.ZodType<T>, input: unknown, prefix: DeclarationPath = []): T {
|
|
40
|
+
const result = schema.safeParse(input)
|
|
41
|
+
if (result.success) return result.data
|
|
42
|
+
const issue = result.error.issues[0]
|
|
43
|
+
throw new DeclarationError([...prefix, ...issue.path.map(key => typeof key === 'symbol' ? String(key) : key)], `${[...prefix, ...issue.path].join('.')}: ${issue.message}`)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
type LiteralFields<T extends EntityInput> = {
|
|
47
|
+
[K in keyof T['fields']]: T['fields'][K] & Record<Exclude<keyof T['fields'][K], keyof EntityInput['fields'][string]>, never>
|
|
48
|
+
}
|
|
49
|
+
/** Data declaration only. loadConfig additionally enforces the literal source boundary. */
|
|
50
|
+
export function defineEntity<const T extends EntityInput>(input: T & Record<Exclude<keyof T, keyof EntityInput>, never> & { fields: LiteralFields<T>; actions?: { [K in keyof T['actions']]: T['actions'][K] & { available?: { when: ActionWhen<T>; reason: string }[] } } }): EntityDeclaration<T> {
|
|
51
|
+
const entity = parse(declarationSchema, input)
|
|
52
|
+
const relations = { ...entity.relations }
|
|
53
|
+
for (const [name, field] of Object.entries(entity.fields)) {
|
|
54
|
+
if (!field.userLink) continue
|
|
55
|
+
if (name !== 'user' || field.type !== 'ref' || field.entity !== 'users' || field.required || field.computed
|
|
56
|
+
|| field.default != null || field.backfillFrom || field.renameFrom) throw new DeclarationError(['fields', name], 'Invalid protected account link')
|
|
57
|
+
if (relations.user_account && (relations.user_account.field !== 'user' || relations.user_account.entity !== 'users' || relations.user_account.many || relations.user_account.through)) throw new DeclarationError(['relations', 'user_account'], 'Invalid user_account relation')
|
|
58
|
+
field.readOnly = true
|
|
59
|
+
relations.user_account = { field: 'user', entity: 'users' }
|
|
60
|
+
}
|
|
61
|
+
const normalized = { ...entity, relations }
|
|
62
|
+
entities.add(normalized)
|
|
63
|
+
return normalized as EntityDeclaration<T>
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The sole allowed call inside an entity literal; generic writes cannot set this ref. */
|
|
67
|
+
export function accountLink() {
|
|
68
|
+
return { type: 'ref', entity: 'users', userLink: true, readOnly: true } as const
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export type ConfigInput = Omit<InstanceInput, 'entities' | 'roles' | 'organizationOwnerRole' | 'permissions' | 'account' | 'languages' | 'enumLabels' | 'baseline' | 'revision'> & {
|
|
72
|
+
entities: Record<string, EntityDeclaration>
|
|
73
|
+
roles: string[]
|
|
74
|
+
organizationOwnerRole: string
|
|
75
|
+
languages: string[]
|
|
76
|
+
permissions?: InstanceInput['permissions']
|
|
77
|
+
access?: AccessInput
|
|
78
|
+
}
|
|
79
|
+
export type SchemaConfig = InstanceConfig & { languages: string[] }
|
|
80
|
+
|
|
81
|
+
const languageList = z.array(z.string().min(1).refine(value => {
|
|
82
|
+
try { return Intl.getCanonicalLocales(value).length === 1 } catch { return false }
|
|
83
|
+
}, 'Invalid language tag')).min(1).refine(values => {
|
|
84
|
+
try { return new Set(Intl.getCanonicalLocales(values)).size === values.length } catch { return false }
|
|
85
|
+
}, 'Duplicate languages')
|
|
86
|
+
|
|
87
|
+
/** Minimal Model B account descriptor; physical DDL belongs to the SDK baseline. */
|
|
88
|
+
function accountEntity(roles: string[]): InstanceInput['entities'][string] {
|
|
89
|
+
return { fields: {
|
|
90
|
+
name: { type: 'string', required: true },
|
|
91
|
+
role: { type: 'enum', values: [...roles], required: true },
|
|
92
|
+
}, displayField: 'name' }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Explicit application roles and SDK accounts; no domain plugin or inline labels. */
|
|
96
|
+
export function defineConfig(input: ConfigInput): SchemaConfig {
|
|
97
|
+
if ('revision' in input) throw new DeclarationError(['revision'], 'revision is bound from schema.lock.json; omit caller-supplied revision')
|
|
98
|
+
const languages = parse(languageList, input.languages, ['languages'])
|
|
99
|
+
const roles = parse(z.array(identifier).min(1).refine(value => new Set(value).size === value.length, 'Duplicate roles'), input.roles, ['roles'])
|
|
100
|
+
if (!roles.includes(input.organizationOwnerRole)) throw new DeclarationError(['organizationOwnerRole'], 'organizationOwnerRole must be in roles')
|
|
101
|
+
if ('account' in input || 'enumLabels' in input) throw new DeclarationError([], 'Account ownership and labels are SDK/dictionary concerns')
|
|
102
|
+
// effectiveAccess is compiler output only; an authored literal would bypass compileAccess.
|
|
103
|
+
if ('effectiveAccess' in input) throw new DeclarationError(['effectiveAccess'], 'effectiveAccess is compiled from access.ts and entity access; it cannot be authored')
|
|
104
|
+
// openapi is generated output bound by bindOpenApi(config, ./openapi.json); an authored literal would desync served bytes from the committed hash.
|
|
105
|
+
if ('openapi' in input) throw new DeclarationError(['openapi'], 'openapi is generated into openapi.json and bound with bindOpenApi; it cannot be authored')
|
|
106
|
+
const domain: InstanceInput['entities'] = {}
|
|
107
|
+
for (const [name, entity] of Object.entries(input.entities)) {
|
|
108
|
+
if (name === 'users') throw new DeclarationError(['entities', name], 'users is SDK-owned; use accountLink()')
|
|
109
|
+
if (!entities.has(entity)) throw new DeclarationError(['entities', name], 'Expected a defineEntity declaration imported from schema/<entity>.ts')
|
|
110
|
+
// Copy through core input types; displayField:false suppresses inference in expand().
|
|
111
|
+
domain[name] = entity as InstanceInput['entities'][string]
|
|
112
|
+
}
|
|
113
|
+
const known = new Set(['users', ...Object.keys(domain)])
|
|
114
|
+
for (const [name, entity] of Object.entries(domain)) {
|
|
115
|
+
for (const [key, field] of Object.entries(entity.fields)) if (field.type === 'ref' && !known.has(field.entity!)) throw new DeclarationError(['entities', name, 'fields', key, 'entity'], `Unknown reference: ${field.entity}`)
|
|
116
|
+
for (const [key, relation] of Object.entries(entity.relations ?? {})) {
|
|
117
|
+
if (!known.has(relation.entity)) throw new DeclarationError(['entities', name, 'relations', key, 'entity'], `Unknown relation target: ${relation.entity}`)
|
|
118
|
+
if (relation.through && !known.has(relation.through.entity)) throw new DeclarationError(['entities', name, 'relations', key, 'through', 'entity'], `Unknown relation target: ${relation.through.entity}`)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
for (const plugin of input.plugins ?? []) {
|
|
122
|
+
if (Object.keys(plugin.model?.entities ?? {}).length || Object.keys(plugin.entities ?? {}).length || plugin.model?.account) throw new DeclarationError(['plugins'], `Plugin ${plugin.name}: new-era domain entities must be imported explicitly`)
|
|
123
|
+
}
|
|
124
|
+
let config: SchemaConfig
|
|
125
|
+
try {
|
|
126
|
+
config = normalizeInstance({ ...input, revision: undefined as never, baseline: 'workbase-sdk', roles, languages,
|
|
127
|
+
entities: { ...domain, users: accountEntity(roles) }, account: { entity: 'users' },
|
|
128
|
+
permissions: input.permissions ?? {},
|
|
129
|
+
} as Parameters<typeof normalizeInstance>[0], true, (error, path) => { throw new DeclarationError(path, error instanceof Error ? error.message : String(error)) }) as SchemaConfig
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (error instanceof DeclarationError) throw error
|
|
132
|
+
if (error instanceof z.ZodError) {
|
|
133
|
+
const issue = error.issues[0]
|
|
134
|
+
throw new DeclarationError(issue.path.map(key => typeof key === 'symbol' ? String(key) : key), issue.message)
|
|
135
|
+
}
|
|
136
|
+
// Kernel expression/display diagnostics already identify their owning entity.
|
|
137
|
+
if (error instanceof Error && 'errors' in error && Array.isArray(error.errors)) {
|
|
138
|
+
const issue = error.errors[0] as { entity?: string; field?: string }
|
|
139
|
+
if (issue?.entity) throw new DeclarationError(['entities', issue.entity, ...(issue.field && domain[issue.entity]?.fields[issue.field] ? ['fields', issue.field, 'computed'] : ['displayField'])], error.message)
|
|
140
|
+
}
|
|
141
|
+
throw error
|
|
142
|
+
}
|
|
143
|
+
if (input.access || Object.values(input.entities).some(entity => entity.access)) {
|
|
144
|
+
if (!input.access) throw new DeclarationError(['access'], 'Expected shared access.ts declaration')
|
|
145
|
+
if (input.permissions || input.policies || input.organizationPermissions) throw new DeclarationError(['access'], 'Authored access replaces permissions, policies and organizationPermissions')
|
|
146
|
+
const declarations = Object.fromEntries(Object.entries(input.entities).map(([name, entity]) => [name, entity.access]))
|
|
147
|
+
const policy = compileAccess(config, declarations, defineAccess(input.access))
|
|
148
|
+
config.effectiveAccess = policy
|
|
149
|
+
// Derived compatibility projections feed existing SQL issuer guards and metadata.
|
|
150
|
+
// Authorization always evaluates the normalized policy, including explicit denials.
|
|
151
|
+
config.permissions = Object.fromEntries(config.roles.map(role => [role,
|
|
152
|
+
Object.fromEntries(Object.keys(config.entities).map(entity => [entity, policy.entities
|
|
153
|
+
.filter(rule => rule.role === role && rule.entity === entity && rule.decision === 'allow').map(rule => rule.operation)])),
|
|
154
|
+
]))
|
|
155
|
+
config.organizationPermissions = Object.fromEntries(config.roles.map(role => [role,
|
|
156
|
+
organizationActions.filter(action => effectiveSystemGrant(policy, [role], action)),
|
|
157
|
+
]))
|
|
158
|
+
validatePolicies(config)
|
|
159
|
+
}
|
|
160
|
+
config.baseline = 'workbase-sdk'
|
|
161
|
+
Object.defineProperty(config, 'revision', { configurable: true, get() {
|
|
162
|
+
assertSchemaLockBound({ baseline: 'workbase-sdk' })
|
|
163
|
+
} })
|
|
164
|
+
return config
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Shape/era check only: copies and serialized configs retain the SDK marker.
|
|
168
|
+
* This does not establish provenance or compiled access; the kernel checks access. */
|
|
169
|
+
export function isSchemaConfig(value: unknown): value is SchemaConfig {
|
|
170
|
+
return typeof value === 'object' && value !== null && 'baseline' in value && value.baseline === 'workbase-sdk'
|
|
171
|
+
}
|
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; OPS_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; OPENAPI_SHA256?: 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,36 @@
|
|
|
1
|
+
import type { InstanceConfig } from './config'
|
|
2
|
+
import { ApiError } from './errors'
|
|
3
|
+
import { quote } from './migrations/schema'
|
|
4
|
+
import { userLinks } from './user-link-fields'
|
|
5
|
+
import type { SqlStatement } from './execution/types'
|
|
6
|
+
|
|
7
|
+
/** Workspace membership and the account's workspace must both match.
|
|
8
|
+
* Shared by the picker read, the Link preflight and its atomic write-time check. */
|
|
9
|
+
export function linkableMembers(organizationId: string, userId?: string): SqlStatement {
|
|
10
|
+
return {
|
|
11
|
+
sql: `SELECT u.id FROM users u JOIN memberships m ON m.user_id=u.id AND m.organization_id=u.organization_id WHERE ${userId === undefined ? '' : 'u.id=? AND '}u.organization_id=?`,
|
|
12
|
+
bindings: [...(userId === undefined ? [] : [userId]), organizationId],
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Uniqueness is per configured entity and workspace, excluding the target row.
|
|
17
|
+
* The read uses only the fixed Members candidate alias; clients cannot supply SQL.
|
|
18
|
+
* Keep this separate from membership preflight so duplicates remain HTTP 409. */
|
|
19
|
+
export function accountLinkUnique(config: InstanceConfig, organizationId: string, target: { entity: string; row: string }, candidate: { userId: string } | { member: true }): SqlStatement {
|
|
20
|
+
const link = userLinks(config).find(link => link.entity === target.entity)
|
|
21
|
+
if (!link) throw new ApiError(400, 'user_link_required')
|
|
22
|
+
return {
|
|
23
|
+
sql: `NOT EXISTS (SELECT 1 FROM ${quote(link.entity)} other WHERE other.organization_id=? AND other.${quote(link.field)}=${'userId' in candidate ? '?' : 'u.id'} AND other.id<>?)`,
|
|
24
|
+
bindings: [organizationId, ...('userId' in candidate ? [candidate.userId] : []), target.row],
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A known invitee must satisfy the same per-entity uniqueness rule, even if
|
|
29
|
+
* their membership was removed. Unknown addresses remain valid invitations. */
|
|
30
|
+
export function invitationAccountUnique(config: InstanceConfig, organizationId: string, target: { entity: string; row: string }, email: string): SqlStatement {
|
|
31
|
+
const unique = accountLinkUnique(config, organizationId, target, { member: true })
|
|
32
|
+
return {
|
|
33
|
+
sql: `NOT EXISTS (SELECT 1 FROM users u WHERE u.organization_id=? AND lower(trim(u.email))=lower(trim(?)) AND NOT (${unique.sql}))`,
|
|
34
|
+
bindings: [organizationId, email, ...(unique.bindings ?? [])],
|
|
35
|
+
}
|
|
36
|
+
}
|
package/src/user-links.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { writeFilter } from './execution/policies'
|
|
|
11
11
|
import { kernelFor } from './kernel/registry'
|
|
12
12
|
import { organizationPermission } from './organization-permissions'
|
|
13
13
|
import { issuerGuard } from './organization-rules'
|
|
14
|
+
import { accountLinkUnique, linkableMembers } from './user-link-eligibility'
|
|
14
15
|
|
|
15
16
|
type LinkContext = Pick<PlanningContext, 'config' | 'scope' | 'now'>
|
|
16
17
|
// Frozen statement identity, rather than caller-supplied metadata, grants the exception.
|
|
@@ -39,12 +40,13 @@ function linkField(config: InstanceConfig, entity: string) {
|
|
|
39
40
|
* The invitation caller runs this AFTER its membership insert, in the same plan. */
|
|
40
41
|
export function linkAccountRow(ctx: LinkContext, entity: string, rowId: string, userId: string, invitation = false): AtomicRule {
|
|
41
42
|
const field = linkField(ctx.config, entity); const table = quote(entity)
|
|
42
|
-
const
|
|
43
|
+
const member = linkableMembers(ctx.scope.organizationId, userId)
|
|
44
|
+
const unique = accountLinkUnique(ctx.config, ctx.scope.organizationId, { entity, row: rowId }, { userId })
|
|
43
45
|
return { name: 'account_link', statements: [writer({
|
|
44
|
-
sql: `UPDATE ${table} SET ${field}=?,updated_at=?,version=version+1 WHERE organization_id=? AND id=? AND ${unique}
|
|
45
|
-
AND EXISTS (
|
|
46
|
-
bindings: [userId, ctx.now, ctx.scope.organizationId, rowId,
|
|
47
|
-
diagnose: { sql: `SELECT ${unique} AS ok`, bindings:
|
|
46
|
+
sql: `UPDATE ${table} SET ${field}=?,updated_at=?,version=version+1 WHERE organization_id=? AND id=? AND ${unique.sql}
|
|
47
|
+
AND EXISTS (${member.sql})`,
|
|
48
|
+
bindings: [userId, ctx.now, ctx.scope.organizationId, rowId, ...(unique.bindings ?? []), ...(member.bindings ?? [])], expectRows: 1,
|
|
49
|
+
diagnose: { sql: `SELECT ${unique.sql} AS ok`, bindings: unique.bindings }, failureCode: 'account_already_linked',
|
|
48
50
|
}, invitation ? 'cleanup' : 'link')] }
|
|
49
51
|
}
|
|
50
52
|
function revokeAccountInvitations(scope: Scope, userId: string): GuardedStatement {
|
|
@@ -78,14 +80,19 @@ export function invitationAccountLink(ctx: LinkContext, invitation: { entity?: s
|
|
|
78
80
|
return invitation.entity && invitation.row ? [linkAccountRow(ctx, invitation.entity, invitation.row, userId, true)] : []
|
|
79
81
|
}
|
|
80
82
|
|
|
81
|
-
const actions = new
|
|
83
|
+
const actions = new WeakMap<object, 'invitations.create' | 'invitations.revoke'>()
|
|
84
|
+
export function registerUserLinkAction<T extends AtomicOperation<any>>(operation: T, permission: 'invitations.create' | 'invitations.revoke' = 'invitations.create'): T {
|
|
85
|
+
actions.set(operation.plan, permission)
|
|
86
|
+
return operation
|
|
87
|
+
}
|
|
82
88
|
export function userLinkActionPermission(config: InstanceConfig, scope: Scope, operation: AtomicOperation<any>) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
89
|
+
const permission = actions.get(operation.plan)
|
|
90
|
+
if (!permission) return
|
|
91
|
+
kernelFor(config).resourcePermission(scope, permission)
|
|
92
|
+
organizationPermission(config, scope, permission)
|
|
86
93
|
}
|
|
87
94
|
interface PreparedIssuer { role: string; filter: SqlStatement }
|
|
88
|
-
export function userLinkCommands(config: InstanceConfig): AtomicOperation<any>[] {
|
|
95
|
+
export function userLinkCommands(config: InstanceConfig, entryPoint: 'legacy' | 'record-action' = 'legacy'): AtomicOperation<any>[] {
|
|
89
96
|
return userLinks(config).flatMap(({ entity }) => (['link_account', 'remove_access'] as const).map(action => {
|
|
90
97
|
const rowId = z.string().min(1).meta({ referenceEntity: entity })
|
|
91
98
|
const inputSchema: z.ZodType<{ rowId: string; userId?: string }> = action === 'link_account'
|
|
@@ -95,13 +102,13 @@ export function userLinkCommands(config: InstanceConfig): AtomicOperation<any>[]
|
|
|
95
102
|
ui: { label: action === 'link_account' ? { en: 'Link', cs: 'Propojit účet' } : { en: 'Remove access', cs: 'Odebrat přístup' } },
|
|
96
103
|
input: inputSchema,
|
|
97
104
|
async prepare(ctx, input) {
|
|
98
|
-
const policy = kernelFor(ctx.config).tableFilter(entity, ctx.scope)
|
|
105
|
+
const policy = kernelFor(ctx.config).tableFilter(entity, ctx.scope, 'update')
|
|
99
106
|
if (policy.kind === 'none') throw new ApiError(404, 'not_found')
|
|
100
107
|
if (!await ctx.reader.first({ sql: `SELECT id FROM ${quote(entity)} WHERE organization_id=? AND id=?`, bindings: [ctx.scope.organizationId, input.rowId] })) throw new ApiError(404, 'not_found')
|
|
101
|
-
if (action === 'link_account' && !await ctx.reader.first(
|
|
108
|
+
if (action === 'link_account' && !await ctx.reader.first(linkableMembers(ctx.scope.organizationId, input.userId!))) throw new ApiError(404, 'member_not_found')
|
|
102
109
|
const kernel = kernelFor(ctx.config)
|
|
103
110
|
kernel.atomicPermission(ctx.scope, operation, input)
|
|
104
|
-
return { role: ctx.scope.role, filter: writeFilter(kernel, ctx.scope, entity) }
|
|
111
|
+
return { role: ctx.scope.role, filter: writeFilter(kernel, ctx.scope, entity, entity, 'update') }
|
|
105
112
|
},
|
|
106
113
|
plan(ctx, input) {
|
|
107
114
|
// A concurrent role change requires a fresh request under that role.
|
|
@@ -120,12 +127,16 @@ export function userLinkCommands(config: InstanceConfig): AtomicOperation<any>[]
|
|
|
120
127
|
// Its WHERE checks the live pre-image. Keep the executor's row capture
|
|
121
128
|
// and 403 denial, without checking the cleared source against the policy.
|
|
122
129
|
livePolicies.set(issuer, Object.freeze({ sql: '1=1' }))
|
|
123
|
-
return { rules: [{ name: 'account_link_issuer', statements: [issuer] }, mutation
|
|
130
|
+
return { rules: [{ name: 'account_link_issuer', statements: [issuer] }, mutation, ...(action === 'link_account' && entryPoint === 'record-action' ? [{ name: 'supersede_row_invitation', statements: [writer({
|
|
131
|
+
// Commit together with the confirmed link, never during discovery.
|
|
132
|
+
// A failed eligibility/policy check rolls this revocation back too.
|
|
133
|
+
sql: `UPDATE invitations SET revoked_at=? WHERE organization_id=? AND target_entity=? AND target_row=? AND accepted_at IS NULL AND revoked_at IS NULL AND declined_at IS NULL AND expired_at IS NULL AND expires_at>?`,
|
|
134
|
+
bindings: [ctx.now, ctx.scope.organizationId, entity, input.rowId, ctx.now],
|
|
135
|
+
}, 'cleanup')] }] : [])],
|
|
124
136
|
event: { operation: action === 'link_account' ? 'account.linked' : 'account.access_removed', entity, entityId: input.rowId },
|
|
125
137
|
result: { status: 200, body: { id: input.rowId } } }
|
|
126
138
|
},
|
|
127
139
|
}
|
|
128
|
-
|
|
129
|
-
return operation
|
|
140
|
+
return registerUserLinkAction(operation)
|
|
130
141
|
}))
|
|
131
142
|
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { registerPostCommit } from './execution/post-commit'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
import type { InstanceConfig } from './config'
|
|
4
|
+
import type { RuntimeEnv } from './types'
|
|
5
|
+
import type { AtomicOperation } from './execution/types'
|
|
6
|
+
import { userLinkCommands, registerUserLinkAction } from './user-links'
|
|
7
|
+
import { kernelFor } from './kernel/registry'
|
|
8
|
+
import { accountCommand } from './account-action-conditions'
|
|
9
|
+
import { rowInvitationGuard } from './row-invitations'
|
|
10
|
+
import { invitationAccountUnique } from './user-link-eligibility'
|
|
11
|
+
import { invitationRole } from './worker-access'
|
|
12
|
+
import { issuerGuard } from './organization-rules'
|
|
13
|
+
import { actorAccountId } from './policies'
|
|
14
|
+
import { ApiError } from './errors'
|
|
15
|
+
import { randomToken, sha256, ulid } from './crypto'
|
|
16
|
+
|
|
17
|
+
export { isAccountAccessCommand } from './account-command'
|
|
18
|
+
/** Internal command schemas own the path id. HTTP input is parsed separately,
|
|
19
|
+
* and cannot supply selectors, grants or server credential destinations. */
|
|
20
|
+
export function workerAccessCommands(config: InstanceConfig, env?: RuntimeEnv): AtomicOperation<any>[] {
|
|
21
|
+
return Object.keys(config.effectiveAccess?.accountLinks ?? {}).flatMap(entity => {
|
|
22
|
+
// Only record-action links supersede pending row invitations.
|
|
23
|
+
const commands = userLinkCommands(config, 'record-action')
|
|
24
|
+
const link = commands.find(command => command.name === `${entity}/link_account`)!
|
|
25
|
+
const unlink = commands.find(command => command.name === `${entity}/remove_access`)!
|
|
26
|
+
const id = z.string().min(1).meta({ referenceEntity: entity })
|
|
27
|
+
const adapt = (target: AtomicOperation<any>, name: string): AtomicOperation<any> => {
|
|
28
|
+
const map = (input: any) => ({ rowId: input.id, ...(name === 'link_account' ? { userId: input.user_id } : {}) })
|
|
29
|
+
return registerUserLinkAction({ name: accountCommand(entity, name), permission: target.permission,
|
|
30
|
+
input: name === 'link_account' ? z.strictObject({ id, user_id: z.string().min(1) }) : z.strictObject({ id }),
|
|
31
|
+
async prepare(ctx, input) {
|
|
32
|
+
try { return await target.prepare?.(ctx, map(input)) }
|
|
33
|
+
catch (error) { if (error instanceof ApiError && error.status === 404) throw new ApiError(404, 'not_found'); throw error }
|
|
34
|
+
},
|
|
35
|
+
plan: (ctx, input) => target.plan(ctx, map(input)),
|
|
36
|
+
})
|
|
37
|
+
}
|
|
38
|
+
const cancel = registerUserLinkAction({ name: accountCommand(entity, 'cancel_invite'), permission: { entity, operation: 'update' }, input: z.strictObject({ id }),
|
|
39
|
+
plan(ctx, input) {
|
|
40
|
+
const guard = issuerGuard(ctx.config, ctx.scope, 'invitations.revoke', undefined, role => role === ctx.scope.role)
|
|
41
|
+
return { rules: [{ name: 'cancel_invite', statements: [{
|
|
42
|
+
sql: `UPDATE invitations SET revoked_at=? WHERE organization_id=? AND target_entity=? AND target_row=? AND accepted_at IS NULL AND revoked_at IS NULL AND declined_at IS NULL AND expired_at IS NULL AND expires_at>? AND ${guard.sql}`,
|
|
43
|
+
bindings: [ctx.now, ctx.scope.organizationId, entity, input.id, ctx.now, ...guard.values], expectRows: 1,
|
|
44
|
+
}] }], event: { operation: 'invitation.revoked', entity, entityId: input.id }, result: { status: 200, body: { id: input.id } } }
|
|
45
|
+
},
|
|
46
|
+
}, 'invitations.revoke')
|
|
47
|
+
const invite = registerPostCommit(registerUserLinkAction({ name: accountCommand(entity, 'invite'), permission: { entity, operation: 'create' }, input: z.strictObject({ id, email: z.string().trim().pipe(z.email()).transform(email => email.toLowerCase()) }),
|
|
48
|
+
async prepare(ctx, input) {
|
|
49
|
+
const unique = invitationAccountUnique(ctx.config, ctx.scope.organizationId, { entity, row: input.id }, input.email)
|
|
50
|
+
if (!await ctx.reader.first({ sql: `SELECT 1 WHERE ${unique.sql}`, bindings: unique.bindings })) throw new ApiError(409, 'account_already_linked')
|
|
51
|
+
// Prepare the unsigned selector and mail metadata outside config/locks.
|
|
52
|
+
const role = invitationRole(ctx.config, entity)
|
|
53
|
+
const token = randomToken(), deliveryToken = randomToken(), invitationId = ulid(), outboxId = ulid()
|
|
54
|
+
const expires = new Date(Date.now() + 7 * 86400000).toISOString()
|
|
55
|
+
const port = kernelFor(ctx.config).invitationMail
|
|
56
|
+
const url = await port.copyLink(env!, token)
|
|
57
|
+
const guard = rowInvitationGuard(ctx.config, ctx.scope, { entity, row: input.id })
|
|
58
|
+
const mail = await port.prepare(env!, ctx.config, outboxId, ctx.scope.organizationId, input.email, deliveryToken, {
|
|
59
|
+
inviterId: actorAccountId(ctx.scope), role, expiresAt: expires, kind: 'invite', invitationId,
|
|
60
|
+
eligible: async () => !!await env!.DB.prepare(`SELECT 1 WHERE ${guard.sql}`).bind(...guard.values).first(),
|
|
61
|
+
})
|
|
62
|
+
return { role, invitationId, outboxId, expires, hash: await sha256(token), deliveryHash: await sha256(deliveryToken), url, mail, deliveryStatus: () => port.status(env!, ctx.config, outboxId) }
|
|
63
|
+
},
|
|
64
|
+
plan(ctx, input) {
|
|
65
|
+
const p = ctx.prepared
|
|
66
|
+
const guard = rowInvitationGuard(ctx.config, ctx.scope, { entity, row: input.id })
|
|
67
|
+
const unique = invitationAccountUnique(ctx.config, ctx.scope.organizationId, { entity, row: input.id }, input.email)
|
|
68
|
+
return { rules: [{ name: 'invite', statements: [{
|
|
69
|
+
// Migration 004's BEFORE INSERT trigger expires the stale row before
|
|
70
|
+
// its partial unique index is checked, within this same D1 batch.
|
|
71
|
+
sql: `INSERT INTO invitations (id,organization_id,email,role,token_hash,delivery_token_hash,expires_at,inviter_id,created_at,delivery_outbox_id,target_entity,target_row) SELECT ?,?,?,?,?,?,?,?,?,?,?,? WHERE ${guard.sql} AND ${unique.sql}`,
|
|
72
|
+
bindings: [p.invitationId, ctx.scope.organizationId, input.email, p.role, p.hash, p.deliveryHash, p.expires, actorAccountId(ctx.scope), ctx.now, p.outboxId, entity, input.id, ...guard.values, ...(unique.bindings ?? [])], expectRows: 1,
|
|
73
|
+
diagnose: { sql: `SELECT ${unique.sql} AS ok`, bindings: unique.bindings }, failureCode: 'account_already_linked',
|
|
74
|
+
}, p.mail.intent(p.expires)] }], event: { operation: 'invitation.created', entity: 'invitations', entityId: p.invitationId },
|
|
75
|
+
result: { status: 201, body: { invitation_id: p.invitationId, expires_at: p.expires, accept_url: p.url,
|
|
76
|
+
delivery: { status: 'unknown', attempts: 0, sent_at: null, error: 'email_delivery_unknown' } } } }
|
|
77
|
+
},
|
|
78
|
+
}), async (prepared, result) => {
|
|
79
|
+
try {
|
|
80
|
+
await prepared.mail.deliver()
|
|
81
|
+
return { ...result, body: { ...result.body, delivery: await prepared.deliveryStatus() } }
|
|
82
|
+
} catch {
|
|
83
|
+
console.error(JSON.stringify({ event: 'invitation_post_commit_failed', outboxId: prepared.outboxId }))
|
|
84
|
+
return result
|
|
85
|
+
}
|
|
86
|
+
})
|
|
87
|
+
return [invite, cancel, adapt(link, 'link_account'), adapt(unlink, 'unlink_account')]
|
|
88
|
+
})
|
|
89
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { memberIdentities, canReadMembers } from './member-identities'
|
|
2
|
+
import type { InstanceConfig } from './config'
|
|
3
|
+
import type { Scope } from './types'
|
|
4
|
+
import { ApiError } from './errors'
|
|
5
|
+
import { kernelFor } from './kernel/registry'
|
|
6
|
+
import { organizationPermission } from './organization-permissions'
|
|
7
|
+
import { userLinks } from './user-link-fields'
|
|
8
|
+
import { writeFilter } from './execution/policies'
|
|
9
|
+
import { quote } from './migrations/schema'
|
|
10
|
+
|
|
11
|
+
/** SDK mappings are explicit; historical instances retain their member target. */
|
|
12
|
+
export function invitationRole(config: InstanceConfig, entity: string): string {
|
|
13
|
+
if (config.baseline !== 'workbase-sdk') return 'member'
|
|
14
|
+
const role = config.effectiveAccess?.accountLinks?.[entity]?.invitationRole
|
|
15
|
+
if (!role) throw new ApiError(400, 'invitation_role_required')
|
|
16
|
+
return role
|
|
17
|
+
}
|
|
18
|
+
export function canReadAccountAccess(config: InstanceConfig, scope: Scope, entity: string): boolean {
|
|
19
|
+
if (!config.effectiveAccess?.accountLinks?.[entity]) return false
|
|
20
|
+
try {
|
|
21
|
+
kernelFor(config).resourcePermission(scope, 'invitations.read')
|
|
22
|
+
organizationPermission(config, scope, 'invitations.read')
|
|
23
|
+
return true
|
|
24
|
+
} catch { return false }
|
|
25
|
+
}
|
|
26
|
+
export interface AccountAccessState {
|
|
27
|
+
state: 'no_account' | 'invited' | 'expired' | 'linked'
|
|
28
|
+
account: { id: string; display_name: string; email: string } | null
|
|
29
|
+
invitation: { id: string; email: string; expires_at: string } | null
|
|
30
|
+
}
|
|
31
|
+
/** The caller checks invitation and row read authority before looking up history. */
|
|
32
|
+
export async function latestRowInvitation(db: D1Database, organizationId: string, entity: string, id: string): Promise<(NonNullable<AccountAccessState['invitation']> & { expired_at: string | null }) | null> {
|
|
33
|
+
// Select history before filtering terminal rows, so a cancelled replacement
|
|
34
|
+
// never resurrects an older expired invitation.
|
|
35
|
+
const latest = await db.prepare(`SELECT id,email,expires_at,expired_at,accepted_at,revoked_at,declined_at FROM invitations WHERE organization_id=? AND target_entity=? AND target_row=? ORDER BY created_at DESC,id DESC LIMIT 1`)
|
|
36
|
+
.bind(organizationId, entity, id).first<{ id: string; email: string; expires_at: string; expired_at: string | null; accepted_at: string | null; revoked_at: string | null; declined_at: string | null }>()
|
|
37
|
+
if (!latest || latest.accepted_at || latest.revoked_at || latest.declined_at) return null
|
|
38
|
+
return { id: latest.id, email: latest.email, expires_at: latest.expires_at, expired_at: latest.expired_at }
|
|
39
|
+
}
|
|
40
|
+
/** Only public card data leaves this service. The caller checks invitations.read;
|
|
41
|
+
* row read and Members identity disclosure retain independent authority. */
|
|
42
|
+
export async function accountAccessState(config: InstanceConfig, scope: Scope, db: D1Database, entity: string, id: string): Promise<AccountAccessState> {
|
|
43
|
+
const link = userLinks(config).find(link => link.entity === entity)
|
|
44
|
+
if (!link) throw new ApiError(400, 'user_link_required')
|
|
45
|
+
const kernel = kernelFor(config)
|
|
46
|
+
kernel.permission(scope, entity, 'read')
|
|
47
|
+
const filter = writeFilter(kernel, scope, entity)
|
|
48
|
+
const row = await db.prepare(`SELECT ${quote(link.field)} AS account_id FROM ${quote(entity)} WHERE organization_id=? AND id=? AND (${filter.sql})`)
|
|
49
|
+
.bind(scope.organizationId, id, ...(filter.bindings ?? [])).first<{ account_id: string | null }>()
|
|
50
|
+
if (!row) throw new ApiError(404, 'not_found')
|
|
51
|
+
if (row.account_id) {
|
|
52
|
+
const member = kernel.fieldMask(entity, scope).includes(link.field) && canReadMembers(config, scope)
|
|
53
|
+
? (await memberIdentities(config, scope, db, row.account_id))[0] : undefined
|
|
54
|
+
const account = member ? { id: member.user_id, display_name: member.display_name ?? member.email, email: member.email } : null
|
|
55
|
+
return { state: 'linked', account, invitation: null }
|
|
56
|
+
}
|
|
57
|
+
const latest = await latestRowInvitation(db, scope.organizationId, entity, id)
|
|
58
|
+
if (!latest) return { state: 'no_account', account: null, invitation: null }
|
|
59
|
+
return { state: latest.expired_at || latest.expires_at <= new Date().toISOString() ? 'expired' : 'invited', account: null,
|
|
60
|
+
invitation: { id: latest.id, email: latest.email, expires_at: latest.expires_at } }
|
|
61
|
+
}
|