@fabrika/db 0.9.0-dev.19 → 0.9.0-dev.20

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/src/store.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  type AccessRelation,
7
7
  activeRow,
8
8
  conditioned,
9
+ conditionedAny,
9
10
  everyPath,
10
11
  gateTerms,
11
12
  heldThrough,
@@ -138,16 +139,20 @@ import {
138
139
  type PathWriter,
139
140
  pathWriters,
140
141
  type PolicyRow,
142
+ type ReadReach,
141
143
  type RevealModel,
142
144
  type SecondaryPath,
143
145
  type TableModel,
144
146
  type TableModels,
145
147
  tableModels,
146
148
  type Tables,
149
+ updatableBy,
150
+ updatableByAny,
147
151
  updateActions,
148
152
  type UpdateValues,
149
153
  type VersionArguments,
150
154
  visibleFor,
155
+ visibleThrough,
151
156
  } from './policy'
152
157
  import { frameworkSideOf, type ProvisionalBinding, register } from './registry'
153
158
  import type { ScopeTerms, ScopeTest, ScopeUse } from './sql'
@@ -833,7 +838,8 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
833
838
  throw new CapabilityError('table_kind', `a scoped site writes no application table: ${statement} needs the capability of an app endpoint`)
834
839
  }
835
840
  const actions = model.actions[use]
836
- if (includes(actions, grant.action)) {
841
+ const held = grantActions(grant)
842
+ if (admitted(held, actions).length > 0) {
837
843
  return
838
844
  }
839
845
  const columnWrites: string[] = []
@@ -845,13 +851,41 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
845
851
  if (actions.length === 0 && columnWrites.length === 0) {
846
852
  throw new CapabilityError('undeclared_operation', `${statement}: its policy declares no ${use} action`)
847
853
  }
848
- if (!includes(columnWrites, grant.action)) {
854
+ if (admitted(held, columnWrites).length === 0) {
849
855
  const needs = actions.length === 0 ? [] : [`its ${use} action ${actions.join(' or ')}`]
850
856
  if (columnWrites.length > 0) needs[needs.length] = `a column's own write action (${columnWrites.join(', ')})`
851
- throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${grant.action}`)
857
+ throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${held.join(', ')}`)
852
858
  }
853
859
  }
854
860
 
861
+ /** The actions a grant holds: an `app` grant's (several for an `anyOf` endpoint), or any other grant's one. */
862
+ export function grantActions(grant: CapabilityGrant): readonly string[] {
863
+ return grant.kind === 'app' ? grant.actions : [grant.action]
864
+ }
865
+
866
+ /** The actions of `held` that `allowed` lists: those that allow an operation, as any one of them does. */
867
+ function admitted(held: readonly string[], allowed: readonly string[]): string[] {
868
+ const found: string[] = []
869
+ for (let index = 0; index < held.length; index++) {
870
+ const action = held[index]
871
+ if (action !== undefined && includes(allowed, action)) {
872
+ found[found.length] = action
873
+ }
874
+ }
875
+ return found
876
+ }
877
+
878
+ /** The first of `actions` the table narrows with a `when`: a fragment, which renders column tests only, cannot hold it. */
879
+ function heldCondition(model: TableModel, actions: readonly string[]): string | undefined {
880
+ for (let index = 0; index < actions.length; index++) {
881
+ const action = actions[index]
882
+ if (action !== undefined && hasOwn(model.when, action)) {
883
+ return action
884
+ }
885
+ }
886
+ return undefined
887
+ }
888
+
855
889
  /**
856
890
  * `ctx.sql.scope`'s predicate: what the handles of `capability` match in the table for `use`, as column tests. A
857
891
  * fragment that reads (`'read'`) needs an action the handles read the table with: any action it names for a `Ref`,
@@ -874,10 +908,15 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
874
908
  // The fragment renders column tests only; a relation's, a member reveal's or a path's subquery, or an action's condition, would be left out.
875
909
  const held = grant.kind !== 'app'
876
910
  && (grant.relations.length > 0 || (grant.kind === 'ref' && (grant.revealing.length > 0 || grant.paths.length > 0)))
877
- if (held || hasOwn(model.when, grant.action)) {
911
+ // An `'any'` read is unconditioned: a `when` keyed by the action narrows only its writes.
912
+ const readsEvery = grant.kind === 'app' && use === 'read' && readsAny(context, grant)
913
+ const conditionedBy = readsEvery ? undefined : heldCondition(model, grantActions(grant))
914
+ if (held || conditionedBy !== undefined) {
878
915
  throw new CapabilityError(
879
916
  'unenforceable',
880
- `ctx.sql.scope cannot render a relation, a member reveal, a secondary path or a condition of ${grant.action} on ${model.name}: read it through ctx.db`,
917
+ `ctx.sql.scope cannot render a relation, a member reveal, a secondary path or a condition of ${
918
+ conditionedBy ?? grantActions(grant).join(', ')
919
+ } on ${model.name}: read it through ctx.db`,
881
920
  )
882
921
  }
883
922
  // Nor the subquery through the parent row, which alone places a child view's rows.
@@ -888,7 +927,7 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
888
927
  )
889
928
  }
890
929
  if (grant.kind === 'app') {
891
- if (use === 'read') {
930
+ if (use === 'read' && !readsEvery) {
892
931
  // The action is held as a global grant, so its scope is every row of a table it reaches.
893
932
  checkAppReach(context, grant)
894
933
  }
@@ -1012,32 +1051,63 @@ export function updatingRef(context: TableContext, capability: unknown, dimensio
1012
1051
  */
1013
1052
  export type AppReach = 'rows' | 'counts'
1014
1053
 
