@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.
Files changed (96) hide show
  1. package/package.json +18 -3
  2. package/src/access-evaluator.ts +72 -0
  3. package/src/access-guards.ts +35 -0
  4. package/src/access-inputs.ts +62 -0
  5. package/src/access-lock/cli.ts +34 -0
  6. package/src/access-lock.ts +183 -0
  7. package/src/access.ts +209 -0
  8. package/src/account-action-conditions.ts +27 -0
  9. package/src/account-command.ts +8 -0
  10. package/src/admin-ui.tsx +3 -2
  11. package/src/app.ts +3 -3
  12. package/src/canonical.ts +6 -0
  13. package/src/capabilities.ts +5 -3
  14. package/src/commands.ts +14 -8
  15. package/src/config.ts +105 -69
  16. package/src/console-build.ts +37 -0
  17. package/src/console-contract.ts +4 -0
  18. package/src/console-model.ts +2 -0
  19. package/src/console.ts +3 -3
  20. package/src/crud.ts +13 -7
  21. package/src/dev-mailbox.ts +35 -0
  22. package/src/display-identity.ts +12 -0
  23. package/src/execution/atomic.ts +17 -3
  24. package/src/execution/policies.ts +14 -6
  25. package/src/execution/policy-receipts.ts +6 -5
  26. package/src/execution/post-commit.ts +11 -0
  27. package/src/execution/types.ts +1 -1
  28. package/src/index.ts +2 -0
  29. package/src/infra/README.md +39 -3
  30. package/src/infra/d1-migrations.ts +4 -3
  31. package/src/infra/instance-migrations.ts +26 -5
  32. package/src/infra/provision-config-main.mjs +3 -3
  33. package/src/infra/provision-diagnostics.ts +4 -0
  34. package/src/infra/provision-plan.ts +34 -5
  35. package/src/infra/provision.ts +26 -4
  36. package/src/infra/schema.ts +1 -1
  37. package/src/kernel/invitation-mail-port.ts +26 -0
  38. package/src/kernel/mail-outbox-port.ts +4 -2
  39. package/src/kernel/migrations.ts +38 -15
  40. package/src/kernel/plugin.ts +2 -0
  41. package/src/kernel/predicate.ts +15 -3
  42. package/src/kernel/registry.ts +69 -12
  43. package/src/member-bootstrap.ts +65 -0
  44. package/src/member-identities.ts +42 -0
  45. package/src/migrations/diagnostics.ts +6 -1
  46. package/src/migrations/model-b.ts +2 -1
  47. package/src/migrations/operational-evidence.ts +51 -0
  48. package/src/migrations/planner.ts +12 -1
  49. package/src/migrations/rebuild.ts +17 -12
  50. package/src/migrations/reset-era.ts +29 -0
  51. package/src/migrations/schema-bundle.ts +43 -0
  52. package/src/migrations/schema-cli.ts +74 -0
  53. package/src/migrations/schema-git.ts +36 -0
  54. package/src/migrations/schema-lock.ts +159 -0
  55. package/src/migrations/schema-plan.ts +94 -0
  56. package/src/migrations/schema.ts +73 -48
  57. package/src/migrations/sdk-baseline.ts +35 -0
  58. package/src/migrations/system-schema.ts +39 -0
  59. package/src/model-inputs.ts +25 -0
  60. package/src/openapi/cli.ts +72 -0
  61. package/src/openapi/generate.ts +166 -0
  62. package/src/openapi/input-projection.ts +131 -0
  63. package/src/openapi/public-paths.ts +80 -0
  64. package/src/openapi/routes.ts +29 -0
  65. package/src/ops.ts +4 -2
  66. package/src/organization-name.ts +35 -0
  67. package/src/organization-permissions.ts +10 -0
  68. package/src/organizations.ts +72 -3
  69. package/src/policies.ts +22 -6
  70. package/src/public-projection.ts +108 -0
  71. package/src/public-schema.ts +5 -43
  72. package/src/query/input-schema.ts +89 -0
  73. package/src/query/limits.ts +1 -1
  74. package/src/query/schema.ts +11 -89
  75. package/src/record-action-routes.ts +87 -0
  76. package/src/record-actions-data.ts +17 -0
  77. package/src/record-actions.ts +61 -0
  78. package/src/record-read.ts +20 -0
  79. package/src/row-access.ts +11 -0
  80. package/src/row-invitations.ts +29 -0
  81. package/src/schema/README.md +323 -0
  82. package/src/schema/declaration.ts +5 -0
  83. package/src/schema/load.ts +423 -0
  84. package/src/schema/lock-format.ts +117 -0
  85. package/src/schema/physical-names.ts +30 -0
  86. package/src/schema/revision.ts +16 -0
  87. package/src/schema/source-location.ts +3 -0
  88. package/src/schema-compatibility.ts +2 -2
  89. package/src/schema.ts +171 -0
  90. package/src/types.ts +1 -1
  91. package/src/user-link-eligibility.ts +36 -0
  92. package/src/user-links.ts +27 -16
  93. package/src/worker-access-actions.ts +89 -0
  94. package/src/worker-access.ts +61 -0
  95. package/src/workflow-runtime.ts +109 -22
  96. package/src/bootstrap.ts +0 -23
