Repository navigation
Expand file tree
/
Copy pathaction-execution.ts
More file actions
4943 lines (4753 loc) · 263 KB
/
Copy pathaction-execution.ts
File metadata and controls
4943 lines (4753 loc) · 263 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* Action-execution subsystem — extracted dispatcher helpers (ADR-0076 D11
* step ③, PR-8). The shared machinery behind server-registered business
* actions: declaration collection/resolution, param enforcement
* (ADR-0104), permission/exposure gates, the engine facade + session shape
* handlers receive, invocation, and the `callData` protocol/ObjectQL data
* bridge. Consumed by the `/actions` domain and the MCP bridge (tool
* invocation path) — extracting it is what turns those two domains into
* mechanical extractions (PR-9).
*
* Depends only on {@link ActionExecutionDeps} — a narrow slice of the
* domain deps contract. NO env-resolution state (kernel/resolver) lives
* here; that stays with the route handlers.
*/
import { validateActionParams, type ActionSession, type ResolvedActionParam } from '@objectstack/spec/ui';
import { templateSlotSource } from '@objectstack/spec/automation';
// [#15124] The facade's `find` judges its own parameter against the SAME
// declaration its type names, so the refusal and the type cannot drift apart.
import { EngineQueryOptionsSchema, DATA_ACTION_TO_API_OPERATION } from '@objectstack/spec/data';
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { isStoredMetadataBodyObject } from '@objectstack/spec/kernel';
import type { IHttpServer, IObjectQLEngine, InternalFieldEvaluationQuery, QueryEvaluationGate, ServiceSlotContract, ServiceSlotContracts } from '@objectstack/spec/contracts';
import { standardErrorCodeForHttpStatus, type MetadataProtocol } from '@objectstack/spec/api';
// [#15942 / #16293] The confirmation member's SPELLING is the contract, so it
// is imported, never hand-spelled: the door that refuses and the client that
// retries have to agree on it, and two doors each writing their own 'confirm'
// is how one contract becomes two dialects (Prime Directive #12).
import {
AI_ACTION_CONFIRMATION_MEMBER,
type AIActionConfirmation,
type ActionConfirmationRequiredDetails,
} from '@objectstack/spec/contracts';
import { checkApiExposure, type ApiExposureDecision, type ObjectApiDef } from './api-exposure.js';
// [#22823] The ONE walk every door that hands a caller's filter to the engine
// takes to find its nested-relation conditions and each one's target — the data
// door's and the MCP stdio bridge's, imported rather than re-walked so this door
// cannot disagree with them about which conditions a filter holds.
import { relationConditionSites } from '@objectstack/core';
// [ADR-0090 D10 rule 5] The agent forward credential: minted here, redeemed by
// the doors that serve forward targets (the dispatcher, the REST face, the
// identity mount). One module in `@objectstack/rest`, which all three reach.
import { FORWARD_CREDENTIAL_HEADER, withForwardCredential, type ForwardAgentProvenance } from '@objectstack/rest';
import { MCP_OAUTH_SCOPE_ACTIONS, MCP_OAUTH_SCOPE_DATA_READ, MCP_OAUTH_SCOPE_DATA_WRITE, MCP_OAUTH_SCOPE_METADATA_WRITE } from '@objectstack/spec/ai';
// [#25653] The app-automation elevation mark an action body's context carries
// — see `buildActionExecutionContext`.
import { markAppAutomationElevation } from '@objectstack/core';
// Managing API keys is a signed-in-session act: the one rule this door's
// per-object gate asks beside the exposure decision, shared with `RestServer`.
import { apiKeyManagementCredentialRefusal } from '@objectstack/core';
// [#9446] The ONE #9378 status table. Imported rather than re-read here: this
// door's blanket `FLOW_FAILED` was the second of three readings of one engine
// result, and a second definition of the rule is what let the doors diverge.
import {
classifyFlowRefusal,
flowFailureDetails,
flowFailureEnvelope,
flowIsUnknown,
flowNotFoundMessage,
FLOW_NOT_FOUND_STATUS,
type FlowRefusalCode,
} from './flow-dispatch-status.js';
// Who may START a flow by name — the one rule the trigger door, this door and
// the declared endpoint share (the maintainer's rulings, letters B and A, and
// the flow's own `requiredPermissions`).
import { flowDeclaredRecordReads, flowRunsElevated, flowStartRefusal } from './flow-start-admission.js';
import { validationFailure } from './validation-failure.js';
// [ADR-0066 D4] The capability arithmetic the action gate and the flow start
// gate share.
import { missingCapabilities } from './required-capabilities.js';
import type { FlowFailureDetails } from '@objectstack/spec/api';
// [#5138] The ONE 404 envelope a single-record path answers. Imported rather
// than re-spelled so `callData`'s ObjectQL fallback and the protocol service it
// falls back FROM cannot disagree about what "this id names no row" looks like.
// A pure factory — no service resolution — so importing it costs the fallback
// nothing on an assembly where the protocol plugin is absent, which is exactly
// when the fallback runs.
import { recordNotFoundError, omitInternalFieldsFromWriteResponse } from '@objectstack/metadata-protocol';
import { serveStoredMetadataRead, serveStoredMetadataReadsThrough } from './stored-metadata-reader-seam.js';
import { actorUserFromExecutionContext, resolveActorDisplayName } from './security/actor-user.js';
import { actionInvocationBranch, actionInvocationFailure, actionInvocationTarget, recordActionInvocation, withActionSurface } from './action-invocation-audit.js';
import type { HttpProtocolContext } from './http-dispatcher.js';
import {
GLOBAL_ACTION_OBJECT_KEY,
actionHandlerObjectKeys,
isObjectLessActionKey,
reconcileActionRegistrations as reconcileActionRegistrationsPure,
resolveActionHandlerKeys,
standaloneActionOwnerKey,
} from '@objectstack/objectql';
import { earnedAnswerOf, staleSummaryRefusalOrThrow, withEarnedAnswer, type SummaryRecomputeRefusal } from '@objectstack/types';
// [ADR-0110] The addressing vocabulary and the D5 reconciliation moved to
// @objectstack/objectql (the engine owns the map they describe, and its
// plugin now runs the boot inventory — AppPlugin, the previous host, is
// registered conditionally and never ran it on the `os dev` path). Runtime
// re-exports them so dispatch, the MCP bridge and existing importers keep
// reading the ONE implementation.
export {
GLOBAL_ACTION_OBJECT_KEY,
actionHandlerObjectKeys,
isObjectLessActionKey,
resolveActionHandlerKeys,
standaloneActionOwnerKey,
};
/** A `sys_`-prefixed object is a system table — off-limits to external MCP agents. */
export function isSystemObjectName(name: string): boolean {
return /^sys_/i.test(name);
}
/**
* [#27681 / ADR-0011] The `sys_*` gate of the MCP action surface, PER ACTION.
* Returns a human-readable refusal for an action on a system object that its
* author did not opt into the AI surface, or `null` when the action may pass
* (a non-system object, or a system-object action declaring `ai.exposed: true`).
*
* Maintainer ruling 6513869839 (letter B): a `sys_*` action is reachable over
* MCP only when the action itself declares `ai: { exposed: true, description }`.
* The guard that stood here refused EVERY action on a `sys_*` object by name,
* ahead of the exposure check, so no declaration could open one, while the REST
* `/actions` door served the same action to the same principal. The refusal now
* yields to the author's opt-in and to nothing else:
*
* - no deployment switch reaches it (the MCP package's `allowSystemObjects`
* stays on the tool layer and gains no reach here — ruling parameter 1);
* - every later gate still runs behind it, unchanged: the ADR-0066 D4
* capability gate, the ADR-0126 §8 activation consult, the param contract,
* the `ai.requiresConfirmation` gate and the subject load under RLS.
*
* ONE predicate for the three MCP sites that ask it — `run_action`
* ({@link invokeBusinessAction}), the `list_actions` bridge and the
* `resume_run` admission (`domains/mcp.ts`) — so an agent that lists sees
* exactly the system-object actions it may run.
*/
export function systemObjectActionExposureError(_deps: ActionExecutionDeps, action: any, objectName: string): string | null {
if (!isSystemObjectName(objectName)) return null;
// [#21594] The stored-metadata family is NOT opened by the flag: the MCP
// door never reaches the subject load for one of its tables (a row carries
// a stored metadata body, credential material included). That boundary
// predates the ruling, which opened identity actions and named no family
// table; it held here only because every `sys_*` action was refused.
if (isStoredMetadataBodyObject(objectName)) {
return (
`Action '${action?.name ?? 'unknown'}' is on a system object ('${objectName}') that stores metadata bodies ` +
`and is never exposed via MCP — read and change those through the metadata API`
);
}
if (action?.ai?.exposed === true) return null;
return (
`Action '${action?.name ?? 'unknown'}' is on a system object ('${objectName}') and is not exposed via MCP — ` +
`a system object's action is reachable here only when its author declares \`ai: { exposed: true, description: … }\` on it`
);
}
/**
* Escape hatch: accept param bags that violate the declared contract, the way
* the pre-17 dispatcher did (ADR-0104 D2, 2026-07-30 addendum).
*
* Enforcement is the default. This exists for the operator whose integration
* hits an unforeseen rejection and needs it dispatching again before they can
* reach the caller's code — the violation still logs, so setting this makes the
* drift tolerated, not invisible.
*
* Spelled `OS_ALLOW_*` per Prime Directive #9 and ADR-0110 D6: an opt-OUT of a
* check that ships on, never an opt-IN to a check that ships off.
*/
function laxActionParams(): boolean {
return typeof process !== 'undefined' && process.env?.OS_ALLOW_LAX_ACTION_PARAMS === '1';
}
const _warnedActionParams = new Set<string>();
function warnActionParamsOnce(key: string, message: string): void {
if (_warnedActionParams.has(key)) return;
_warnedActionParams.add(key);
console.warn(message);
}
/**
* The dispatcher facilities the action subsystem may touch.
*
* [#4127 batch 4] `resolveService` is split the same way as the one on
* `DomainHandlerDeps`. This is a NARROWER re-declaration of the same facility
* and it kept returning `any` after the main one stopped — the third copy of
* the pattern, alongside `ResolveOptions` in security/resolve-execution-context.
* A lookup facade has to be typed everywhere it is re-declared, or the copy
* that still says `any` becomes the way around all the others.
*
* [#5155] Both lookups take the REQUEST as their first parameter, for the
* reason spelled out on `DomainHandlerDeps` (of which this is the narrow view
* `HttpDispatcher.actionExecutionDeps` hands out): the object is shared by
* every request the host serves, so the kernel to resolve against is the
* request's, never the facade's.
*/
export interface ActionExecutionDeps {
resolveService<K extends keyof ServiceSlotContracts>(context: HttpProtocolContext, name: K, environmentId?: string): Promise<ServiceSlotContract<K> | undefined>;
resolveService(context: HttpProtocolContext, name: string, environmentId?: string): any;
getObjectQL(context: HttpProtocolContext, environmentId?: string): Promise<IObjectQLEngine | null>;
}
/**
* Direct data service dispatch — replaces broker.call('data.*').
* Tries protocol service first (supports expand/populate), falls back to ObjectQL.
*
* @param requestContext - The request being served (#5155). Carries the kernel
* every service lookup below resolves against; see
* {@link HttpProtocolContext.kernel}.
* @param dataDriver - Optional environment-scoped driver to use instead of kernel default
* @param scopeId - Optional project ID for scoped service resolution (SharedProjectPlugin mode)
*/
/**
* The registered object schema a write mouth in this file applies the
* write-response rules (credential-class mask, `internal` omit) from: the
* engine's live registry first, then the metadata service. `undefined` when
* neither answers — callers FAIL CLOSED on that (echo no record), because an
* unjudged record is exactly the one that may carry a stored credential.
*
* [#22823] It is also the read {@link refuseUnservedRelationTargets} takes, for
* the filtered object's field map and each condition target's `enable` block:
* the engine's own registry first is the schema the engine's relation lowering
* reads. That caller falls OPEN on `undefined`, as the exposure gate does.
*/
export async function resolveWriteResponseSchema(
deps: ActionExecutionDeps,
requestContext: HttpProtocolContext | undefined,
ql: any,
object: string | undefined,
scopeId?: string,
): Promise<unknown> {
if (!object) return undefined;
try {
const fromEngine = ql?.registry?.getObject?.(object);
if (fromEngine) return fromEngine;
} catch {
// fall through to the metadata service
}
try {
const meta = await deps.resolveService(requestContext as HttpProtocolContext, 'metadata', scopeId);
return (await (meta as any)?.getObject?.(object)) ?? undefined;
} catch {
return undefined;
}
}
/**
* [#22823] The runtime action a NESTED-RELATION condition's TARGET is judged as
* by this door's exposure gate: `query`, which the spec's derivation
* (`DATA_ACTION_TO_API_OPERATION`) maps to `list`. A condition is a predicate
* over the whole target — the engine runs `find(target, { where: condition })`
* bounded by a match cap, not by ids the caller holds — which is the read the
* target's own filtered query performs. The data door judges the same target as
* `list` (its own `RELATION_CONDITION_TARGET_OPERATION`, `@objectstack/metadata-protocol`),
* and so does the MCP stdio bridge (`GATED_ACTIONS.query`).
*/
const RELATION_CONDITION_TARGET_ACTION = 'query';
/** The canonical operation that action derives to, named in the refusal. */
const RELATION_CONDITION_TARGET_OPERATION = DATA_ACTION_TO_API_OPERATION[RELATION_CONDITION_TARGET_ACTION];
/**
* [#22823] Census row 10 of #22661. `callData` hands a caller's `where` to the
* ObjectQL ENGINE on two arms: the `query`/`find` fallback that serves when no
* protocol service resolves, and the `aggregate` arm, which never takes the
* protocol. The engine lowers each NESTED-RELATION condition
* (`{ <lookup>: { <field of the related object>: … } }`) by reading the related
* object as the caller (`ObjectQL.lowerRelationConditions`) and keeping the
* rows whose related record matched, so the condition is a predicate over an
* object nobody addressed. The exposure gate at the top of `callData` judges
* only the ADDRESSED object.
*
* So each condition's TARGET is asked the same gate the addressed object is
* asked ({@link checkApiExposure}, for {@link RELATION_CONDITION_TARGET_ACTION}),
* before the engine is called, and a target the gate does not serve REFUSES the
* call. Refused, not withheld: dropping the condition would widen the result.
* The conditions are found by the one walk the data door
* (`refuseUnservedRelationTarget`, #22737) and the MCP stdio bridge
* (`enforceRelationTargetExposure`, #22777) take, `relationConditionSites` from
* `@objectstack/core`, and the refusal is the data door's: the protocol path
* this fallback stands in for answers the same condition `404
* OBJECT_API_DISABLED` / `405 OBJECT_API_METHOD_NOT_ALLOWED`, and one
* `callData` must not give two answers depending on whether the deployment
* registered the protocol slot (the #5138 rule this file already keeps).
*
* `callData` skips it for a system context on the one decision that skips the
* addressed gate: these flags govern API exposure, not the engine's own reads. A schema
* that cannot be resolved finds no condition (the filtered object) or serves
* (a target), the gate's own fail-open.
*/
async function refuseUnservedRelationTargets(
deps: ActionExecutionDeps,
requestContext: HttpProtocolContext,
engine: unknown,
object: string,
where: unknown,
scopeId?: string,
): Promise<void> {
if (where == null || typeof where !== 'object') return;
const schema = await resolveWriteResponseSchema(deps, requestContext, engine, object, scopeId);
const fields = (schema as { fields?: Record<string, any> } | undefined)?.fields;
for (const site of relationConditionSites(fields, where)) {
const target = await resolveWriteResponseSchema(deps, requestContext, engine, site.target, scopeId);
const gate = checkApiExposure(target as ObjectApiDef | undefined, RELATION_CONDITION_TARGET_ACTION);
if (!gate.allowed) throw unservedRelationTargetError(site.target, `where.${site.field}`, gate);
}
}
/**
* [#23528] The data door's two exposure codes, by the gate's verdict: `404
* OBJECT_API_DISABLED` for an object whose `apiEnabled` is `false`, and `405
* OBJECT_API_METHOD_NOT_ALLOWED` with the effective operation set as `allowed`
* for a verb its `apiMethods` leaves out. That is the pairing `RestServer`
* answers for the same declaration (`apiAccessDenialFromEnable`).
*
* The ONE table both exposure refusals in this file stamp: the addressed
* object's ({@link refuseUnexposedDataAction}) and a nested-relation
* condition's target's ({@link unservedRelationTargetError}). One table, so one
* `callData` never answers the same verdict with two codes. A denial from
* {@link checkApiExposure} carries exactly one of these two statuses.
*/
function exposureRefusalFields(gate: ApiExposureDecision):
| { code: 'OBJECT_API_DISABLED'; status: 404 }
| { code: 'OBJECT_API_METHOD_NOT_ALLOWED'; status: 405; allowed: string[] } {
return gate.status === 404
? { code: 'OBJECT_API_DISABLED', status: 404 }
: { code: 'OBJECT_API_METHOD_NOT_ALLOWED', status: 405, allowed: gate.allowedOperations ?? [] };
}
/**
* [#22823] The data door's refusal of an unserved nested-relation condition
* target, field for field (`refuseUnservedRelationTarget`): `code` and `status`
* by the gate's verdict ({@link exposureRefusalFields}), the TARGET as `object`
* (the route's object is not the one switched off), the condition's position
* as `param`, and the effective operation set as `allowed` on a 405.
*/
function unservedRelationTargetError(target: string, param: string, gate: ApiExposureDecision): Error {
const consequence = `, so the condition on it at '${param}' was not evaluated and the query was not run. `
+ 'Filter on the lookup\'s stored id instead, or remove the condition.';
const refusal = exposureRefusalFields(gate);
const message = refusal.status === 404
? `Object '${target}' is not exposed via the API${consequence}`
: `API operation '${RELATION_CONDITION_TARGET_OPERATION}' is not allowed on object '${target}'${consequence}`;
return Object.assign(new Error(message), refusal, { object: target, param });
}
/** The engine for a schema lookup, or `undefined` — a lookup failure is judged by the caller's fail-closed branch. */
async function resolveEngineQuietly(deps: ActionExecutionDeps, requestContext: HttpProtocolContext | undefined, envId?: string): Promise<unknown> {
try {
return (await deps.getObjectQL(requestContext as HttpProtocolContext, envId)) ?? undefined;
} catch {
return undefined;
}
}
/**
* [#25120] The by-name object reads {@link readExposureDeclaration} asks of
* the `protocol` slot, both optional: the slot is unmapped in
* `ServiceSlotContracts`, and a host may fill it with a partial object.
* `getMetaItemForExecution` is the server-only face `RestProtocol` declares the
* same way (`packages/rest/src/rest-server.ts`).
*/
type ExposureDeclarationRead = Partial<Pick<MetadataProtocol, 'getMetaItem'>> & {
getMetaItemForExecution?: MetadataProtocol['getMetaItem'];
};
/**
* [#25120] The definition {@link refuseUnexposedDataAction} judges: the object,
* by name, through the protocol's MERGED read — the read `RestServer`'s own
* exposure gate makes (`enforceApiAccess`), on the execution face where the
* protocol has one (no serving decorations: the gate reads `enable` and serves
* nothing). The metadata service's copy is read only on a host whose protocol
* has no by-name read: structural absence, answered as before.
*
* ── The defect this closes ────────────────────────────────────────────────
*
* This gate read `IMetadataService.getObject(object)`, and an absent copy is
* "no declaration", i.e. allowed. On a kernel with an `environmentId` nothing
* copies into that service the objects a package or a plugin registers in the
* `SchemaRegistry` during the boot, so such an object declared
* `apiEnabled: false` was served: measured on that shape, `query_records`
* answered and `create_record` reached the driver, through the `/mcp` bridge
* and every other door that asks this gate, while `RestServer` refused the
* same object `404 OBJECT_API_DISABLED`. One declaration, two verdicts.
*
* ── Answers, by what the read returns ─────────────────────────────────────
*
* - the item under its own name → judged;
* - nothing, or an item under another name → `undefined`: no declared
* exposure policy, and the data plane's registry gate answers existence
* (#3770), as before;
* - refused `OBJECT_PACKAGE_DISABLED` → that refusal, THROWN
* ({@link isObjectPackageDisabledRefusal}): a refusal, not an outage, so it
* never falls back to the copy. {@link refuseUnexposedDataAction} decides
* who answers it. `RestServer`'s gate reads it as "no declaration"
* (`loadObjectItem`) because every REST data route then reaches the
* protocol, whose registry gate (`assertObjectRegistered`) refuses with that
* same code. `callData`'s `aggregate` arm takes no protocol: it asks the
* engine, which serves a disabled package's objects. So the reading this
* gate first took from REST served `aggregate_records` on such an object,
* one declared `apiEnabled: false` included, where the metadata service's
* copy had refused it `OBJECT_API_DISABLED`;
* - any other throw (the metadata store unreadable) → the metadata service's
* copy, the source this gate read before. An outage of the merged read must
* not WIDEN exposure: failing open at once would serve an object the copy
* still declares off, where this gate refused it before the move. The copy
* can only add a refusal the healthy read would also make or a stale one, never
* an allowance the caller's fail-open `catch` would not already give.
*/
async function readExposureDeclaration(
deps: ActionExecutionDeps,
requestContext: HttpProtocolContext,
object: string,
scopeId?: string,
): Promise<unknown> {
const readCopy = async () => {
const meta = await deps.resolveService(requestContext, 'metadata', scopeId);
return await (meta as any)?.getObject?.(object);
};
const protocol = await deps.resolveService(requestContext, 'protocol', scopeId) as ExposureDeclarationRead | undefined;
const byName = typeof protocol?.getMetaItemForExecution === 'function'
? protocol.getMetaItemForExecution
: typeof protocol?.getMetaItem === 'function' ? protocol.getMetaItem : undefined;
if (!byName) return await readCopy();
let envelope: unknown;
try {
envelope = await byName.call(protocol, { type: 'object', name: object });
} catch (err) {
if (isObjectPackageDisabledRefusal(err)) throw err;
return await readCopy();
}
const item = (envelope as { item?: unknown } | null | undefined)?.item;
return item !== null && typeof item === 'object' && (item as { name?: unknown }).name === object ? item : undefined;
}
/**
* [#25120] Whether `err` is the protocol's refusal of an object whose owning
* package is disabled: the one constructor `@objectstack/metadata-protocol`
* raises from its by-name reads and its data plane (`code`
* `OBJECT_PACKAGE_DISABLED`, `status` 404, `object`). A refusal, not an outage
* and not an absence: {@link readExposureDeclaration} throws it, where every
* other read failure falls back to the copy, and
* {@link refuseUnexposedDataAction} decides who answers it.
*/
function isObjectPackageDisabledRefusal(err: unknown): boolean {
return (err as { code?: unknown } | null)?.code === 'OBJECT_PACKAGE_DISABLED';
}
/**
* [#25296] Throw the protocol's own `404 OBJECT_PACKAGE_DISABLED` when
* `object`'s owning package is disabled, and return otherwise. The question
* the REST `/actions` door asks before it reads an action's declaration: an
* object the data plane refuses has no action that may run, so neither its
* declaration gates nor its handler are reached.
*
* The read is {@link readExposureDeclaration}'s, the by-name object read the
* data verbs' exposure gate makes, and the refusal is the one constructor the
* protocol raises from it and from its data plane: ⛔ never a second copy of
* the package predicate or of the refusal. Any other answer of that read is
* not this gate's to give: an absent object is the declaration resolution's
* to answer, and so is an unreadable metadata plane (ADR-0110 D3), so they
* pass here unanswered.
*/
export async function refuseDisabledPackageObject(deps: ActionExecutionDeps,
requestContext: HttpProtocolContext,
object: string,
scopeId?: string,
): Promise<void> {
try {
await readExposureDeclaration(deps, requestContext, object, scopeId);
} catch (err) {
if (isObjectPackageDisabledRefusal(err)) throw err;
}
}
/**
* ── Object-level API exposure gate (ADR-0049, #1889) ─────
* Honour the object's `apiEnabled` / `apiMethods` declarations for external
* traffic: throws the refusal ({@link checkApiExposure}'s `404` / `405`) when
* `object` does not expose `action`, and returns otherwise. System/internal
* contexts bypass — these flags govern API *exposure*, not internal engine
* self-writes.
*
* [#23574] Extracted from {@link callData}, which still asks it first for
* every caller, so that the runtime dispatcher's `/data` domain can ask the
* SAME question before its own request-schema gate (`domains/data.ts`): a
* caller the object refuses is answered the refusal, never a shape verdict
* about the body it sent. `RestServer` asks `enforceApiAccess` before its
* twin gate for the same reason. Moved, not copied: this is the one place the
* dispatcher's exposure decision is resolved.
*
* [#23528] The refusal is the data door's, as the nested-relation target's
* already was: an `Error` carrying `code` and `status` from
* {@link exposureRefusalFields}, the addressed object as `object`, and
* `allowed` on a 405. It used to throw `{ statusCode, message }` with no code,
* so the dispatcher's `/data` door answered `404 RESOURCE_NOT_FOUND` / `405
* METHOD_NOT_ALLOWED` (codes derived from the status) and the `/mcp` tools
* rendered the message alone, where `RestServer` and the MCP stdio face answer
* the same declaration `OBJECT_API_DISABLED` / `OBJECT_API_METHOD_NOT_ALLOWED`.
* The statuses do not move, and neither does the message.
*
* [#25120] An object whose owning package is disabled, whatever it declares:
* the protocol refuses its by-name read `404 OBJECT_PACKAGE_DISABLED`
* ({@link readExposureDeclaration}), and `disabledPackage` says who answers
* that refusal, so every door answers what `RestServer` answers:
*
* - `'defer'`, the default: the dispatcher's `/data` door, which asks this gate
* BEFORE its request-schema gate as the twin of `RestServer`'s
* `enforceApiAccess`. "No declaration", as `enforceApiAccess` reads it
* (`loadObjectItem`), so a body that is not a record is answered `400
* VALIDATION_FAILED` first, and a well-formed request is refused `404
* OBJECT_PACKAGE_DISABLED` when it reaches {@link callData}, as REST's data
* plane refuses it.
* - `'refuse'`: {@link callData}, which every data door reaches where REST
* reaches the protocol, and which the `/mcp` bridge asks alone. The
* protocol's own error, thrown, on every arm: the `aggregate` arm asks the
* engine and never the protocol, and the engine serves a disabled package's
* objects, so reading the refusal as "no declaration" there served
* `aggregate_records` on such an object, one declared `apiEnabled: false`
* included.
*/
export async function refuseUnexposedDataAction(deps: ActionExecutionDeps,
requestContext: HttpProtocolContext,
action: string,
object: unknown,
scopeId?: string,
executionContext?: ExecutionContext,
disabledPackage: 'defer' | 'refuse' = 'defer',
): Promise<void> {
if (executionContext?.isSystem || !object) return;
let def: any;
try {
def = await readExposureDeclaration(deps, requestContext, String(object), scopeId);
} catch (err) {
// [#25120] The protocol's `404 OBJECT_PACKAGE_DISABLED` is a refusal,
// never a read failure to fall open on: thrown where this gate stands
// in for the data plane, "no declaration" where the data plane follows.
if (isObjectPackageDisabledRefusal(err) && disabledPackage === 'refuse') throw err;
def = undefined; // fall open to schema defaults (apiEnabled=true)
}
const gate = checkApiExposure(def, action);
if (!gate.allowed) {
throw Object.assign(new Error(gate.reason ?? 'API access denied'), exposureRefusalFields(gate), { object });
}
// A write to `sys_api_key` from a principal an API key admitted is refused
// `403 PERMISSION_DENIED`: changing a key is a signed-in-session act, the
// answer `/keys` gives (`@objectstack/core` `apiKeyManagementCredentialRefusal`,
// whose docblock carries the rule). Asked after the exposure verdict, so an
// operation the object does not expose keeps its `405`, and on this gate
// because every data face of this door passes it: `/data`, the `/mcp`
// bridge and the action doors, through {@link callData}. The credential is
// the one the identity step was told (`HttpProtocolContext.admission`);
// a context that carries none keeps today's answer.
const credentialRefusal = apiKeyManagementCredentialRefusal({
object,
operation: action,
credential: requestContext?.admission?.credential,
});
if (credentialRefusal) throw credentialRefusal;
}
/**
* Ask `engine` the `internal: true` evaluate refusal (`QueryEvaluationGate`
* on the `objectql` slot contract, `IObjectQLEngine`) for `object` and
* `query`, for every caller — or nothing, when the value handed in is not an
* engine that carries it (a test double, a foreign engine, the raw driver the
* MCP multi-env path threads through), which then answers for itself.
*/
function assertNoInternalFieldEvaluatedBy(engine: unknown, object: string, query: InternalFieldEvaluationQuery): void {
const gate = (engine as Partial<QueryEvaluationGate> | null | undefined)?.assertNoInternalFieldEvaluated;
if (typeof gate !== 'function') return;
gate.call(engine, object, query);
}
export async function callData(deps: ActionExecutionDeps,
requestContext: HttpProtocolContext,
action: string,
params: any,
dataDriver?: any,
scopeId?: string,
executionContext?: ExecutionContext,
): Promise<any> {
// The object-level API exposure gate ({@link refuseUnexposedDataAction}).
// [#22823] Decided ONCE, here: the same bypass covers each nested-relation
// condition's target, asked below on the two arms that hand the engine a
// caller's `where` ({@link refuseUnservedRelationTargets}).
const exposureGated = !executionContext?.isSystem;
// [#25120] `'refuse'`: a disabled package's object is refused here, on
// every arm, the `aggregate` arm that never reaches the protocol included.
await refuseUnexposedDataAction(deps, requestContext, action, params?.object, scopeId, executionContext, 'refuse');
const protocol = await deps.resolveService(requestContext, 'protocol', scopeId);
const qlService = dataDriver ?? await deps.getObjectQL(requestContext, scopeId);
const ql = qlService ?? await deps.resolveService(requestContext, 'objectql', scopeId);
const qlOpts = executionContext ? { context: executionContext } : undefined;
const findOpts = (extra?: any) => {
const base = qlOpts ? { ...qlOpts } : {};
return extra ? { ...base, ...extra } : (qlOpts ? base : undefined);
};
const writeResponseSchema = () =>
resolveWriteResponseSchema(deps, requestContext, ql, params?.object, scopeId);
if (action === 'create') {
// Prefer the protocol service (validations + RLS + audit), mirroring
// the read paths below. The MCP bridge passes `context.dataDriver` as
// `ql`, which in the multi-env runtime is a RAW db driver with no ORM
// `insert` — so going straight to `ql.insert` broke MCP create_record
// ("ql.insert is not a function") while REST (which uses `createData`)
// worked. Routing writes through the protocol keeps them aligned.
if (protocol && typeof protocol.createData === 'function') {
return await protocol.createData({ object: params.object, data: params.data, ...(scopeId ? { environmentId: scopeId } : {}), context: executionContext });
}
if (ql && typeof ql.insert === 'function') {
// [#28782] A row stored under a parent roll-up the engine could
// not recompute (`ERR_SUMMARY_RECOMPUTE`, "the triggering records
// WERE written") builds this arm's answer from the refusal's
// `written` and carries it on the refusal, as the protocol's
// `createData` does since #28781 (`withEarnedAnswer`), so a door
// reading `earnedAnswerOf` answers the write's success here too.
let stale: SummaryRecomputeRefusal | undefined;
const res = await ql.insert(params.object, params.data, qlOpts)
.catch((e: unknown) => (stale = staleSummaryRefusalOrThrow(e)).written as any);
const record = { ...params.data, ...res };
// The engine's write result keeps the stored row whole, so this
// fallback mouth owes the same write-response rules the protocol
// ingress applies (credential-class mask, `internal` omit).
// Fail closed: with no schema to judge the fields by, no record
// is echoed at all — only the receipt.
const schema = await writeResponseSchema();
if (!schema) {
const receipt = { object: params.object, id: record.id };
if (stale) throw withEarnedAnswer(stale, receipt);
return receipt;
}
omitInternalFieldsFromWriteResponse(schema, record);
const answer = { object: params.object, id: record.id, record };
if (stale) throw withEarnedAnswer(stale, answer);
return answer;
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'get') {
if (protocol && typeof protocol.getData === 'function') {
return await protocol.getData({ object: params.object, id: params.id, expand: params.expand, select: params.select, context: executionContext });
}
if (ql) {
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const match = (all as any[]).find((i: any) => i.id === params.id);
// [#5138] Was `: null` — a miss resolved, and `/data` wrapped it as
// `200 { data: null }`. The protocol path this falls back from has
// answered `404 RECORD_NOT_FOUND` since #4435, so the same GET
// answered 200 or 404 depending only on whether the deployment
// registered the protocol slot — a difference the caller cannot see
// and never asked for.
if (!match) throw recordNotFoundError(params.object, params.id);
return { object: params.object, id: params.id, record: match };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'update') {
// [#23462] `expectedVersion` rides through to `updateData`, whose
// version check refuses a stale update. This arm forwarded only
// `{ object, id, data }`, so a token the `/data` domain read was
// dropped here a second time. Present only when a caller sent one:
// every other caller hands `{ object, id, data }` and reaches
// `updateData` as before. The `delete` arm below does the same.
const expectedVersion = params?.expectedVersion;
if (protocol && typeof protocol.updateData === 'function') {
return await protocol.updateData({
object: params.object,
id: params.id,
data: params.data,
...(expectedVersion !== undefined ? { expectedVersion } : {}),
...(scopeId ? { environmentId: scopeId } : {}),
context: executionContext,
});
}
// [#23462] The fallback below updates by id and nothing else, so it
// cannot judge a version. A caller who sent one is refused `501`
// before anything is read, never updated unguarded: that is the very
// drop the arm above just closed. The `delete` arm's fallback refuses
// it the same way.
if (expectedVersion !== undefined) {
throw {
statusCode: 501,
message: 'This host has no protocol updateData, so it cannot honour expectedVersion or If-Match on an '
+ 'update. Send the update without them, or update through a host whose protocol implements updateData.',
};
}
if (ql && params.id && typeof ql.update === 'function') {
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const existing = (all as any[]).find((i: any) => i.id === params.id);
// [#5138] Was `throw new Error('[ObjectStack] Not Found')`. That
// error carried neither `.status` nor `.statusCode`, so BOTH
// dispatcher exits fell through to their 500 fallback
// (`HttpDispatcher.errorFromThrown`, `dispatcher-plugin`'s
// `errorResponseBase`, and the endpoint executor's `errorAnswer`
// all read `.status` → `.statusCode` → 500). A caller mistake was
// reported as an internal fault and taken to the error reporter
// with it.
if (!existing) throw recordNotFoundError(params.object, params.id);
// [#28782] The create arm's carrier, for an update that landed.
let stale: SummaryRecomputeRefusal | undefined;
await ql.update(params.object, params.data, findOpts({ where: { id: params.id } }))
.catch((e: unknown) => { stale = staleSummaryRefusalOrThrow(e); });
const record = { ...existing, ...params.data };
// The echo carries the caller's own patch: a credential-class value
// in it is masked like a read of the stored row would be. Fail
// closed, as on create: no schema ⇒ the receipt only.
const schema = await writeResponseSchema();
if (!schema) {
const receipt = { object: params.object, id: params.id };
if (stale) throw withEarnedAnswer(stale, receipt);
return receipt;
}
omitInternalFieldsFromWriteResponse(schema, record);
const answer = { object: params.object, id: params.id, record };
if (stale) throw withEarnedAnswer(stale, answer);
return answer;
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'delete') {
// [#23265] `expectedVersion` rides through to `deleteData`, whose
// version check refuses a stale delete. This arm forwarded only
// `{ object, id }`, so a token the `/data` domain read was dropped here
// a second time. Present only when a caller sent one: every other
// caller hands `{ object, id }` and reaches `deleteData` as before.
const expectedVersion = params?.expectedVersion;
if (protocol && typeof protocol.deleteData === 'function') {
return await protocol.deleteData({
object: params.object,
id: params.id,
...(expectedVersion !== undefined ? { expectedVersion } : {}),
...(scopeId ? { environmentId: scopeId } : {}),
context: executionContext,
});
}
// [#23265] The fallback below deletes by id and nothing else, so it
// cannot judge a version. A caller who sent one is refused `501`
// before anything is read, never deleted unguarded: that is the very
// drop the arm above just closed. The `/meta` save refuses a
// precondition its fallback writer cannot honour the same way.
if (expectedVersion !== undefined) {
throw {
statusCode: 501,
message: 'This host has no protocol deleteData, so it cannot honour ?expectedVersion or If-Match on a '
+ 'delete. Send the delete without them, or delete through a host whose protocol implements deleteData.',
};
}
if (ql && typeof ql.delete === 'function') {
// [#5138] There was NO existence check here: the delete ran and the
// answer was `200 { deleted: true }` for any string in the path, so
// a typo'd id, an already-deleted row and a real deletion were
// indistinguishable — the exact shape #4435 removed from the
// protocol's `deleteData`, still live on the path that stands in
// for it. The "assume it worked" answer is the worst of the three
// this fallback gave, because an integrator reading 200 records the
// cleanup as done.
//
// The existence PROBE is a `find`, not a read of what `ql.delete`
// returned. `deleteData` can read its result because `IDataDriver.
// delete` declares `Promise<boolean>` ("true if deleted, false if
// not found"); `ql` here is the ObjectQL ENGINE (or, on the MCP
// multi-env path, a raw driver), and `IDataEngine.delete` declares
// `Promise<any>` — the engine passes its driver's result through
// the hook chain and returns `opCtx.result`. Testing that for
// `=== false` would be reading a signal the contract does not
// promise, which fails silently in the direction this issue is
// about: back to reporting a delete that removed nothing. The probe
// is the same one the sibling `get`/`update` fallbacks already run.
let all = await ql.find(params.object, findOpts({ where: { id: params.id }, limit: 1 }));
if (all && (all as any).value) all = (all as any).value;
if (!all) all = [];
const existing = (all as any[]).find((i: any) => i.id === params.id);
if (!existing) throw recordNotFoundError(params.object, params.id);
// [#28782] The create arm's carrier, for a delete that landed.
let stale: SummaryRecomputeRefusal | undefined;
await ql.delete(params.object, findOpts({ where: { id: params.id } }))
.catch((e: unknown) => { stale = staleSummaryRefusalOrThrow(e); });
// [#5581] `success`, not `deleted`. The success body was the other
// half of the same "one `callData`, two answers" defect #5138 fixed
// on the not-found side: the protocol path returns the SPEC's shape
// (`DeleteDataResponseSchema` — `{ object, id, success }`,
// `packages/spec/src/api/protocol.zod.ts:472`) and this fallback
// returned `{ object, id, deleted: true }` — `success` missing, and
// `deleted` declared nowhere in the spec. A client written against
// the declared shape read `success === undefined` off an HTTP 200
// on any deployment that did not register the `protocol` slot, and
// had no way to tell which path had served it.
//
// The spec is the authority, not this literal: `success` is what
// `DeleteDataResponseSchema` declares, what the protocol path has
// returned since #4435, and what the public HTTP docs already
// document (`content/docs/protocol/kernel/http-protocol.mdx`).
// Teaching consumers to read `success ?? deleted` would have been
// the contract-first-forbidden shape — two spellings of one fact,
// kept alive by every reader.
const answer = { object: params.object, id: params.id, success: true };
if (stale) throw withEarnedAnswer(stale, answer);
return answer;
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'query' || action === 'find') {
// Build query: use explicit params.query if provided, otherwise extract
// query fields from params. Shared by both paths below — the fallback
// must serve the SAME request the protocol path would have served.
const query = params.query || (() => {
const { object, ...rest } = params;
return rest;
})();
if (protocol && typeof protocol.findData === 'function') {
return await protocol.findData({ object: params.object, query, context: executionContext });
}
if (ql) {
// [#4386] This fallback used to pass only `{ context }` — the
// caller's entire query (where/orderBy/limit/…) was dropped and the
// FULL table came back as an ordinary-looking `{ records, total }`.
// Serve the canonical QueryAST keys both possible recipients
// actually execute (`ql` here is the engine, or on the MCP
// multi-env path a RAW driver reading a QueryAST — same canonical
// keys by design). Anything else — wire spellings (`sort`,
// `select`, …) that need the protocol layer's fold/lowering, or
// capabilities a raw driver would silently drop (`search`,
// `expand`) — is refused loudly rather than part-served: a
// fallback that cannot reproduce the query's semantics must not
// pretend to (route-ownership rule 3).
const FALLBACK_QUERY_KEYS = ['where', 'fields', 'orderBy', 'limit', 'offset'];
const bag: any = {};
const unservable: string[] = [];
for (const [k, v] of Object.entries((query ?? {}) as Record<string, unknown>)) {
if (v == null) continue;
// `context` is SERVER-derived on this path, same as findData's
// unconditional `delete options.context` — a caller-supplied
// one is dropped, never an error and never honoured.
if (k === 'context') continue;
if (FALLBACK_QUERY_KEYS.includes(k)) bag[k] = v;
else unservable.push(k);
}
if (unservable.length > 0) {
throw {
statusCode: 501,
message: `Data query fallback cannot serve ${unservable.map((k) => `'${k}'`).join(', ')}: ` +
'the protocol service (metadata-protocol plugin) is not registered, and without its ' +
`normalization this path serves only canonical QueryAST keys (${FALLBACK_QUERY_KEYS.join(', ')}).`,
};
}
// [#22823] …and each nested-relation condition's TARGET, before the
// engine reads it — the protocol path asks the same of the same
// sites (`refuseUnservedRelationTarget`).
if (exposureGated) {
await refuseUnservedRelationTargets(deps, requestContext, ql, params.object, bag.where, scopeId);
}
// …and the `internal: true` evaluate refusal for every caller, as
// the protocol path asks it inside `findData` — the engine's one
// definition (see the `aggregate` arm). A raw driver on the MCP
// multi-env path carries no such member and is not an engine.
assertNoInternalFieldEvaluatedBy(ql, params.object, bag);
let all = await ql.find(params.object, findOpts(bag));
if (!Array.isArray(all) && all && (all as any).value) all = (all as any).value;
if (!all) all = [];
return { object: params.object, records: all, total: all.length };
}
throw { statusCode: 503, message: 'Data service not available' };
}
if (action === 'aggregate') {
// Aggregate MUST run through the ObjectQL ENGINE (never the raw
// `dataDriver` the MCP bridge threads through for the other verbs):
// only the engine's middleware chain injects RLS/tenant scoping and
// the FLS aggregate-input gate. A raw driver.aggregate() would
// evaluate the query verbatim over every row.
//
// At least one aggregation is REQUIRED: with neither aggregations
// nor groupBy the engine's in-memory path degrades to raw rows,
// and the FLS result masker does not cover the `aggregate` op —
// grouped/aggregated output must stay the only thing this action
// can ever return.
if (!Array.isArray(params.aggregations) || params.aggregations.length === 0) {
throw { statusCode: 400, message: 'aggregate requires at least one aggregation' };
}
const engine = (await deps.getObjectQL(requestContext, scopeId))
?? await deps.resolveService(requestContext, 'objectql', scopeId).catch(() => null);
if (engine && typeof engine.aggregate === 'function') {
// [#22823] This arm runs on no protocol data method, so it is the engine's door on
// every assembly: each nested-relation condition's TARGET in `where`
// is asked before the engine aggregates, as the query fallback asks
// it (the engine lowers relation conditions in `where` only, never
// in an aggregation's own `filter`).
if (exposureGated) {
await refuseUnservedRelationTargets(deps, requestContext, engine, params.object, params.where, scopeId);
}
// The `internal: true` evaluate refusal — a filter (`where`, an
// aggregation's own `filter`), a group key or an aggregation operand
// on such a field — asked of the ENGINE's one definition
// (`QueryEvaluationGate` on the `objectql` slot contract), the one
// the data door asks too, so the refusal is the door's word for
// word whether or not this host registers a `protocol` service.
// `engine.aggregate` applies it itself to every non-system caller;
// it is asked here as well so a system context this arm admits is
// refused like every caller at the door. ⛔ Never a copy of the
// walk here (route-ownership rule 1). The probe tolerates a test
// double or foreign engine without the member, which then answers
// for itself.
assertNoInternalFieldEvaluatedBy(engine, params.object, {
where: params.where,
groupBy: params.groupBy,
aggregations: params.aggregations,
});
const rows = await engine.aggregate(
params.object,
{
...(params.where ? { where: params.where } : {}),
...(params.groupBy ? { groupBy: params.groupBy } : {}),
...(params.aggregations ? { aggregations: params.aggregations } : {}),
...(params.timezone ? { timezone: params.timezone } : {}),
...(executionContext ? { context: executionContext } : {}),
},
);
return { object: params.object, rows: rows ?? [] };
}
throw { statusCode: 503, message: 'Data service not available' };
}
// [#5856] `batch` deliberately has NO arm here. It used to answer
// `{ object, results: [] }` — an HTTP 200 whose body a consumer cannot
// tell apart from "the batch ran and matched nothing" — on a path that
// opened no transaction and wrote nothing. Its safety was never its own:
// no caller of `callData` can spell `batch` (`domains/data.ts` compares
// `parts[1]` against the literal `'query'`; `domains/mcp.ts`,
// `domains/actions.ts` and `invokeBusinessAction` pass literals; the
// declarative endpoint executor is bounded by
// `ApiEndpointSchema.objectParams.operation`, a closed enum of
// find/get/create/update/delete; and `callData` is not part of this
// package's export surface), so the arm's only live effect was to
// pre-decide — wrongly — what the FIRST caller to arrive would get:
// a silent success where every other unhandled action gets a loud
// refusal. Removed under ADR-0049 enforce-or-remove, so `batch` falls to
// the same 400 as any other unknown action. Batching itself is untouched
// and keeps its ONE owner (route-ownership rule 1): both the atomic
// cross-object `POST /batch` and the per-object `POST /data/:object/batch`
// are mounted by `@objectstack/rest`'s `registerBatchEndpoints`
// (ADR-0119) — which is exactly why this dispatcher answers
// `capabilities.transactionalBatch: false` (#5672,
// `http-dispatcher.ts`). Pinned by
// `action-execution-calldata-batch-retired.test.ts`.
throw { statusCode: 400, message: `Unknown data action: ${action}` };
}
/**
* [ADR-0066 D4] Shared capability gate for an action invocation. Returns a
* human-readable error string when the caller's `systemPermissions` don't
* cover the action's declared `requiredPermissions`, or `null` when allowed.
* System/engine self-invocation (`isSystem`) bypasses; an action without
* `requiredPermissions` is ungated. Single-sourced so the REST `/actions/...`
* route and the MCP `run_action` bridge enforce the SAME declaration.
*/
export function actionPermissionError(_deps: ActionExecutionDeps, actionDef: any, ec: any, objectName?: string): string | null {
const required: string[] = Array.isArray(actionDef?.requiredPermissions)
? actionDef.requiredPermissions
: [];
if (required.length === 0) return null;
if (ec?.isSystem) return null;
const missing = missingCapabilities(required, ec);
if (missing.length === 0) return null;
const on = objectName ? ` on '${objectName}'` : '';
return (
`Action '${actionDef?.name ?? 'unknown'}'${on} requires capability ` +
`[${required.join(', ')}] — caller is missing [${missing.join(', ')}]`
);
}
/**
* [ADR-0126 §8 item 2] The activation refusal a DISABLED packaged action is
* answered with — `409 ACTION_DISABLED`.
*
* ## Why 409, and why its own code
*
* The artifact exists and is well-formed; only its current STATE conflicts with
* running it, and flipping the switch makes the identical request succeed —
* 409's meaning, and the same reading `FLOW_DISABLED` got in the #9378 table.
* The code is the action's own rather than a borrowed `FLOW_DISABLED`: a
* `script` action refused under a code naming a flow would send an operator
* looking for a flow that does not exist, and a machine-readable surface must
* not lie about which artifact it is talking about (Route & surface ownership
* rule 4). It joins the `*_DISABLED` family already registered in the ADR-0112
* ledger (`FLOW_DISABLED`, `OBJECT_API_DISABLED`, `OBJECT_PACKAGE_DISABLED`) —
* one census row, no new condition class.
*/
export const ACTION_DISABLED_CODE = 'ACTION_DISABLED';
export const ACTION_DISABLED_STATUS = 409;