1015
- /** Refuses an `app` capability whose action does not reach `reach` of a dimension or child table. */
1016
- function checkRecordReach(context: TableContext, grant: AppGrant, reach: AppReach): void {
1054
+ /**
1055
+ * The actions of an `app` capability that reach `reach` of a dimension or child table, at least one: its read action and
1056
+ * its `appRead`, and for `counts` its `appCount` too. Refuses a capability none of whose actions does.
1057
+ */
1058
+ function recordReach(context: TableContext, grant: AppGrant, reach: AppReach): readonly string[] {
1017
1059
  const model = context.model
1018
1060
  const { appRead, appCount } = model.actions
1019
1061
  const read = model.actions.read.join(' or ')
1020
- if (
1021
- includes(model.actions.read, grant.action) || includes(appRead, grant.action) || (reach === 'counts' && includes(appCount, grant.action))
1022
- ) {
1023
- return
1062
+ const reaching = admitted(grant.actions, model.actions.read)
1063
+ const reads = admitted(grant.actions, appRead)
1064
+ for (let index = 0; index < reads.length; index++) {
1065
+ reaching[reaching.length] = reads[index] ?? ''
1066
+ }
1067
+ const counts = admitted(grant.actions, appCount)
1068
+ if (reach === 'counts') {
1069
+ for (let index = 0; index < counts.length; index++) {
1070
+ reaching[reaching.length] = counts[index] ?? ''
1071
+ }
1024
1072
  }
1025
- if (includes(appCount, grant.action)) {
1073
+ if (reaching.length > 0) {
1074
+ return reaching
1075
+ }
1076
+ const held = grant.actions.join(', ')
1077
+ if (counts.length > 0) {
1026
1078
  throw new CapabilityError(
1027
1079
  'wrong_action',
1028
- `an app capability of ${grant.action} only counts ${model.name} (its appCount): it reads no row, so list, aggregate and a scope fragment need its read action ${read}${
1080
+ `an app capability of ${held} only counts ${model.name} (its appCount): it reads no row, so list, aggregate and a scope fragment need its read action ${read}${
1029
1081
  appRead.length === 0 ? '' : ` or one of its appRead (${appRead.join(', ')})`
1030
1082
  }`,
1031
1083
  )
1032
1084
  }
1033
1085
  throw new CapabilityError(
1034
1086
  'wrong_action',
1035
- `an app capability of ${grant.action} does not reach ${model.name}: ctx.db.app lists it for its read action ${read}${
1087
+ `an app capability of ${held} does not reach ${model.name}: ctx.db.app lists it for its read action ${read}${
1036
1088
  appRead.length === 0 ? '' : ` or one of its appRead (${appRead.join(', ')})`
1037
1089
  } only`,
1038
1090
  )
1039
1091
  }
1040
1092
 
1093
+ /** The actions of an `app` capability the application table names; refuses a capability none of whose actions it names. */
1094
+ function namedActions(model: TableModel, grant: AppGrant): readonly string[] {
1095
+ const named: string[] = []
1096
+ for (let index = 0; index < grant.actions.length; index++) {
1097
+ const action = grant.actions[index]
1098
+ if (action !== undefined && namesAction(model, action)) {
1099
+ named[named.length] = action
1100
+ }
1101
+ }
1102
+ if (named.length === 0) {
1103
+ throw new CapabilityError(
1104
+ 'wrong_action',
1105
+ `an app capability of ${grant.actions.join(', ')} does not reach ${model.name}: ${model.name} does not name the action`,
1106
+ )
1107
+ }
1108
+ return named
1109
+ }
1110
+
1041
1111
  /**
1042
1112
  * Refuses a table `ctx.db.app` does not list for the capability (`applicationTables` in `orm.ts`): it lists an
1043
1113
  * application table under any action the table names, and the rows of a dimension or child table under its read
@@ -1047,12 +1117,7 @@ function checkAppReach(context: TableContext, grant: AppGrant): void {
1047
1117
  const model = context.model
1048
1118
  const mode = model.scope.mode
1049
1119
  if (mode === 'app') {
1050
- if (!namesAction(model, grant.action)) {
1051
- throw new CapabilityError(
1052
- 'wrong_action',
1053
- `an app capability of ${grant.action} does not reach ${model.name}: ${model.name} does not name the action`,
1054
- )
1055
- }
1120
+ namedActions(model, grant)
1056
1121
  return
1057
1122
  }
1058
1123
  if (mode !== 'dimension' && mode !== 'child') {
@@ -1061,14 +1126,20 @@ function checkAppReach(context: TableContext, grant: AppGrant): void {
1061
1126
  `an app capability does not reach ${model.name}: ctx.db.app lists application, dimension and child tables only`,
1062
1127
  )
1063
1128
  }
1064
- checkRecordReach(context, grant, 'rows')
1129
+ recordReach(context, grant, 'rows')
1130
+ }
1131
+
1132
+ /** What an `app` capability reads of a table: the rows (`predicate`), and the reach whose columns it answers. */
1133
+ export interface AppRead {
1134
+ readonly predicate: OperationNode
1135
+ readonly reach: ReadReach
1065
1136
  }
1066
1137
 
1067
1138
  /**
1068
- * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`: `true`, for an action that
1069
- * reaches `reach` (`checkRecordReach`).
1139
+ * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`, for its actions that reach
1140
+ * `reach` (`recordReach`): each row within the condition of one of them, and the columns they read alone.
1070
1141
  */
1071
- export function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode {
1142
+ export function appRecordRead(context: TableContext, capability: unknown, reach: AppReach): AppRead {
1072
1143
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
1073
1144
  const model = context.model
1074
1145
  if (grant.kind !== 'app') {
@@ -1080,8 +1151,13 @@ export function appRecordPredicate(context: TableContext, capability: unknown, r
1080
1151
  if (model.scope.mode !== 'dimension' && model.scope.mode !== 'child') {
1081
1152
  throw new CapabilityError('table_kind', `${model.name} is not a dimension or child table`)
1082
1153
  }
1083
- checkRecordReach(context, grant, reach)
1084
- return conditioned(model, grant.action, 'all', new Date())
1154
+ const actions = recordReach(context, grant, reach)
1155
+ return { predicate: conditionedAny(model, actions, 'all', new Date()), reach: freeze({ actions, narrowed: true }) }
1156
+ }
1157
+
1158
+ /** `appRecordRead`'s rows. */
1159
+ export function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode {
1160
+ return appRecordRead(context, capability, reach).predicate
1085
1161
  }
1086
1162
 
1087
1163
  /** An `app` capability addresses a row by its key, and writes, only in an application table. */
@@ -1095,10 +1171,11 @@ function checkApplicationTable(context: TableContext, operation: Operation): voi
1095
1171
  }
1096
1172
 
1097
1173
  /**
1098
- * The capability of an `app` endpoint for `operation` on `table`: its action is that operation's. An application table
1099
- * is written with it, and a dimension or child table read with it.
1174
+ * The capability of an `app` endpoint for `operation` on `table`, and its actions that are that operation's, at least
1175
+ * one. An application table is written with it, and a dimension or child
1176
+ * table read with it.
1100
1177
  */
1101
- function appGrant(context: TableContext, capability: unknown, operation: Operation): AppGrant {
1178
+ function appGrant(context: TableContext, capability: unknown, operation: Operation): AppOperation {
1102
1179
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
1103
1180
  const table = context.model.name
1104
1181
  if (grant.kind !== 'app') {
@@ -1107,15 +1184,75 @@ function appGrant(context: TableContext, capability: unknown, operation: Operati
1107
1184
  if (operation !== 'read') {
1108
1185
  checkApplicationTable(context, operation)
1109
1186
  }
1187
+ if (operation === 'read' && readsAny(context, grant)) {
1188
+ return { grant, actions: grant.actions, narrowed: false }
1189
+ }
1110
1190
  checkAppReach(context, grant)
1111
- checkAction(context, operation, grant.action)
1112
- return grant
1191
+ return { grant, actions: operationActions(context, operation, grant), narrowed: true }
1192
+ }
1193
+
1194
+ /**
1195
+ * An `app` capability and those of its actions that allow one operation: every one it holds for a read of a table read
1196
+ * with `'any'`, which no `when` narrows.
1197
+ */
1198
+ interface AppOperation extends ReadReach {
1199
+ readonly grant: AppGrant
1113
1200
  }
1114
1201
 
1115
- /** Every row a capability of an `app` endpoint reads in `table`, by the table's read action: `true`. */
1202
+ /** The actions of `grant` that allow `operation` on the table, at least one; `checkAction` over a set. */
1203
+ function operationActions(context: TableContext, operation: Operation, grant: AppGrant): readonly string[] {
1204
+ const actions = requiredActions(context, operation)
1205
+ const allowing = admitted(grant.actions, actions)
1206
+ if (allowing.length === 0) {
1207
+ throw new CapabilityError(
1208
+ 'wrong_action',
1209
+ `${operation} on ${context.model.name} requires ${actions.join(' or ')}; the capability holds ${grant.actions.join(', ')}`,
1210
+ )
1211
+ }
1212
+ return allowing
1213
+ }
1214
+
1215
+ /**
1216
+ * Whether `grant` reads `context`'s table because it is read with `'any'`: every `app` grant but a public procedure's,
1217
+ * which is refused there. The read is unconditioned: a `when` of the grant's action narrows only its writes.
1218
+ */
1219
+ function readsAny(context: TableContext, grant: AppGrant): boolean {
1220
+ const model = context.model
1221
+ if (model.scope.mode !== 'app' || !model.actions.readAny) {
1222
+ return false
1223
+ }
1224
+ if (grant.public) {
1225
+ throw new CapabilityError(
1226
+ 'wrong_capability',
1227
+ `a public procedure does not read ${model.name}: it is read with 'any', which an app endpoint, a job and a webhook hold`,
1228
+ )
1229
+ }
1230
+ return true
1231
+ }
1232
+
1233
+ /**
1234
+ * The rows `held`, the read actions of an `app` capability, read of `context`'s table within `branch`: narrowed by their
1235
+ * conditions, any one admitting a row, unless the table is read with `'any'`.
1236
+ */
1237
+ function appReadPredicate(context: TableContext, held: AppOperation, branch: OperationNode | 'all'): OperationNode {
1238
+ if (context.model.scope.mode === 'app' && context.model.actions.readAny) {
1239
+ return branch === 'all' ? ValueNode.createImmediate(true) : branch
1240
+ }
1241
+ return conditionedAny(context.model, held.actions, branch, new Date())
1242
+ }
1243
+
1244
+ /**
1245
+ * Every row a capability of an `app` endpoint reads in an application table, by the table's read actions it holds or
1246
+ * `'any'`, and the reach whose columns it answers.
1247
+ */
1248
+ export function appListRead(context: TableContext, capability: unknown): AppRead {
1249
+ const held = appGrant(context, capability, 'read')
1250
+ return { predicate: appReadPredicate(context, held, 'all'), reach: freeze({ actions: held.actions, narrowed: held.narrowed }) }
1251
+ }
1252
+
1253
+ /** `appListRead`'s rows. */
1116
1254
  export function appListPredicate(context: TableContext, capability: unknown): OperationNode {
1117
- const grant = appGrant(context, capability, 'read')
1118
- return conditioned(context.model, grant.action, 'all', new Date())
1255
+ return appListRead(context, capability).predicate
1119
1256
  }
1120
1257
 
1121
1258
  /**
@@ -1131,6 +1268,12 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
1131
1268
  if (grant.kind === 'app') {
1132
1269
  throw new CapabilityError('wrong_capability', `a read of ${model.name} from a scoped site needs a Ref or a Within, got ${describeGrant(grant)}`)
1133
1270
  }
1271
+ if (model.actions.readAny) {
1272
+ throw new CapabilityError(
1273
+ 'wrong_capability',
1274
+ `a scoped site does not read ${model.name}: it is read with 'any', which an app endpoint, a job and a webhook hold`,
1275
+ )
1276
+ }
1134
1277
  const read = requiredActions(context, 'read')
1135
1278
  if (!includes(read, grant.action)) {
1136
1279
  throw new CapabilityError(
@@ -1144,8 +1287,9 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
1144
1287
  /** One row of an application table by its key, for an `app` capability of `operation`'s action. */
1145
1288
  export function appRowPredicate(context: TableContext, capability: unknown, key: unknown, operation: Operation): OperationNode {
1146
1289
  checkApplicationTable(context, operation)
1147
- const grant = appGrant(context, capability, operation)
1148
- return conditioned(context.model, grant.action, appKeyPredicate(context.model, key), new Date())
1290
+ const held = appGrant(context, capability, operation)
1291
+ const row = appKeyPredicate(context.model, key)
1292
+ return operation === 'read' ? appReadPredicate(context, held, row) : conditionedAny(context.model, held.actions, row, new Date())
1149
1293
  }
1150
1294
 
1151
1295
  /**
@@ -1155,15 +1299,20 @@ export function appRowPredicate(context: TableContext, capability: unknown, key:
1155
1299
  export function claimScope(
1156
1300
  context: TableContext,
1157
1301
  capability: unknown,
1158
- ): { readonly grant: AppGrant | WithinGrant; readonly scope: OperationNode | undefined } {
1302
+ ): { readonly grant: AppGrant | WithinGrant; readonly action: string; readonly scope: OperationNode | undefined } {
1159
1303
  const model = context.model
1160
1304
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
1161
1305
  if (model.queue === undefined) {
1162
1306
  throw new CapabilityError('undeclared_operation', `${model.name} is not a queue table: its policy declares no queue`)
1163
1307
  }
1164
1308
  if (grant.kind === 'app') {
1165
- const held = appGrant(context, capability, 'update')
1166
- return { grant: held, scope: conditioned(model, held.action, 'all', new Date()) }
1309
+ const [action, ...more] = grant.actions
1310
+ // A claimed row's `row.ref` is finished under one action; only a job claims, and its `ctx.app(action)` holds one.
1311
+ if (more.length > 0) {
1312
+ throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a capability of one action, got one of ${grant.actions.join(', ')}`)
1313
+ }
1314
+ appGrant(context, capability, 'update')
1315
+ return { grant, action, scope: conditioned(model, action, 'all', new Date()) }
1167
1316
  }
1168
1317
  if (grant.kind !== 'within') {
1169
1318
  throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a Within or an app capability, got ${describeGrant(grant)}`)
@@ -1179,7 +1328,7 @@ export function claimScope(
1179
1328
  `a Within of ${grant.dimension} does not reach ${model.name}: its containment chain does not hold ${grant.dimension}`,
1180
1329
  )
1181
1330
  }
1182
- return { grant, scope: withinPredicate(context, column, grant, 'update') }
1331
+ return { grant, action: grant.action, scope: withinPredicate(context, column, grant, 'update') }
1183
1332
  }
1184
1333
 
1185
1334
  /**
@@ -1205,9 +1354,14 @@ export function claimedRowPredicate(context: TableContext, capability: unknown,
1205
1354
  return conditioned(model, grant.action, allOf(terms), new Date())
1206
1355
  }
1207
1356
 
1208
- /** The row of an application table `key` names, as `action` reaches it: within the action's condition. */
1209
- export function appKeyScope(model: TableModel, action: string, key: unknown): OperationNode {
1210
- return conditioned(model, action, appKeyPredicate(model, key), new Date())
1357
+ /** The row of an application table `key` names, as `actions` reach it: within their conditions, any one admitting it. */
1358
+ export function appKeyScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode {
1359
+ return conditionedAny(model, actions, appKeyPredicate(model, key), new Date())
1360
+ }
1361
+
1362
+ /** The row `key` names, as a read by key with `actions` reaches it: unconditioned in a table read with `'any'`. */
1363
+ export function appGetScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode {
1364
+ return model.actions.readAny ? appKeyPredicate(model, key) : appKeyScope(model, actions, key)
1211
1365
  }
1212
1366
 
1213
1367
  /** The row of an application table `key` names. */
@@ -1219,10 +1373,10 @@ export function appKeyPredicate(model: TableModel, key: unknown): OperationNode
1219
1373
  }
1220
1374
 
1221
1375
  /**
1222
- * The capability of an `app` endpoint whose action updates columns of an application table: its update action, or a
1223
- * column's own write action. Which columns it updates follows from the action (`updatableBy`).
1376
+ * The actions of an `app` endpoint's capability that update columns of an application table, at least one: its update
1377
+ * action, or a column's own write action. Which columns they update follows from them (`updatableByAny`).
1224
1378
  */
1225
- export function updatingApp(context: TableContext, capability: unknown): AppGrant {
1379
+ export function updatingApp(context: TableContext, capability: unknown): readonly string[] {
1226
1380
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
1227
1381
  const table = context.model.name
1228
1382
  if (grant.kind !== 'app') {
@@ -1233,12 +1387,63 @@ export function updatingApp(context: TableContext, capability: unknown): AppGran
1233
1387
  if (actions.length === 0) {
1234
1388
  throw new CapabilityError('undeclared_operation', `${table} allows no update; its policy declares no update action`)
1235
1389
  }
1236
- for (let index = 0; index < actions.length; index++) {
1237
- if (actions[index] === grant.action) {
1238
- return grant
1390
+ const updating = admitted(grant.actions, actions)
1391
+ if (updating.length === 0) {
1392
+ throw new CapabilityError('wrong_action', `update on ${table} requires ${actions.join(' or ')}; the capability holds ${grant.actions.join(', ')}`)
1393
+ }
1394
+ return updating
1395
+ }
1396
+
1397
+ /**
1398
+ * An `app` capability's update of the application table row `key`: `values`, read against the columns its update
1399
+ * actions write, and the row's scope under only those actions that write every given column, any one's condition
1400
+ * admitting the row. So several held actions never write one action's columns on rows only another one reaches.
1401
+ */
1402
+ export function appUpdate(
1403
+ context: TableContext,
1404
+ capability: unknown,
1405
+ key: unknown,
1406
+ values: unknown,
1407
+ ): { readonly scope: OperationNode; readonly changes: Map<string, Primitive | null> } {
1408
+ const model = context.model
1409
+ const updating = updatingApp(context, capability)
1410
+ const writable = updatableByAny(model, updating)
1411
+ const changes = readValues(values, writable, 'update', model)
1412
+ // `readValues` took only columns of `writable`, so those of them `changes` sets are every column it sets.
1413
+ const columns = namesOf(writable)
1414
+ const written: string[] = []
1415
+ for (let index = 0; index < columns.length; index++) {
1416
+ const name = columns[index] ?? ''
1417
+ if (changes.has(name)) {
1418
+ written[written.length] = name
1239
1419
  }
1240
1420
  }
1241
- throw new CapabilityError('wrong_action', `update on ${table} requires ${actions.join(' or ')}; the capability holds ${grant.action}`)
1421
+ const covering: string[] = []
1422
+ for (let index = 0; index < updating.length; index++) {
1423
+ const action = updating[index]
1424
+ if (action !== undefined && writesEvery(updatableBy(model, action), written)) {
1425
+ covering[covering.length] = action
1426
+ }
1427
+ }
1428
+ if (covering.length === 0) {
1429
+ throw new CapabilityError(
1430
+ 'wrong_action',
1431
+ `no action of ${updating.join(', ')} updates every column of this update of ${model.name} (${
1432
+ written.join(', ')
1433
+ }): update the columns of each action apart`,
1434
+ )
1435
+ }
1436
+ return { scope: appKeyScope(model, covering, key), changes }
1437
+ }
1438
+
1439
+ /** Whether `columns` holds each of `written`. */
1440
+ function writesEvery(columns: NameSet, written: readonly string[]): boolean {
1441
+ for (let index = 0; index < written.length; index++) {
1442
+ if (!inSet(columns, written[index])) {
1443
+ return false
1444
+ }
1445
+ }
1446
+ return true
1242
1447
  }
1243
1448
 
1244
1449
  export function childObjectPredicate(context: TableContext, parent: unknown, key: unknown, operation: Operation): OperationNode {
@@ -1288,9 +1493,29 @@ export function fencedWork<T>(runtime: DataLayerRuntime, work: (transaction: Ses
1288
1493
  return fence === null ? session.transaction(work) : fencedTransaction(session, fence, work)
1289
1494
  }
1290
1495
 
1291
- /** The action a capability holds, which its operation's checks already admitted. */
1496
+ /**
1497
+ * The one action a capability holds, which its operation's checks already admitted. An `anyOf` endpoint's `app`
1498
+ * capability that holds several is refused: it reads through `ctx.db.app`, which reads with every action it holds.
1499
+ */
1292
1500
  export function heldAction(context: TableContext, capability: unknown): string {
1293
- return runtimeOf(context.connection).capabilities.resolve(capability).action
1501
+ const grant = runtimeOf(context.connection).capabilities.resolve(capability)
1502
+ if (grant.kind !== 'app') {
1503
+ return grant.action
1504
+ }
1505
+ const [action, ...more] = grant.actions
1506
+ if (more.length > 0) {
1507
+ throw new CapabilityError(
1508
+ 'wrong_capability',
1509
+ `this read takes a capability of one action, got one of ${grant.actions.join(', ')}: read through ctx.db.app`,
1510
+ )
1511
+ }
1512
+ return action
1513
+ }
1514
+
1515
+ /** The one action a capability holds, or `undefined` for an `anyOf` endpoint's `app` capability that holds several. */
1516
+ function soleAction(context: TableContext, capability: unknown): string | undefined {
1517
+ const actions = grantActions(runtimeOf(context.connection).capabilities.resolve(capability))
1518
+ return actions.length === 1 ? actions[0] : undefined
1294
1519
  }
1295
1520
 
1296
1521
  function storeRunner(context: TableContext): Runner {
@@ -1395,7 +1620,7 @@ async function selectRows<S>(
1395
1620
  context: TableContext,
1396
1621
  scope: OperationNode | undefined,
1397
1622
  state: SelectState,
1398
- action: string,
1623
+ action: string | undefined,
1399
1624
  visible: readonly string[] = context.model.visible,
1400
1625
  ): Promise<S[]> {
1401
1626
  const run = storeRunner(context)
@@ -1404,6 +1629,9 @@ async function selectRows<S>(
1404
1629
  for (let index = 0; index < state.joins.length; index++) {
1405
1630
  const join = state.joins[index]
1406
1631
  if (join === undefined) continue
1632
+ if (action === undefined) {
1633
+ throw new CapabilityError('wrong_capability', `joining ${join.join.shape.table} takes a capability of one action, whose condition narrows it`)
1634
+ }
1407
1635
  if (!includes(join.join.readActions, action)) {
1408
1636
  throw new CapabilityError(
1409
1637
  'wrong_action',
@@ -1479,14 +1707,14 @@ function joinedColumns(context: TableContext, state: SelectState): RowColumns {
1479
1707
 
1480
1708
  /**
1481
1709
  * One row by its scope predicate, with `visible` columns (the table's read action's, unless a capability reads its own).
1482
- * `action` is what read it: each file column then answers a reference that reads the file only under a read action.
1710
+ * `reach` is what read it: each file column then answers a reference that reads the file only under a read action.
1483
1711
  */
1484
1712
  export async function selectOne<O>(
1485
1713
  context: TableContext,
1486
1714
  run: Runner,
1487
1715
  scope: OperationNode,
1488
1716
  visible = context.model.visible,
1489
- action?: string,
1717
+ reach?: ReadReach,
1490
1718
  ): Promise<O> {
1491
1719
  const start = startSelect(context.shape)
1492
1720
  const state = finishSelect(start, start)
@@ -1498,8 +1726,8 @@ export async function selectOne<O>(
1498
1726
  if (row === undefined) {
1499
1727
  throw new NotFoundError(`${context.model.name} not found`)
1500
1728
  }
1501
- if (action !== undefined) {
1502
- await answerFiles(context.model, run.files, session, [row], action)
1729
+ if (reach !== undefined) {
1730
+ await answerFiles(context.model, run.files, session, [row], reach)
1503
1731
  }
1504
1732
  return row
1505
1733
  }
@@ -1640,20 +1868,20 @@ export interface OnConflict {
1640
1868
  readonly mode: 'nothing' | 'update'
1641
1869
  /** The values given for the table's update columns: what `update` sets on the conflicting row. */
1642
1870
  readonly updates: ReadonlyMap<string, Primitive | null>
1643
- /** The capability's action, whose condition the conflicting row must satisfy to be updated. */
1644
- readonly action: string
1871
+ /** The capability's update actions, one of whose conditions the conflicting row must satisfy to be updated. */
1872
+ readonly actions: readonly string[]
1645
1873
  }
1646
1874
 
1647
1875
  const CONFLICT_FIELDS = nameSet(['columns', 'do'])
1648
1876
 
1649
1877
  /**
1650
1878
  * The `onConflict` of an insert's options, read through own data properties; `undefined` without options. `'update'`
1651
- * also needs the capability's action to be one of the table's update actions.
1879
+ * also needs one of the capability's `actions` to be one of the table's update actions.
1652
1880
  */
1653
1881
  export function onConflictOf(
1654
1882
  context: TableContext,
1655
1883
  options: unknown,
1656
- action: string,
1884
+ actions: readonly string[],
1657
1885
  given: ReadonlyMap<string, Primitive | null>,
1658
1886
  ): OnConflict | undefined {
1659
1887
  if (options === undefined) {
@@ -1684,13 +1912,14 @@ export function onConflictOf(
1684
1912
  throw new QueryRefusedError('on_conflict', "onConflict.do takes 'nothing' or 'update'")
1685
1913
  }
1686
1914
  const updates = new Map<string, Primitive | null>()
1915
+ const updating = admitted(actions, model.actions.update)
1687
1916
  if (mode === 'update') {
1688
- if (!includes(model.actions.update, action)) {
1917
+ if (updating.length === 0) {
1689
1918
  throw new CapabilityError(
1690
1919
  'wrong_action',
1691
1920
  `an insert of ${model.name} that updates on a conflict also needs its update action ${
1692
1921
  model.actions.update.join(' or ') || '(none)'
1693
- }; the capability holds ${action}`,
1922
+ }; the capability holds ${actions.join(', ')}`,
1694
1923
  )
1695
1924
  }
1696
1925
  const columns = namesOf(model.update)
@@ -1702,7 +1931,7 @@ export function onConflictOf(
1702
1931
  }
1703
1932
  }
1704
1933
  }
1705
- return freeze({ columns: freeze(columns), mode, updates, action })
1934
+ return freeze({ columns: freeze(columns), mode, updates, actions: freeze(updating) })
1706
1935
  }
1707
1936
 
1708
1937
  /** A plain object's own data properties, each one of `allowed`; the options of an insert or its `onConflict`. */
@@ -1780,7 +2009,7 @@ async function insertOnConflict(
1780
2009
  }
1781
2010
  matches[matches.length] = equals(model.name, name, value)
1782
2011
  }
1783
- const scope = conflict.mode === 'update' ? conditioned(model, conflict.action, insertedScope(context, values), new Date()) : undefined
2012
+ const scope = conflict.mode === 'update' ? conditionedAny(model, conflict.actions, insertedScope(context, values), new Date()) : undefined
1784
2013
  for (let attempt = 0; attempt < 2; attempt++) {
1785
2014
  const node = insertNode(model.name, values, answer(context), conflict.columns)
1786
2015
  const [row] = await transaction.run<Readonly<Record<string, unknown>>>(node, {
@@ -2102,42 +2331,77 @@ export function prepareDimensionInsert(context: TableContext, target: unknown, v
2102
2331
  const scope = dimensionScope(context.model)
2103
2332
  const grant = refGrant(context, target, listDimension(scope), 'insert')
2104
2333
  const row = readValues(values, context.model.insert, 'insert', context.model)
2105
- const conflict = onConflictOf(context, options, grant.action, row)
2334
+ const conflict = onConflictOf(context, options, [grant.action], row)
2106
2335
  if (scope.container === undefined) {
2107
2336
  // The object does not exist yet; this only refuses a chain the table has no column for.
2108
2337
  linkValues(context.model.name, [{ dimension: scope.dimension, column: scope.key }], grant)
2109
2338
  stampInsert(context, grant, row, scope.key, grant.id)
2110
- const judged = checkInserted(context, grant, row)
2339
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2111
2340
  // No destination to check again after the write, so a condition with a path holds nothing here.
2112
2341
  narrowedDestination(context, grant, row, false)
2113
2342
  return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
2114
2343
  }
2115
2344
  stampInsert(context, grant, row, scope.key, uuidv7())
2116
2345
  stampChain(row, linkValues(context.model.name, context.model.chain, grant))
2117
- const judged = checkInserted(context, grant, row)
2346
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2118
2347
  const held = narrowedDestination(context, grant, row, true)
2119
2348
  return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
2120
2349
  }
2121
2350
 
2122
2351
  /** An application table's insert, for an `app` capability of its insert action: a new key, no containment. */
2123
2352
  export function prepareApplicationInsert(context: TableContext, capability: unknown, values: unknown, options?: unknown): PreparedInsert {
2124
- const grant = appGrant(context, capability, 'insert')
2353
+ const { grant, actions } = appGrant(context, capability, 'insert')
2354
+ // Every insert action writes the table's one insert list, so each held one writes all of `values`: only their conditions differ.
2125
2355
  const row = readValues(values, context.model.insert, 'insert', context.model)
2126
- const conflict = onConflictOf(context, options, grant.action, row)
2356
+ // Only an insert action that also updates may update on a conflict: never one action's insert with another's update.
2357
+ const declared = onConflictOf(context, options, actions, row)
2127
2358
  stampInsert(context, grant, row, keyOf(context.model), uuidv7())
2128
- const judged = checkInserted(context, grant, row)
2359
+ const conflict = declared?.mode === 'update' ? upsertingActions(context.model, declared, row) : declared
2360
+ const judged = checkInserted(context, conflict?.mode === 'update' ? conflict.actions : actions, grant.principal, row)
2129
2361
  return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
2130
2362
  }
2131
2363
 
2364
+ /**
2365
+ * An upsert under several actions that each insert and update: only those whose own condition admits the inserted row
2366
+ * may update the conflicting one, so the update runs under an action whose insert alone was allowed. A condition that
2367
+ * follows a path is judged only in the transaction, after the update chose its actions, so several such are refused.
2368
+ */
2369
+ function upsertingActions(model: TableModel, conflict: OnConflict, row: ReadonlyMap<string, Primitive | null>): OnConflict {
2370
+ if (conflict.actions.length < 2) {
2371
+ return conflict
2372
+ }
2373
+ const now = new Date()
2374
+ const admitting: string[] = []
2375
+ for (let index = 0; index < conflict.actions.length; index++) {
2376
+ const action = conflict.actions[index] ?? ''
2377
+ const condition = ownEntry(model.when, action)
2378
+ if (condition !== undefined && readPaths(condition).length > 0) {
2379
+ throw new CapabilityError(
2380
+ 'unenforceable',
2381
+ `an insert into ${model.name} that updates on a conflict under ${
2382
+ conflict.actions.join(', ')
2383
+ } would pair a condition that follows a path with another action's: upsert from an endpoint of one of them`,
2384
+ )
2385
+ }
2386
+ if (condition === undefined || rowSatisfies(condition, row, now)) {
2387
+ admitting[admitting.length] = action
2388
+ }
2389
+ }
2390
+ // None admits the row: keep them all, and the insert's own check refuses it.
2391
+ return admitting.length === 0
2392
+ ? conflict
2393
+ : freeze({ columns: conflict.columns, mode: conflict.mode, updates: conflict.updates, actions: freeze(admitting) })
2394
+ }
2395
+
2132
2396
  /** A child table's insert under the parent its `Ref` names, whose chain is checked against the database. */
2133
2397
  export function prepareChildInsert(context: TableContext, parent: unknown, values: unknown, options?: unknown): PreparedInsert {
2134
2398
  const scope = childScope(context)
2135
2399
  const grant = refGrant(context, parent, scope.parent.dimension, 'insert')
2136
2400
  const row = readValues(values, context.model.insert, 'insert', context.model)
2137
- const conflict = onConflictOf(context, options, grant.action, row)
2401
+ const conflict = onConflictOf(context, options, [grant.action], row)
2138
2402
  stampInsert(context, grant, row, scope.key, uuidv7())
2139
2403
  stampChain(row, linkValues(context.model.name, context.model.chain, grant))
2140
- const judged = checkInserted(context, grant, row)
2404
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2141
2405
  const held = narrowedDestination(context, grant, row, true)
2142
2406
  return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
2143
2407
  }
@@ -2152,16 +2416,13 @@ const DAY_MS = 86_400_000
2152
2416
  */
2153
2417
  function checkInserted(
2154
2418
  context: TableContext,
2155
- grant: { readonly action: string; readonly principal: string },
2419
+ actions: readonly string[],
2420
+ principal: string,
2156
2421
  row: ReadonlyMap<string, Primitive | null>,
2157
2422
  ): JudgedInsert | undefined {
2158
2423
  const model = context.model
2159
2424
  const now = new Date()
2160
- const condition = ownEntry(model.when, grant.action)
2161
- const judged = condition === undefined || readPaths(condition).length === 0 ? undefined : { action: grant.action, condition }
2162
- if (condition !== undefined && judged === undefined && !rowSatisfies(condition, row, now)) {
2163
- throw new ConflictError(`the row is outside what ${grant.action} inserts into ${model.name}`)
2164
- }
2425
+ const judged = insertCondition(model, actions, row, now)
2165
2426
  for (let index = 0; index < model.confers.length; index++) {
2166
2427
  const source = model.confers[index]
2167
2428
  if (source === undefined) {
@@ -2172,7 +2433,7 @@ function checkInserted(
2172
2433
  throw new CapabilityError('undeclared_operation', `${model.name} confers ${source.relation} and states no assign, so no handler inserts a row`)
2173
2434
  }
2174
2435
  // A principal through a path is resolved in the insert's transaction (`checkPrincipalAssign`).
2175
- if (!assign.self && source.principalPath === undefined && row.get(source.principal) === grant.principal) {
2436
+ if (!assign.self && source.principalPath === undefined && row.get(source.principal) === principal) {
2176
2437
  throw new ConflictError(`a row of ${model.name} names its writer in ${source.relation}, which assign.self does not allow`)
2177
2438
  }
2178
2439
  if (assign.maxDays !== undefined && source.expires !== undefined) {
@@ -2188,6 +2449,46 @@ function checkInserted(
2188
2449
  return judged
2189
2450
  }
2190
2451
 
2452
+ /**
2453
+ * The insert actions' condition on the row, as one role holding `actions` is narrowed: a row any of them admits passes,
2454
+ * and one without a condition admits every row. A pathless condition is judged here; one that follows a path is
2455
+ * answered for the transaction to judge, which holds one such condition only, so several are refused.
2456
+ */
2457
+ function insertCondition(
2458
+ model: TableModel,
2459
+ actions: readonly string[],
2460
+ row: ReadonlyMap<string, Primitive | null>,
2461
+ now: Date,
2462
+ ): JudgedInsert | undefined {
2463
+ const pathed: JudgedInsert[] = []
2464
+ for (let index = 0; index < actions.length; index++) {
2465
+ const action = actions[index]
2466
+ if (action === undefined) continue
2467
+ const condition = ownEntry(model.when, action)
2468
+ if (condition === undefined) {
2469
+ return undefined
2470
+ }
2471
+ if (readPaths(condition).length > 0) {
2472
+ pathed[pathed.length] = { action, condition }
2473
+ } else if (rowSatisfies(condition, row, now)) {
2474
+ return undefined
2475
+ }
2476
+ }
2477
+ const [only, ...more] = pathed
2478
+ if (only === undefined) {
2479
+ throw new ConflictError(`the row is outside what ${actions.join(' or ')} inserts into ${model.name}`)
2480
+ }
2481
+ if (more.length > 0) {
2482
+ throw new CapabilityError(
2483
+ 'unenforceable',
2484
+ `an insert into ${model.name} under ${
2485
+ actions.join(', ')
2486
+ } would be judged by several conditions that follow paths: insert from an endpoint of one of them`,
2487
+ )
2488
+ }
2489
+ return only
2490
+ }
2491
+
2191
2492
  /**
2192
2493
  * The destination `Ref` an insert locks, without the relations the inserted table's `relationWhen` narrows for the insert
2193
2494
  * and the written row fails: a pathless condition judged here, on the row's final values; one with a path answered for
@@ -2874,7 +3175,7 @@ function probeRunner(context: TableContext): { readonly run: Runner; readonly he
2874
3175
  }
2875
3176
 
2876
3177
  /**
2877
- * One table's operations without the store types, for `@fabrika/db/testing` only: the generated isolation tests address
3178
+ * One table's operations without the store types, for `@fabrika/db/testing` only: the policy isolation kit addresses
2878
3179
  * a table by name. Every runtime check of a store applies; a child row is addressed by its parent's capability and
2879
3180
  * `key`, a dimension row by its capability alone.
2880
3181
  */
@@ -2902,15 +3203,19 @@ function probeOf(context: TableContext): TableProbe {
2902
3203
  }
2903
3204
  return objectPredicate(context, capability, operation)
2904
3205
  }
3206
+ const app = (capability: unknown): boolean => runtimeOf(context.connection).capabilities.resolve(capability).kind === 'app'
2905
3207
  // An `app` capability reads every row through ctx.db.app: its rows with appRead, its counts with appCount too.
2906
3208
  const list = (capability: unknown, reach: AppReach): OperationNode | undefined => {
2907
- if (runtimeOf(context.connection).capabilities.resolve(capability).kind === 'app') {
3209
+ if (app(capability)) {
2908
3210
  return appRecordPredicate(context, capability, reach)
2909
3211
  }
2910
3212
  return child ? childListPredicate(context, capability, 'read') : dimensionListPredicate(context, capability, 'read')
2911
3213
  }
2912
- // A capability reads the columns of its own action, as ctx.db does.
2913
- const visible = (capability: unknown): readonly string[] => visibleFor(context.model, heldAction(context, capability))
3214
+ // A capability reads the columns of its own action, as ctx.db does; an `app` one those its reaching actions read alone.
3215
+ const visible = (capability: unknown): readonly string[] =>
3216
+ app(capability)
3217
+ ? visibleThrough(context.model, appRecordRead(context, capability, 'rows').reach)
3218
+ : visibleFor(context.model, heldAction(context, capability))
2914
3219
  const { run, held } = probeRunner(context)
2915
3220
  return freeze({
2916
3221
  mode: child ? 'child' : 'dimension',
@@ -2921,7 +3226,7 @@ function probeOf(context: TableContext): TableProbe {
2921
3226
  context,
2922
3227
  list(capability, 'rows'),
2923
3228
  finishSelect(start, start),
2924
- heldAction(context, capability),
3229
+ soleAction(context, capability),
2925
3230
  visible(capability),
2926
3231
  )
2927
3232
  },
@@ -2992,7 +3297,7 @@ function appProbeOf(context: TableContext): TableProbe {
2992
3297
  context,
2993
3298
  every(capability),
2994
3299
  finishSelect(start, start),
2995
- heldAction(context, capability),
3300
+ soleAction(context, capability),
2996
3301
  )
2997
3302
  },
2998
3303
  count,