@@ -0,0 +1,72 @@
1
+ import { readFile, writeFile } from 'node:fs/promises'
2
+ import { dirname, resolve } from 'node:path'
3
+ import { pathToFileURL } from 'node:url'
4
+ import { createHash } from 'node:crypto'
5
+ import { KernelRegistry } from '../kernel/registry'
6
+ import { loadConfig, type LoadConfigOptions } from '../schema/load'
7
+ import { generate } from './generate'
8
+
9
+ /** Diagnostics are separate from config-loader options so embedded callers own routing. */
10
+ export interface OpenApiDiagnosticSink {
11
+ info(message: string): void
12
+ error(message: string): void
13
+ }
14
+ const defaultDiagnostics: OpenApiDiagnosticSink = {
15
+ info: message => console.log(message),
16
+ error: message => console.error(message),
17
+ }
18
+
19
+ /** Instance-root artifact; checking never creates or rewrites files. */
20
+ export async function runOpenApiCli(args: readonly string[], loadOptions: LoadConfigOptions = {}, diagnostics: OpenApiDiagnosticSink = defaultDiagnostics): Promise<number> {
21
+ const usage = 'Usage: check:openapi [--config config.ts] [--root .] [--directory .] [--write | --live <origin>]'
22
+ const options = { config: 'config.ts', root: '.', directory: '', write: false, live: '' }
23
+ for (let i = 0; i < args.length; i++) {
24
+ const arg = args[i]
25
+ if (arg === '--write') options.write = true
26
+ else if (['--config', '--root', '--directory', '--live'].includes(arg) && args[i + 1] && !args[i + 1].startsWith('--')) options[arg.slice(2) as 'config' | 'root' | 'directory' | 'live'] = args[++i]
27
+ else throw new Error(usage)
28
+ }
29
+ if (options.live && options.write) throw new Error(usage)
30
+ if (options.live) {
31
+ const origin = new URL(options.live)
32
+ if (!['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash) throw new Error(usage)
33
+ }
34
+ const file = resolve(options.root, options.config)
35
+ const { config, configHash } = await loadConfig(file, loadOptions)
36
+ // Compose the loaded schema, including SDK-registered account commands.
37
+ const kernel = new KernelRegistry(config)
38
+ const bytes = generate(kernel.config, kernel, configHash)
39
+ const target = options.directory ? resolve(options.root, options.directory, 'openapi.json') : resolve(dirname(file), 'openapi.json')
40
+ if (options.write) {
41
+ await writeFile(target, bytes)
42
+ diagnostics.info('openapi:write: regenerated openapi.json')
43
+ return 0
44
+ }
45
+ let previous: Buffer | undefined
46
+ try { previous = await readFile(target) }
47
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error }
48
+ if (!previous?.equals(Buffer.from(bytes))) {
49
+ diagnostics.error(`check:openapi: ${previous === undefined ? 'missing' : 'stale'} openapi.json; run bun run openapi:write`)
50
+ return 1
51
+ }
52
+ if (options.live) {
53
+ try {
54
+ const [spec, build] = await Promise.all(['/openapi.json', '/build.json'].map(path => fetch(new URL(path, options.live), { cache: 'no-store', redirect: 'error', signal: AbortSignal.timeout(10000) })))
55
+ if (!spec.ok || !build.ok) throw new Error('metadata unavailable')
56
+ const hash = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex')
57
+ const served = hash(new Uint8Array(await spec.arrayBuffer()))
58
+ const metadata = await build.json() as { openapi?: unknown }
59
+ if (served !== hash(previous) || served !== metadata.openapi) throw new Error('hash mismatch')
60
+ diagnostics.info('check:openapi: live bytes, build.json.openapi and committed file hashes match')
61
+ } catch {
62
+ diagnostics.error('check:openapi: live OpenAPI verification failed (served bytes, build.json.openapi and committed file must match)')
63
+ return 1
64
+ }
65
+ }
66
+ diagnostics.info('check:openapi: openapi.json matches configuration and registered operations')
67
+ return 0
68
+ }
69
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
70
+ try { process.exitCode = await runOpenApiCli(process.argv.slice(2)) }
71
+ catch (error) { defaultDiagnostics.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1 }
72
+ }
@@ -0,0 +1,166 @@
1
+ import type { z } from 'zod'
2
+ import { isAccountAccessCommand } from '../account-command'
3
+ import { canonical } from '../access-lock'
4
+ import { baseFields, bodyValidator } from '../model-inputs'
5
+ import type { Field, InstanceConfig } from '../config'
6
+ import type { KernelRegistry } from '../kernel/registry'
7
+ import { publicCommandDefinitions, publicFields, publicPolicies, publicQuery } from '../public-projection'
8
+ import { labelDependencies } from '../query/labels'
9
+ import { querySchema } from '../query/input-schema'
10
+ import { publicInputSchema } from './input-projection'
11
+ import { publicPaths, object, array, ref, string, boolean, nullable, response, request, parameter, operation, type Schema } from './public-paths'
12
+
13
+ const sorted = (values: readonly string[]) => [...new Set(values)].sort()
14
+ const compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
15
+ function scalar(field: Pick<Field, 'type' | 'values'>): Schema {
16
+ return field.type === 'bool' ? boolean : field.type === 'int' ? { type: 'integer' }
17
+ : field.type === 'float' ? { type: 'number' } : field.type === 'enum' ? { type: 'string', enum: field.values } : string
18
+ }
19
+ /** Rebase Zod's local recursive references when embedding a schema in components. */
20
+ function rebaseInput(input: Schema, name: string): Schema {
21
+ function rebase(node: any): any {
22
+ if (Array.isArray(node)) return node.map(rebase)
23
+ if (!node || typeof node !== 'object') return node
24
+ return Object.fromEntries(Object.entries(node).map(([key, value]) => [key,
25
+ key === '$ref' && typeof value === 'string' && value.startsWith('#') ? `#/components/schemas/${name}${value.slice(1)}`
26
+ : ['required', 'type'].includes(key) && Array.isArray(value) ? sorted(value) : rebase(value)]))
27
+ }
28
+ return rebase(input)
29
+ }
30
+ function permission(value: any): Schema {
31
+ return 'system' in value ? { system: value.system } : { entity: value.entity, operation: value.operation }
32
+ }
33
+
34
+ /** Build-time only, with no actor, environment, database, filesystem or clock input. */
35
+ export function generate(config: InstanceConfig, kernel: Pick<KernelRegistry, 'commands' | 'workflows'>, configHash: string): string {
36
+ const schemas: Record<string, Schema> = Object.create(null)
37
+ const insert = (name: string, schema: Schema) => {
38
+ if (Object.hasOwn(schemas, name)) throw new Error(`OpenAPI component collision: ${name}`)
39
+ schemas[name] = schema
40
+ return schema
41
+ }
42
+ for (const [name, schema] of Object.entries(publicPaths.schemas)) insert(name, schema)
43
+ const inputs = new WeakMap<z.ZodType, Schema>()
44
+ const inputSchema = (schema: z.ZodType, name: string) => {
45
+ let input = inputs.get(schema)
46
+ if (!input) { input = publicInputSchema(schema); inputs.set(schema, input) }
47
+ return rebaseInput(input, name)
48
+ }
49
+ const paths = publicPaths()
50
+ const commands = publicCommandDefinitions(config, kernel).map(({ name, command }) => {
51
+ const component = `CommandInput_${name.replaceAll('/', '_')}`
52
+ const input = insert(component, inputSchema(command.input, component))
53
+ return { name, permission: permission(command.permission), additionalPermissions: (command.additionalPermissions ?? []).map(permission).sort((a, b) => compare(JSON.stringify(canonical(a)), JSON.stringify(canonical(b)))), inputSchema: input }
54
+ }).sort((a, b) => compare(a.name, b.name))
55
+ const queryRequests: Schema[] = [], queryResponses: Schema[] = []
56
+ for (const name of Object.keys(config.entities).sort()) {
57
+ const entity = config.entities[name]
58
+ const actions = (config.effectiveAccess?.actions ?? []).filter(action => action.entity === name)
59
+ const fields = publicFields(entity)
60
+ const properties: Record<string, Schema> = Object.fromEntries(baseFields.map(field => [field, field === 'version' ? { type: 'integer' } : string]))
61
+ for (const [key, field] of Object.entries(entity.fields)) properties[key] = {
62
+ // Responses allow omitted fields (masks/select) and null references (visibility).
63
+ ...(field.required && field.type !== 'ref' ? scalar(field) : nullable(scalar(field))),
64
+ 'x-workbase-field': fields[key],
65
+ }
66
+ for (const [key, relation] of Object.entries(entity.relations)) properties[key] = relation.many ? array(ref(`Row_${relation.entity}`)) : nullable(ref(`Row_${relation.entity}`))
67
+ properties.__labels = { type: 'object', additionalProperties: nullable({ oneOf: [
68
+ object({ status: { type: 'string', enum: ['unavailable'] } }),
69
+ object({ status: { type: 'string', enum: ['ok'] }, entity: string, display: nullable(string), row: { type: 'object' } }),
70
+ ] }) }
71
+ properties.__display = array({ anyOf: [string, object({ type: { type: 'string', enum: ['date', 'datetime'] }, value: nullable(string) })] })
72
+ insert(`Row_${name}`, { ...object(properties, []),
73
+ 'x-workbase-display': { ...(entity.displayField ? { displayField: entity.displayField } : {}), ...(entity.label ? { labelDependencies: labelDependencies(config, name).sort((a, b) => compare(`${a.entity}.${a.field}`, `${b.entity}.${b.field}`)) } : {}) },
74
+ 'x-workbase-relations': Object.fromEntries(Object.entries(entity.relations).map(([key, relation]) => [key, {
75
+ entity: relation.entity, field: relation.field, cardinality: relation.many ? '1:n' : 'n:1',
76
+ ...(relation.through ? { through: { entity: relation.through.entity, field: relation.through.field, createCommand: relation.through.createCommand, deleteCommand: relation.through.deleteCommand } } : {}),
77
+ }])),
78
+ })
79
+ insert(`Detail_${name}`, object({ ...properties,
80
+ actions: object(Object.fromEntries(actions.map(action => [action.name, object({ enabled: boolean, reason: string }, ['enabled'])])), []),
81
+ ...(config.effectiveAccess?.accountLinks?.[name] ? { access: ref('AccountAccess') } : {}),
82
+ }, config.baseline === 'workbase-sdk' ? ['actions'] : []))
83
+ const writable = Object.entries(entity.fields).filter(([, field]) => !field.readOnly && !field.userLink && !field.computed).map(([key]) => key).sort()
84
+ insert(`Create_${name}`, inputSchema(bodyValidator(entity), `Create_${name}`))
85
+ insert(`Update_${name}`, { ...inputSchema(bodyValidator(entity, true), `Update_${name}`),
86
+ anyOf: writable.length ? writable.map(key => ({ required: [key] })) : [{ not: {} }],
87
+ })
88
+ schemas[`Update_${name}`].properties.version = { type: 'integer', minimum: 1 }
89
+ const queryName = `Query_${name}`
90
+ insert(queryName, inputSchema(querySchema(config, name), queryName))
91
+ schemas[queryName].properties.entity = { type: 'string', enum: [name] }
92
+ schemas[queryName].properties.cursor.description = 'Opaque signed query cursor; bound to the query and authorization scope.'
93
+ // querySchema emits only generated grammar/projection enums, never authored
94
+ // field values. Normalize every set here; other input/row enums keep their order.
95
+ const setEnums = (node: any) => {
96
+ if (!node || typeof node !== 'object') return
97
+ if (Array.isArray(node.enum)) node.enum = sorted(node.enum)
98
+ if (Array.isArray(node.required)) node.required = sorted(node.required)
99
+ for (const child of Object.values(node)) setEnums(child)
100
+ }
101
+ setEnums(schemas[queryName])
102
+ queryRequests.push(ref(queryName))
103
+ const page = (cursor: string) => object({ data: array(ref(`Row_${name}`)), next_cursor: { type: ['string', 'null'], description: cursor } })
104
+ insert(`List_${name}`, page('REST cursor: last returned row id, or null. Pass as the cursor URL parameter; rows sort by id.'))
105
+ insert(`Result_${name}`, page('Opaque signed query cursor, or null. Pass unchanged to POST /query; it is not a row id.'))
106
+ queryResponses.push(ref(`Result_${name}`))
107
+ const base = `/api/${name}`
108
+ const expand = parameter('expand', 'query', { type: 'string', description: 'Comma-separated relation names, at most five.' })
109
+ paths[base] = {
110
+ get: operation({ '200': response(ref(`List_${name}`)) }, { parameters: [parameter('limit', 'query', { type: 'integer', minimum: 1, maximum: 90, description: 'Page size; omitted means 25.' }),
111
+ parameter('cursor', 'query', { type: 'string', description: 'Last returned row id (REST cursor).' }), expand,
112
+ ...Object.entries(entity.fields).sort(([a], [b]) => compare(a, b)).flatMap(([key, field]) => ['', '[gt]', '[gte]', '[lt]', '[lte]'].map(op => parameter(key + op, 'query', field.type === 'bool' ? { type: 'string', enum: ['true', 'false', '1', '0'] } : ['int', 'float'].includes(field.type) ? { type: 'number' } : string))),
113
+ ] }),
114
+ ...(!entity.commandsOnly ? { post: operation({ '201': response(ref(`Row_${name}`)) }, { parameters: [parameter('Idempotency-Key', 'header', { type: 'string', minLength: 1, maxLength: 128 })], requestBody: request(ref(`Create_${name}`)) }) } : {}),
115
+ }
116
+ paths[`${base}/{id}`] = {
117
+ parameters: [parameter('id', 'path', string, true)],
118
+ get: operation({ '200': response(ref(`Detail_${name}`)) }, { parameters: [expand] }),
119
+ ...(!entity.commandsOnly ? {
120
+ patch: operation({ '200': response(ref(`Row_${name}`)), '409': response(ref('Error'), 'Version conflict') }, {
121
+ parameters: [parameter('If-Match', 'header', { type: 'string', description: 'Expected positive row version, optionally quoted. Required unless body.version is supplied.' })], requestBody: request(ref(`Update_${name}`)),
122
+ }), delete: operation({ '204': { description: 'Deleted' } }),
123
+ } : {}),
124
+ }
125
+ for (const action of actions) {
126
+ const command = kernel.commands.get(action.command)
127
+ if (!command) throw new Error(`Missing action command: ${action.command}`)
128
+ const component = `Action_${name.length}_${name}_${action.name.length}_${action.name}`
129
+ const input = inputSchema(command.input, component)
130
+ for (const key of ['id', 'rowId', 'role']) { delete input.properties?.[key]; input.required = input.required?.filter((value: string) => value !== key) }
131
+ insert(component, input)
132
+ const accountAction = isAccountAccessCommand(config, action.command)
133
+ const result = accountAction ? action.name === 'invite' ? object({ invitation_id: string, expires_at: string, accept_url: string }) : object({ id: string }) : {}
134
+ paths[`${base}/{id}/actions/${action.name}`] = { parameters: [parameter('id', 'path', string, true)], post: operation({
135
+ ...(accountAction ? { [action.name === 'invite' ? '201' : '200']: response(result) } : { '2XX': response(result, 'Command result') }),
136
+ '409': response({ anyOf: [object({ error: { type: 'string', enum: ['action_unavailable'] }, reason: string }), ref('Error')] }, 'Unavailable action includes reason; command conflicts use Error'),
137
+ }, { requestBody: request(ref(component)) }) }
138
+ }
139
+ }
140
+ paths['/query'] = { post: operation({ '200': response({ anyOf: queryResponses }) }, { requestBody: request({ oneOf: queryRequests }), description: 'Filter-object query. Cursors are opaque signed tokens, distinct from REST last-id cursors.' }) }
141
+ for (const command of commands) {
142
+ const component = `Command_${command.name.replaceAll('/', '_')}`
143
+ // Names may contain slashes and underscores; fail rather than silently alias components.
144
+ insert(component, structuredClone(command.inputSchema))
145
+ if (schemas[component].type === 'object') schemas[component].properties.idempotencyKey = { type: 'string', minLength: 1, maxLength: 128 }
146
+ paths[`/commands/${command.name}`] = { post: operation({ '200': response({}, 'Command result'), '201': response({}, 'Command result'), '405': response(ref('Error'), 'Unsupported command (including record-only adapters)') }, { requestBody: request(ref(component)) }) }
147
+ }
148
+ const workflows = [...kernel.workflows.values()].map(workflow => {
149
+ const component = `WorkflowInput_${workflow.name.replaceAll('/', '_')}`
150
+ const input = insert(component, inputSchema(workflow.input, component))
151
+ return { name: workflow.name, version: workflow.version, inputSchema: input,
152
+ permissions: workflow.steps?.map(step => ({ name: step.operation.name, permission: permission(step.operation.permission) })).sort((a, b) => compare(a.name, b.name)),
153
+ }
154
+ }).sort((a, b) => compare(a.name, b.name))
155
+ const doc = {
156
+ openapi: '3.1.0', info: { title: config.id, version: `r${config.revision}` }, paths,
157
+ components: { schemas, securitySchemes: { session: { type: 'apiKey', in: 'cookie', name: '__Host-workbase.session' }, bearer: { type: 'http', scheme: 'bearer' } } },
158
+ 'x-workbase-revision': config.revision, 'x-workbase-config-hash': configHash,
159
+ 'x-workbase-permissions': { roles: sorted(config.roles), resources: Object.fromEntries(Object.entries(config.permissions).map(([role, resources]) => [role, Object.fromEntries(Object.entries(resources).map(([name, operations]) => [name, sorted(operations)]))])), entities: publicPolicies(config) },
160
+ 'x-workbase-query': publicQuery(config), 'x-workbase-commands': commands,
161
+ 'x-workbase-workflows': workflows,
162
+ }
163
+ const bytes = JSON.stringify(canonical(doc), null, 2) + '\n'
164
+ if (JSON.stringify(canonical(JSON.parse(bytes)), null, 2) + '\n' !== bytes) throw new Error('OpenAPI canonical round-trip failed')
165
+ return bytes
166
+ }
@@ -0,0 +1,131 @@
1
+ import { z } from 'zod'
2
+ import type { Schema } from './public-paths'
3
+
4
+ type ZodSchema = z.core.$ZodType
5
+ // Only JSON Schema vocabulary used by the public projection is eligible for disclosure.
6
+ // Schema-map keys (including user fields named "default") are data, not vocabulary.
7
+ const structural = new Set(['$ref', '$defs', 'type', 'properties', 'required', 'items', 'prefixItems', 'additionalProperties', 'anyOf', 'oneOf', 'allOf', 'not'])
8
+ const constraints = new Set(['enum', 'format', 'pattern', 'patternProperties', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', 'minLength', 'maxLength', 'minItems', 'maxItems', 'uniqueItems', 'minProperties', 'maxProperties', 'propertyNames', 'contains', 'minContains', 'maxContains', 'dependentRequired', 'dependentSchemas'])
9
+ const annotations = ['title', 'description', 'sensitive', 'readOnly', 'referenceEntity'] as const
10
+
11
+ /** Follow exactly the output-facing wrapper chain used by /schema, without parsing
12
+ * values or reading defaultValue getters. Pipelines' input annotations are private. */
13
+ function outputChain(schema: ZodSchema): ZodSchema[] {
14
+ const chain: ZodSchema[] = [], seen = new Set<ZodSchema>()
15
+ while (!seen.has(schema)) {
16
+ seen.add(schema)
17
+ chain.push(schema)
18
+ const def = schema._zod.def as any
19
+ const next = def.type === 'pipe' ? def.out : def.innerType ?? (def.type === 'lazy' ? (schema as z.core.$ZodLazy)._zod.innerType : undefined)
20
+ if (!next) break
21
+ schema = next
22
+ }
23
+ return chain
24
+ }
25
+ function sensitivity(schema: ZodSchema, seen = new Set<ZodSchema>()): boolean {
26
+ if (seen.has(schema)) return false
27
+ seen.add(schema)
28
+ if (z.globalRegistry.get(schema)?.sensitive === true) return true
29
+ const def = schema._zod.def as any
30
+ return def.type === 'pipe' ? sensitivity(def.in, seen) || sensitivity(def.out, seen)
31
+ : def.innerType ? sensitivity(def.innerType, seen) : def.type === 'lazy' ? sensitivity((schema as z.core.$ZodLazy)._zod.innerType!, seen) : false
32
+ }
33
+
34
+ /** Build a default-free graph before Zod can evaluate default/prefault/catch
35
+ * factories. Input syntax is retained; pipeline-only values and annotations are
36
+ * omitted, and object keys must also exist on the public output side. This may
37
+ * deliberately widen a pipeline's scalar constraints rather than disclose them.
38
+ * /schema uses the same disclosure rules with output conversion as its primary view. */
39
+ export function publicInputSchema(input: z.ZodType): Schema {
40
+ const result = publicProjection(input, 'input')
41
+ delete result.$schema
42
+ return result
43
+ }
44
+
45
+ /** Preserve output semantics, visiting input syntax only at an output transform. */
46
+ export function publicOutputSchema(input: z.ZodType): Schema {
47
+ return publicProjection(input, 'output')
48
+ }
49
+
50
+ type Mode = 'input' | 'output'
51
+ function publicProjection(input: z.ZodType, io: Mode): Schema {
52
+ const metadata = z.registry<Record<string, any>>()
53
+ const contexts = new WeakMap<ZodSchema, { boundary: ZodSchema; sensitive: boolean; restricted: boolean; mode: Mode; schema: ZodSchema }[]>()
54
+ const restrictedSchemas = new WeakSet<ZodSchema>()
55
+ const undisclosed = z.unknown()
56
+ function project(source: ZodSchema, boundary = source, inherited = false, restricted = false, mode = io): ZodSchema {
57
+ const sensitive = inherited || sensitivity(source) || sensitivity(boundary)
58
+ const cached = contexts.get(source)?.find(entry => entry.boundary === boundary && entry.sensitive === sensitive && entry.restricted === restricted && entry.mode === mode)
59
+ if (cached) return cached.schema
60
+ const def = source._zod.def as any
61
+ const chain = outputChain(boundary), publicNode = chain.at(-1)!, publicDef = publicNode._zod.def as any
62
+ // Copy descriptors so a ZodDefault's defaultValue accessor is never read.
63
+ const descriptors = Object.getOwnPropertyDescriptors(def)
64
+ const copy: any = {}
65
+ for (const [key, descriptor] of Object.entries(descriptors)) {
66
+ if (['defaultValue', 'catchValue', 'shape', 'getter', '_cachedInner'].includes(key)) continue
67
+ Object.defineProperty(copy, key, descriptor)
68
+ }
69
+ if (def.type === 'default' || def.type === 'prefault') copy.defaultValue = null
70
+ if (def.type === 'catch') copy.catchValue = () => undefined
71
+ // Resolve structural getters lazily, after the clone is memoized (recursive objects).
72
+ if (def.type === 'object') Object.defineProperty(copy, 'shape', { get: () => Object.fromEntries(Object.entries(def.shape).flatMap(([key, child]) => {
73
+ const output = publicDef.type === 'object' ? publicDef.shape[key] : undefined
74
+ return restricted && !output ? [] : [[key, project(child as ZodSchema, output ?? child as ZodSchema, sensitive, restricted, mode)]]
75
+ })), enumerable: true })
76
+ if (def.type === 'lazy') copy.getter = () => project((source as z.core.$ZodLazy)._zod.innerType!, publicNode, sensitive, restricted, mode)
77
+ let schema: ZodSchema
78
+ // Broadening private enum/literal values also prevents record/union processors
79
+ // from deriving public key inventories from the private _zod.values set.
80
+ if (restricted && ['enum', 'literal'].includes(def.type)) {
81
+ const values = def.type === 'enum' ? Object.values(def.entries) : def.values
82
+ const types = [...new Set(values.map((value: unknown) => value === null ? 'null' : typeof value))]
83
+ const primitives: Record<string, z.ZodType> = { string: z.string(), number: z.number(), boolean: z.boolean(), null: z.null() }
84
+ schema = types.length === 1 ? primitives[types[0] as string] ?? z.unknown() : z.unknown()
85
+ } else schema = z.core.clone(source, copy)
86
+ const entries = contexts.get(source) ?? []
87
+ entries.push({ boundary, sensitive, restricted, mode, schema })
88
+ contexts.set(source, entries)
89
+ if (restricted) restrictedSchemas.add(schema)
90
+ const meta: Record<string, any> = {}
91
+ for (const node of [...chain].reverse()) {
92
+ const published = z.globalRegistry.get(node)
93
+ for (const key of annotations) if (published?.[key] !== undefined && !(sensitive && key === 'description')) meta[key] = published[key]
94
+ }
95
+ metadata.add(schema, meta)
96
+ // The constructor retains `copy` by reference. Replace child schemas only
97
+ // after memoization; lazy getters above close over this same projection.
98
+ const child = (value: ZodSchema, output?: ZodSchema) => project(value, output ?? (restricted ? undisclosed : value), sensitive, restricted, mode)
99
+ if (def.type === 'pipe' && mode === 'output') {
100
+ copy.in = undisclosed // Never convert a representable output pipeline's input.
101
+ if (def.out._zod.def.type === 'transform') {
102
+ const fallback = project(source, boundary, sensitive, restricted, 'input')
103
+ // Use Zod's shared conversion context so recursive/reused schemas retain
104
+ // document-local refs. The fallback graph is already disclosure-filtered.
105
+ schema._zod.processJSONSchema = (ctx, _json, params) => {
106
+ z.core.processSchema(fallback, { ...ctx, io: 'input' }, params)
107
+ ctx.seen.get(schema)!.ref = fallback
108
+ }
109
+ copy.out = undisclosed
110
+ } else copy.out = project(def.out, boundary, sensitive, restricted, mode)
111
+ } else if (def.type === 'pipe') {
112
+ const input = def.in._zod.def.type === 'transform' ? def.out : def.in
113
+ copy.in = project(input, boundary, sensitive, true, mode)
114
+ copy.out = z.unknown() // io:input never visits the executable output transform.
115
+ } else {
116
+ for (const key of ['innerType', 'element', 'keyType', 'valueType', 'left', 'right', 'rest', 'catchall']) if (def[key]) copy[key] = child(def[key], publicDef[key])
117
+ for (const key of ['options', 'items']) if (Array.isArray(def[key])) copy[key] = def[key].map((value: ZodSchema, index: number) => child(value, publicDef[key]?.[index]))
118
+ }
119
+ return schema
120
+ }
121
+ return z.toJSONSchema(project(input), { io, metadata, override({ zodSchema, jsonSchema }) {
122
+ const restricted = restrictedSchemas.has(zodSchema)
123
+ for (const key of Object.keys(jsonSchema)) if (!structural.has(key) && !annotations.includes(key as any) && !(constraints.has(key) && !restricted)) delete (jsonSchema as any)[key]
124
+ if (restricted) {
125
+ // Broadening must stay a widening: omitted private keys may still be required at
126
+ // runtime, and broadened branches can overlap, so neither closure nor exclusivity holds.
127
+ if ((jsonSchema as any).additionalProperties === false) delete (jsonSchema as any).additionalProperties
128
+ if (Array.isArray((jsonSchema as any).oneOf)) { (jsonSchema as any).anyOf = (jsonSchema as any).oneOf; delete (jsonSchema as any).oneOf }
129
+ }
130
+ } }) as Schema
131
+ }
@@ -0,0 +1,80 @@
1
+ /** Curated public HTTP contracts. No runtime handler imports or configuration spreads. */
2
+ export type Schema = Record<string, any>
3
+ export const string = { type: 'string' }
4
+ export const boolean = { type: 'boolean' }
5
+ export const array = (items: Schema): Schema => ({ type: 'array', items })
6
+ export const nullable = (schema: Schema): Schema => ({ anyOf: [schema, { type: 'null' }] })
7
+ export const ref = (name: string): Schema => ({ $ref: `#/components/schemas/${name}` })
8
+ export const object = (properties: Record<string, Schema>, required = Object.keys(properties)): Schema => ({ type: 'object', properties, required: [...required].sort(), additionalProperties: false })
9
+ export const response = (schema: Schema, description = 'Success'): Schema => ({ description, content: { 'application/json': { schema } } })
10
+ export const request = (schema: Schema): Schema => ({ required: true, content: { 'application/json': { schema } } })
11
+ export const parameter = (name: string, location: string, schema: Schema, required = false): Schema => ({ name, in: location, required, schema })
12
+ export const operation = (responses: Schema, extra: Schema = {}): Schema => ({ security: [{ session: [] }, { bearer: [] }], responses: { default: response(ref('Error'), 'API error'), ...responses }, ...extra })
13
+ const map = (schema: Schema): Schema => ({ type: 'object', additionalProperties: schema })
14
+ const strings = array(string)
15
+ const account = object({ id: string, display_name: string, email: string })
16
+ const invitation = object({ id: string, email: string, expires_at: string })
17
+ const org = object({ id: string, name: nullable(string) })
18
+ const target = object({ entity: string, row: nullable(string) })
19
+ const metadata = { id: string, organization: org, inviter: object({ display_name: string }), role: string, expires_at: string, target,
20
+ state: { type: 'string', enum: ['pending', 'expired', 'accepted', 'declined', 'revoked'] }, account_match: { type: 'boolean', enum: [true] } }
21
+ const publicEntry = object({ id: string, account_match: { enum: [false, null] } })
22
+ const metadataRequired = Object.keys(metadata).filter(key => key !== 'target')
23
+ const preflight = { oneOf: [publicEntry, object({ ...metadata, account_match: { enum: [true, null] } }, metadataRequired)] }
24
+ const preview = object({ ...metadata, navigation_target: string, return_to: string, profile_complete: boolean, next: { type: 'string', enum: ['terminal', 'preview', 'profile'] }, actions: strings }, [...metadataRequired, 'navigation_target', 'return_to', 'profile_complete', 'next', 'actions'])
25
+ const profile = object({ id: string, email: string, firstName: nullable(string), lastName: nullable(string), displayName: nullable(string),
26
+ authority: object({ kind: { type: 'string', enum: ['local', 'idp'] }, provider: nullable(string), synchronization: nullable(object({ method: string, maxLatencySeconds: { type: 'integer', minimum: 0 } })) }),
27
+ capabilities: object({ canEditNames: boolean, canEditEmail: { type: 'boolean', enum: [false] } }),
28
+ completeness: object({ complete: boolean, missingFields: array({ type: 'string', enum: ['firstName', 'lastName'] }) }), syncedAt: nullable(string),
29
+ })
30
+ const member = object({ user_id: string, email: string, role: string, display_name: string })
31
+ const linkCandidate = object({ ...member.properties, linkable: boolean, link_reason: { type: 'string', enum: ['account_already_linked', 'account_not_linkable'] } }, [...Object.keys(member.properties), 'linkable'])
32
+ const memberPending = object({ ...member.properties, display_name: string, last_administrator: boolean, kind: { type: 'string', enum: ['member'] }, status: { type: 'string', enum: ['active'] }, actions: strings })
33
+ const invited = object({ target_entity: nullable(string), target_row: nullable(string), id: string, email: string, role: string, expires_at: string, created_at: nullable(string), inviter: object({ display_name: string }), kind: { type: 'string', enum: ['invitation'] }, status: { type: 'string', enum: ['pending'] }, actions: strings })
34
+ const revision = object({ revision: { type: 'integer' }, coreVersion: string, migrations: string, pluginMigrations: string }, ['revision', 'coreVersion', 'migrations'])
35
+ const health = object({ instance: string, revision: { type: 'integer' }, core_version: string, schema: object({ enabled: boolean, compatible: boolean, expected: nullable(revision), applied: nullable(revision) }) })
36
+ const tokenBody = object({ token: string, return_to: string }, ['token'])
37
+ const returnBody = object({ return_to: string }, [])
38
+ const me = object({ organizationsEnabled: boolean, organizationCreationAllowed: boolean,
39
+ user: nullable(object({ id: string, email: string, name: string }, ['id', 'email'])),
40
+ actor: object({ type: { type: 'string', enum: ['user', 'agent', 'service'] }, id: string, tokenId: string }, ['type', 'id']),
41
+ memberships: array(object({ organization_id: string, name: string, role: string })),
42
+ organization_id: string, role: string, operations: strings,
43
+ }, ['organizationsEnabled', 'organizationCreationAllowed', 'user', 'actor', 'memberships'])
44
+
45
+ export function publicPaths(): Record<string, Schema> {
46
+ return {
47
+ '/me': { get: operation({ '200': response(me) }, { parameters: [parameter('scope', 'query', { type: 'string', enum: ['organization'] }), parameter('X-Organization-Id', 'header', string)] }) },
48
+ '/o/{org}/capabilities': { parameters: [parameter('org', 'path', string, true)], get: operation({ '200': response(ref('Capabilities')) }) },
49
+ '/orgs/{orgId}/members': { parameters: [parameter('orgId', 'path', string, true)], get: operation({ '200': response({ oneOf: [object({ data: array({ oneOf: [member, linkCandidate] }) }), object({ data: array({ oneOf: [memberPending, invited] }), role_options: array(object({ id: string, administrator: boolean })), default_role: string }, ['data', 'role_options'])] }) }, { parameters: [parameter('include', 'query', { type: 'string', enum: ['pending'] }), parameter('q', 'query', { type: 'string', maxLength: 200, description: 'Optional literal name/email search for eligible=link_account; all whitespace-separated tokens must match (at most 20).' }), parameter('eligible', 'query', { type: 'string', enum: ['link_account'] }), parameter('target_entity', 'query', { type: 'string', pattern: '^[a-z][a-z0-9_]*$', description: 'Required for eligible=link_account; configured entity with a user link.' }), parameter('target_row', 'query', { type: 'string', minLength: 1, maxLength: 200, description: 'Required for eligible=link_account; visible, writable row in this organization.' })], description: 'Link eligibility requires an administrator with members.read, target_entity and target_row plus Link authority. Missing, malformed or inaccessible targets return 400 invalid_link_target. Without q, results exclude accounts linked to another row of that entity in this organization. With q, matching members include linkable and, when unavailable, link_reason; unavailable accounts cannot be linked.' }) },
50
+ '/me/invitations': { get: operation({ '200': response(object({ data: array(object({ ...metadata, navigation_target: string }, [...metadataRequired, 'navigation_target'])), next: string })) }, { parameters: [parameter('return_to', 'query', string)] }) },
51
+ '/orgs/{orgId}/invitations': { parameters: [parameter('orgId', 'path', string, true)], post: operation({
52
+ '200': response(object({ message: { type: 'string', enum: ['already_member'] } })),
53
+ '201': response(object({ ...invitation.properties, role: string, accept_url: string, delivery: object({ status: string, attempts: { type: 'integer' }, sent_at: nullable(string), error: nullable(string) }) })),
54
+ '409': response(object({ error: { type: 'string', enum: ['account_already_linked', 'invitation_pending', 'invitation_conflict'] } }), 'Invitation conflict'),
55
+ }, { requestBody: request(object({ email: { type: 'string', format: 'email' }, role: string, target: object({ entity: { type: 'string', pattern: '^[a-z][a-z0-9_]*$' }, row: { type: 'string', minLength: 1, maxLength: 200 } }), profile_prefill: object({ firstName: string, lastName: string }, []) }, ['email'])),
56
+ description: 'Creates an invitation. A row target derives its role from the configured entity. Returns 409 account_already_linked if the target is occupied or the known invitee is already linked to another row of the same entity in this organization. The uniqueness check is repeated atomically when inserting the invitation; unknown addresses and links to different entities or organizations are allowed.' }) },
57
+ '/invitations/preflight': { post: operation({ '200': response(preflight) }, { security: [], requestBody: request(object({ token: { type: 'string', pattern: '^[a-f0-9]{64}(?:\\.[a-f0-9]{0,64})?$' } })), description: 'Read-only preview. A matching verified session or an anonymous token with a server-verified mailbox proof receives full metadata, including terminal state. Copied selectors and invalid mailbox proofs receive only id and account_match, uniformly across states. A different signed-in account always receives the minimal response.' }) },
58
+ '/invitations/resolve': { post: operation({ '200': response(preview) }, { security: [], requestBody: request(tokenBody) }) },
59
+ '/invitations/{id}/preview': { parameters: [parameter('id', 'path', string, true)], get: operation({ '200': response(preview) }, { parameters: [parameter('return_to', 'query', string)] }) },
60
+ '/invitations/{id}/resolve': { parameters: [parameter('id', 'path', string, true)], post: operation({ '200': response(preview) }, { requestBody: request(returnBody) }) },
61
+ ...Object.fromEntries(['accept', 'decline'].map(action => [`/invitations/{id}/${action}`, { parameters: [parameter('id', 'path', string, true)], post: operation({
62
+ '200': response(object({ id: string, state: { type: 'string', enum: [action === 'accept' ? 'accepted' : 'declined'] }, replayed: boolean, organization_id: string, role: string, entry_target: string }, ['id', 'state', 'replayed'])),
63
+ ...(action === 'accept' ? { '201': response(object({ id: string, state: { type: 'string', enum: ['accepted'] }, replayed: boolean, organization_id: string, role: string, entry_target: string })) } : {}),
64
+ }, { requestBody: { ...request(returnBody), required: false } }) }])),
65
+ '/me/profile': { get: operation({ '200': response(profile) }), patch: operation({ '200': response(profile) }, { requestBody: request(object({ firstName: { type: 'string', minLength: 1, maxLength: 200 }, lastName: { type: 'string', minLength: 1, maxLength: 200 } })) }) },
66
+ '/auth/providers': { get: operation({ '200': response(object({ providers: array(object({ id: string })) })) }, { security: [] }) },
67
+ '/auth/logout': { post: operation({ '204': { description: 'Signed out' } }) },
68
+ '/auth/sign-in/magic-link': { post: operation({ '200': response({}, 'Opaque authentication-provider response'), default: response({}, 'Opaque authentication-provider response') }, { security: [], requestBody: request(object({ email: { type: 'string', format: 'email' }, callbackURL: string, name: string }, ['email'])) }) },
69
+ '/build.json': { get: operation({ '200': response(object({ sha: string, builtAt: string, revision: { type: 'integer' }, openapi: string })) }, { security: [] }) },
70
+ '/health': { get: operation({ '200': response(health), '503': response(health, 'Schema incompatible') }, { security: [] }) },
71
+ '/openapi.json': { get: operation({ '200': response({ type: 'object' }), '503': response(object({ error: { type: 'string', enum: ['openapi_not_bound'] } }), 'OpenAPI artifact is not bound') }, { security: [], description: 'Serves the committed public specification anonymously. Returns 503 when no valid OpenAPI artifact is bound.' }) },
72
+ }
73
+ }
74
+ publicPaths.schemas = {
75
+ Error: { type: 'object', properties: { error: string, hint: string, reason: string }, required: ['error'], additionalProperties: true },
76
+ AccountAccess: object({ state: { type: 'string', enum: ['no_account', 'invited', 'expired', 'linked'] }, account: nullable(account), invitation: nullable(invitation) }),
77
+ Capabilities: object({ revision: { type: 'integer' }, entities: map(object({ readable: strings, writable: strings, operations: array({ type: 'string', enum: ['read', 'create', 'update', 'delete'] }), displayField: string }, ['readable', 'writable', 'operations'])),
78
+ commands: strings, workflows: map(array({ type: 'string', enum: ['start', 'cancel', 'resume'] })), resources: map(boolean), organization: object({ role: string }),
79
+ }),
80
+ }
@@ -0,0 +1,29 @@
1
+ import { canonical } from '../canonical'
2
+ import type { InstanceConfig } from '../config'
3
+ import type { App } from '../types'
4
+
5
+ function validSpec(spec: unknown, revision: number): spec is Record<string, unknown> {
6
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) return false
7
+ const value = spec as Record<string, unknown>
8
+ const info = value.info as { version?: unknown } | undefined
9
+ return value.openapi === '3.1.0' && info?.version === `r${revision}`
10
+ && value['x-workbase-revision'] === revision
11
+ && typeof value['x-workbase-config-hash'] === 'string' && /^[a-f0-9]{64}$/.test(value['x-workbase-config-hash'])
12
+ && !!value.paths && typeof value.paths === 'object' && !Array.isArray(value.paths)
13
+ && !!value.components && typeof value.components === 'object' && !Array.isArray(value.components)
14
+ }
15
+
16
+ /** Generated public artifact, carried as data across module realms and bundles. */
17
+ export function bindOpenApi<T extends InstanceConfig>(config: T, spec: unknown): T {
18
+ if (config.baseline !== 'workbase-sdk' || !validSpec(spec, config.revision)) throw new Error('Invalid openapi.json binding')
19
+ config.openapi = JSON.parse(JSON.stringify(canonical(spec)))
20
+ return config
21
+ }
22
+
23
+ /** Public, independent of identity, database contents and ASSETS. */
24
+ export function openApiRoutes(app: App, config: InstanceConfig): void {
25
+ const bytes = config.baseline === 'workbase-sdk' && validSpec(config.openapi, config.revision) ? JSON.stringify(canonical(config.openapi), null, 2) + '\n' : undefined
26
+ app.get('/openapi.json', c => bytes === undefined
27
+ ? c.json({ error: 'openapi_not_bound' }, 503)
28
+ : c.body(bytes, 200, { 'Content-Type': 'application/json; charset=UTF-8', 'Cache-Control': 'no-store' }))
29
+ }
package/src/ops.ts CHANGED
@@ -15,8 +15,10 @@ export async function recordRelayRun(env: RuntimeEnv, metrics: Awaited<ReturnTyp
15
15
  }
16
16
  async function lastRelayRun(env: RuntimeEnv) {
17
17
  try {
18
- const row = await env.DB.prepare('SELECT ts,backlog,oldest_age_seconds AS oldestAgeSeconds,failed,delivered,webhook_delivered AS webhookDelivered,errors FROM _ops_relay_run WHERE id=1').first()
19
- return row
18
+ const row = await env.DB.prepare('SELECT ts,backlog,oldest_age_seconds AS oldestAgeSeconds,failed,delivered,webhook_delivered AS webhookDelivered,errors,operational_history FROM _ops_relay_run WHERE id=1').first()
19
+ if (!row) return null
20
+ const { operational_history, ...latest } = row
21
+ return { ...latest, history: JSON.parse(operational_history as string) }
20
22
  } catch { return null } // Local-only schema fixtures may omit the optional cron snapshot.
21
23
  }
22
24
  const tables = async (db: D1Database) => (await db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all<{ name: string }>()).results.map(row => row.name)
@@ -0,0 +1,35 @@
1
+ import { z } from 'zod'
2
+ import { ApiError } from './errors'
3
+
4
+ export const organizationNameReasons = ['required', 'not_string', 'empty', 'too_long', 'control_character', 'line_separator', 'hidden_character', 'nonstandard_space', 'invalid_character', 'url_not_allowed'] as const
5
+ export type OrganizationNameReason = typeof organizationNameReasons[number]
6
+ export type OrganizationNameResult = { ok: true; value: string } | { ok: false; reason: OrganizationNameReason }
7
+
8
+ /** #122: normalize first; length is measured in Unicode code points. */
9
+ export function validateOrganizationName(input: string): OrganizationNameResult {
10
+ // Only ordinary spaces may be trimmed; forbidden boundary characters must survive validation.
11
+ const value = input.replace(/^ +| +$/g, '').normalize('NFC')
12
+ if (!value) return { ok: false, reason: 'empty' }
13
+ if ([...value].length > 200) return { ok: false, reason: 'too_long' }
14
+ if (/\p{Cc}/u.test(value)) return { ok: false, reason: 'control_character' }
15
+ if (/[\p{Zl}\p{Zp}]/u.test(value)) return { ok: false, reason: 'line_separator' }
16
+ if (/\p{Cf}/u.test(value)) return { ok: false, reason: 'hidden_character' }
17
+ if ([...value].some(char => char !== ' ' && /\p{Zs}/u.test(char))) return { ok: false, reason: 'nonstandard_space' }
18
+ if (/[\p{Cn}\p{Co}\p{Cs}]/u.test(value)) return { ok: false, reason: 'invalid_character' }
19
+ if (/[a-z][a-z0-9+.-]*:\/\//i.test(value)) return { ok: false, reason: 'url_not_allowed' }
20
+ return { ok: true, value }
21
+ }
22
+
23
+ export const organizationNameSchema = z.string({ error: issue => issue.input === undefined ? 'required' : 'not_string' }).transform((input, ctx) => {
24
+ const result = validateOrganizationName(input)
25
+ if (result.ok) return result.value
26
+ ctx.addIssue({ code: 'custom', message: result.reason, params: { reason: result.reason } })
27
+ return z.NEVER
28
+ })
29
+
30
+ /** HTTP inputs and core write guards share the same field-level ApiError. */
31
+ export const organizationNameApiSchema = organizationNameSchema.catch(ctx => {
32
+ const reason = ctx.error.issues[0]?.message
33
+ throw new ApiError(400, 'invalid_organization_name', undefined, { field: 'name', reason })
34
+ })
35
+ export const requireOrganizationName = (input: string): string => organizationNameApiSchema.parse(input)
@@ -1,3 +1,4 @@
1
+ import { effectiveAuthority, effectiveSystemGrant } from './access-evaluator'
1
2
  import { rbacRoles, hasActorProjection } from './policies'
2
3
  import type { InstanceConfig, OrganizationAction } from './config'
3
4
  import type { Scope } from './types'
@@ -13,6 +14,10 @@ export function roleNamePrivileges(role: string): ReadonlySet<string> {
13
14
  */
14
15
  export function effectiveRolePrivileges(config: InstanceConfig, role: string): ReadonlySet<string> {
15
16
  if (!config.roles.includes(role)) return new Set()
17
+ if (config.effectiveAccess) return new Set([
18
+ ...config.effectiveAccess.system.filter(rule => rule.role === role && effectiveSystemGrant(config.effectiveAccess!, [role], rule.action)).map(rule => `system:${rule.action}`),
19
+ ...config.effectiveAccess.entities.filter(rule => rule.role === role && rule.decision === 'allow').map(rule => `entity:${rule.entity}:${rule.operation}`),
20
+ ])
16
21
  const privileges = new Set([
17
22
  ...roleNamePrivileges(role), ...(config.organizationPermissions[role] ?? []),
18
23
  // These resource operations are available to every configured membership role.
@@ -33,6 +38,11 @@ export function canGrantRole(config: InstanceConfig, actorRole: string, targetRo
33
38
  return [...effectiveRolePrivileges(config, targetRole)].every(privilege => issuer.has(privilege))
34
39
  }
35
40
  export function organizationPermission(config: InstanceConfig, scope: Scope, action: OrganizationAction) {
41
+ if (config.effectiveAccess) {
42
+ if (scope.actor.type !== 'user' && !(scope.actor.type === 'agent' && hasActorProjection(scope))) throw new ApiError(403, 'user_required')
43
+ if (!effectiveAuthority(config.effectiveAccess, scope).permits({ system: action })) throw new ApiError(403, 'permission_denied')
44
+ return
45
+ }
36
46
  if (scope.actor.type !== 'user' && !(scope.actor.type === 'agent' && ['invitations.create', 'invitations.read', 'invitations.revoke'].includes(action))) throw new ApiError(403, 'user_required')
37
47
  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')
38
48
  if ((action === 'members.read' || action === 'invitations.read') && config.roles.includes(scope.role)) return