@aooth/arbac-moost 0.2.3 → 0.2.5

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.
@@ -1,4 +1,4 @@
1
- import { r as AoothArbacClaims, t as ArbacUserProvider } from "../user.provider-BbYgv9RC.mjs";
1
+ import { r as AoothArbacClaims, t as ArbacUserProvider } from "../user.provider-BSEBh1px.mjs";
2
2
  import { TAtscriptAnnotatedType, TAtscriptTypeObject, TMetadataMap, TValidatorOptions, Validator } from "@atscript/typescript/utils";
3
3
  import { AoothUserCredentials } from "@aooth/user/atscript-db/model.as";
4
4
  /**
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { _ as ProjectionOf, a as conjoinArbacDbScopes, b as TArbacMeta, c as ArbacDbScope, d as extractUsedControlValues, f as applyAllowedFieldsAndSet, g as OwnFieldKey, h as NavTarget, i as ConjoinArbacDbScopesOptions, l as AsArbacDbController, m as NavRelationKey, n as ArbacUserProviderToken, o as RefForeignKey, p as ControlsOf, r as AoothArbacClaims, s as RefTableSource, t as ArbacUserProvider, u as enforceControlsPolicy, v as ARBAC_DELEGATED_AUTH, x as getArbacMate, y as ArbacDelegatedAuth } from "./user.provider-BbYgv9RC.mjs";
1
+ import { _ as ProjectionOf, a as conjoinArbacDbScopes, b as TArbacMeta, c as ArbacDbScope, d as extractUsedControlValues, f as applyAllowedFieldsAndSet, g as OwnFieldKey, h as NavTarget, i as ConjoinArbacDbScopesOptions, l as AsArbacDbController, m as NavRelationKey, n as ArbacUserProviderToken, o as RefForeignKey, p as ControlsOf, r as AoothArbacClaims, s as RefTableSource, t as ArbacUserProvider, u as enforceControlsPolicy, v as ARBAC_DELEGATED_AUTH, x as getArbacMate, y as ArbacDelegatedAuth } from "./user.provider-BSEBh1px.mjs";
2
2
  import { Arbac, Arbac as Arbac$1, TArbacCompiledRule, TArbacEvalResult, TArbacEvalResult as TArbacEvalResult$1, TArbacRole, TArbacRoleForResource, TArbacRule, arbacPatternToRegex } from "@aooth/arbac-core";
3
3
  import { ControlGate, ControlGate as ControlGate$1, TProjection, TScopeFieldRules, TScopeFilter, conjoinScopeFilters } from "@aooth/arbac";
4
- import { TAuthGuardDef } from "@moostjs/event-http";
5
4
  import { EventContext } from "@wooksjs/event-core";
5
+ import { HttpError, TAuthGuardDef } from "@moostjs/event-http";
6
6
  import { FilterExpr, TDbRemoveGuardContext, TDbWriteCheckContext, TDbWriteGuardContext, TDeleteOptions, TMetaResponse, TRowResolveOptions, TWriteOptions, UniqueryControls } from "@atscript/db";
7
7
  import { AsDbReadableController, AsJsonValueHelpController, AsValueHelpController, TDbActionScopeContext, TDbControlsType, TDbIndexFieldPaths, TDbRequestContext, ValueHelpSelect } from "@atscript/moost-db";
8
8
  import { TAtscriptAnnotatedType, TAtscriptDataType, TSerializedAnnotatedType } from "@atscript/typescript/utils";
@@ -328,6 +328,37 @@ export declare const ArbacResource: (name: string) => MethodDecorator & ClassDec
328
328
  * at the method level.
329
329
  */
330
330
  export declare const ArbacAction: (name: string) => MethodDecorator & ClassDecorator & ParameterDecorator & PropertyDecorator;
331
+ /**
332
+ * Code-keyed English templates of the `HttpError`s arbac-moost raises. Each
333
+ * error body carries the `code` and its `params`; `MoostHttp` translates it
334
+ * by code with the moost translator (`translateErrorBody`). Registered with
335
+ * `registerMessages` on import.
336
+ *
337
+ * Not coded: the 404 a row outside the caller's scope answers — it is the
338
+ * same answer as a missing row on purpose.
339
+ */
340
+ export declare const ARBAC_MESSAGES: {
341
+ /** 403 — the authorize interceptor denied the handler. Params: `resource`, `action`. */
342
+ readonly INSUFFICIENT_PRIVILEGES: "Insufficient privileges for action \"{action}\" on resource \"{resource}\"";
343
+ /** 403 — `useArbac().evaluateOrThrow()` denied. Params: `resource`, `action`. */
344
+ readonly ARBAC_FORBIDDEN: "Forbidden: {resource}/{action}";
345
+ /** 401 — the authorize interceptor could not evaluate the caller (e.g. unknown user). */
346
+ readonly ARBAC_NOT_AUTHORIZED: "Not authorized";
347
+ /** 403 — a query control the role's `controls` gate denies. Params: `control`. */
348
+ readonly CONTROL_NOT_ALLOWED: "Control \"{control}\" is not allowed for your role";
349
+ /** 403 — a value outside the role's `controls` whitelist. Params: `control`, `value`. */
350
+ readonly CONTROL_VALUE_NOT_ALLOWED: "Control \"{control}={value}\" is not allowed for your role";
351
+ /** 403 — a write through a relation no scope lists in `nestedWrites`. Params: `relation`. */
352
+ readonly NESTED_WRITE_NOT_ALLOWED: "Nested writes through \"{relation}\" are not allowed";
353
+ /** 403 — a written row fails the scope `check` (WITH CHECK). */
354
+ readonly ROW_OUT_OF_SCOPE: "Row outside your write scope";
355
+ /** 403 — a foreign key the write sets points at a row outside the caller's read scope. Params: `fields`. */
356
+ readonly REFERENCE_OUT_OF_SCOPE: "Referenced row \"{fields}\" is outside your scope";
357
+ /** 400 — the query string does not parse. Params: `error` (the parser's text). */
358
+ readonly INVALID_QUERY_STRING: "Invalid query string: {error}";
359
+ };
360
+ /** A code of {@link ARBAC_MESSAGES}. */
361
+ type ArbacMessageCode = keyof typeof ARBAC_MESSAGES;
331
362
  type TSelect = UniqueryControls["$select"];
332
363
  /**
333
364
  * Read-only mirror of {@link AsArbacDbController} for view-style controllers
@@ -615,9 +646,41 @@ export declare function isScopedFieldVisible(scopes: ArbacDbScope[], path: strin
615
646
  * caller's readable rows match the query; the action itself is authorized
616
647
  * by its source controller on every batch.
617
648
  *
649
+ * A read endpoint (`query`, `pages`, `geo`, `one`) under a moost-db write
650
+ * handler (`insert`, `update`, `replace`, `remove`, `removeComposite`) is
651
+ * served only inside {@link readBackUnderReadGrant} (since 0.2.4), under the
652
+ * read grant it installs — otherwise a 403, never the write grant. moost-db's
653
+ * insert read-back (`Prefer: return=representation`) then answers the plain
654
+ * insert result.
655
+ *
618
656
  * @since 0.1.72
619
657
  */
620
658
  export declare function prepareArbacRequest(ctx: TDbRequestContext, readable?: VisibilityTableSource): Promise<void>;
659
+ /**
660
+ * Read back the row `id` after a write, exactly as `GET /one/:id` would
661
+ * answer the caller (since 0.2.4) — the body of
662
+ * `AsArbacDbController._readRepresentation`, and the way for a write handler
663
+ * override to answer the written row:
664
+ *
665
+ * ```ts
666
+ * await super.update(payload);
667
+ * return readBackUnderReadGrant(id, () => this.getOne(String(id), ""));
668
+ * ```
669
+ *
670
+ * `read` calls the controller's `/one` handler: `getOne` for a scalar `id`,
671
+ * `getOneComposite` for a key object. The caller's grant on that handler is
672
+ * evaluated (its `@ArbacResource` / `@ArbacAction`, credential attenuation
673
+ * included) and installed as the request's scopes while `read` runs — its
674
+ * row filter, projection and controls apply, and an overridden handler body
675
+ * runs too — then the write's scopes are restored.
676
+ *
677
+ * Answers `undefined` instead of the row when: the caller has no grant on
678
+ * that handler; the handler carries method-level interceptors (they would
679
+ * not run on a direct call); `read` answers or throws an `HttpError` (e.g.
680
+ * the row is outside the read filter → 404); or anything else fails (logged
681
+ * as a warning, never answered — the write is already committed).
682
+ */
683
+ export declare function readBackUnderReadGrant<R>(id: unknown, read: () => Promise<R>): Promise<Exclude<R, HttpError> | undefined>;
621
684
  /**
622
685
  * `authorizeForm` for the ARBAC DB controllers: a form is served iff the
623
686
  * caller may run at least one of the actions that take it as input — each
@@ -932,4 +995,4 @@ export declare class MoostArbac<TUserAttrs extends object, TScope extends object
932
995
  /** The registered custom scope field rules. @since 0.1.72 */
933
996
  getScopeFields(): TScopeFieldRules<TScope>;
934
997
  }
935
- export { ARBAC_DELEGATED_AUTH, type AoothArbacClaims, Arbac, ArbacDbScope, type ArbacDbScopeHelpers, ArbacDelegatedAuth, type ArbacGuardedTable, type ArbacRelationResolution, type ArbacScopedTable, ArbacUserProvider, ArbacUserProviderToken, type ArbacWriteTable, AsArbacDbController, type ConjoinArbacDbScopesOptions, type ControlGate, type ControlsOf, type MetaVisibility, type NavRelationKey, type NavTarget, type OwnFieldKey, type ProjectionOf, type RefForeignKey, type RefTableSource, type ScopeVisibilityOptions, type TArbacCompiledRule, type TArbacEvalResult, TArbacMeta, type TArbacRole, type TArbacRoleForResource, type TArbacRule, type VisibilityTableSource, applyAllowedFieldsAndSet, arbacPatternToRegex, conjoinArbacDbScopes, conjoinScopeFilters, enforceControlsPolicy, extractUsedControlValues, getArbacMate };
998
+ export { ARBAC_DELEGATED_AUTH, type AoothArbacClaims, Arbac, ArbacDbScope, type ArbacDbScopeHelpers, ArbacDelegatedAuth, type ArbacGuardedTable, type ArbacMessageCode, type ArbacRelationResolution, type ArbacScopedTable, ArbacUserProvider, ArbacUserProviderToken, type ArbacWriteTable, AsArbacDbController, type ConjoinArbacDbScopesOptions, type ControlGate, type ControlsOf, type MetaVisibility, type NavRelationKey, type NavTarget, type OwnFieldKey, type ProjectionOf, type RefForeignKey, type RefTableSource, type ScopeVisibilityOptions, type TArbacCompiledRule, type TArbacEvalResult, TArbacMeta, type TArbacRole, type TArbacRoleForResource, type TArbacRule, type VisibilityTableSource, applyAllowedFieldsAndSet, arbacPatternToRegex, conjoinArbacDbScopes, conjoinScopeFilters, enforceControlsPolicy, extractUsedControlValues, getArbacMate };
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  import { i as __decorate, n as ArbacUserProvider, r as ArbacUserProviderToken, t as __decorateMetadata } from "./decorateMetadata-BqEexuhv.mjs";
2
2
  import { Arbac, Arbac as Arbac$1, arbacPatternToRegex } from "@aooth/arbac-core";
3
3
  import { DB_SCOPE_KEYS, DENY_FILTER, ScopeFieldConfigError, applyScopeFieldFilters, conjoinScopeFilters, conjoinScopeFilters as conjoinScopeFilters$1, conjoinScopes, effectiveScope, expandExcludeToLeaves, getProjectionMode, intersectEnabled, isFieldAllowed, needsInheritedConjunction, normalizeScopes, restrictProjection, stableKey, unionOutcomes } from "@aooth/arbac";
4
- import { Authenticate, HttpError } from "@moostjs/event-http";
5
4
  import { cached, cachedBy, current, eventTypeKey, key, tryGetCurrent } from "@wooksjs/event-core";
6
- import { Inherit, Injectable, TInterceptorPriority, defineBeforeInterceptor, getConstructor, getMoostMate, useControllerContext, useLogger } from "moost";
5
+ import { Inherit, Injectable, TInterceptorPriority, defineBeforeInterceptor, formatMessage, getConstructor, getMoostMate, registerMessages, useControllerContext, useLogger } from "moost";
6
+ import { Authenticate, HttpError } from "@moostjs/event-http";
7
7
  import { computeInsights, containsRelationFilter, findAncestorInSet, getPath, hasRelationOp, isPlainObject, isRelationOp, translateQueryTree } from "@atscript/db";
8
8
  import { AsDbController, AsDbReadableController, AsJsonValueHelpController, AsValueHelpController, DB_CRUD_HANDLERS, VALUE_HELP_CRUD_HANDLERS, badRequest, discoverRowLevelActions, getControllerFormType, getDbEndpoint, hasActionDelegations, resolveTerminalRef, stableMeta } from "@atscript/moost-db";
9
9
  import { groupByFields, walkFilter } from "@uniqu/core";
@@ -21,6 +21,15 @@ function getOrCreate(map, key, create) {
21
21
  function hasSelfOrAncestor(set, path) {
22
22
  return set.has(path) || findAncestorInSet(path, set) !== void 0;
23
23
  }
24
+ /**
25
+ * A key object (a composite id, read by `getOneComposite`) — a plain object.
26
+ * A class instance such as a MongoDB `ObjectId` is a scalar id: `String(id)`.
27
+ */
28
+ function isKeyObject(id) {
29
+ if (id === null || typeof id !== "object") return false;
30
+ const proto = Object.getPrototypeOf(id);
31
+ return proto === Object.prototype || proto === null;
32
+ }
24
33
  /** A patch (`update` / `updateMany`) — only the keys it carries are written. */
25
34
  function isPatchAction(action) {
26
35
  return action === "update" || action === "updateMany";
@@ -502,6 +511,45 @@ function requestRelations(readable) {
502
511
  const stored = ctx.has(requestRelationsKey) ? ctx.get(requestRelationsKey) : void 0;
503
512
  return stored && stored.readable === readable ? stored.relations : void 0;
504
513
  }
514
+ // src/messages.ts
515
+ /**
516
+ * Code-keyed English templates of the `HttpError`s arbac-moost raises. Each
517
+ * error body carries the `code` and its `params`; `MoostHttp` translates it
518
+ * by code with the moost translator (`translateErrorBody`). Registered with
519
+ * `registerMessages` on import.
520
+ *
521
+ * Not coded: the 404 a row outside the caller's scope answers — it is the
522
+ * same answer as a missing row on purpose.
523
+ */
524
+ const ARBAC_MESSAGES = {
525
+ /** 403 — the authorize interceptor denied the handler. Params: `resource`, `action`. */
526
+ INSUFFICIENT_PRIVILEGES: "Insufficient privileges for action \"{action}\" on resource \"{resource}\"",
527
+ /** 403 — `useArbac().evaluateOrThrow()` denied. Params: `resource`, `action`. */
528
+ ARBAC_FORBIDDEN: "Forbidden: {resource}/{action}",
529
+ /** 401 — the authorize interceptor could not evaluate the caller (e.g. unknown user). */
530
+ ARBAC_NOT_AUTHORIZED: "Not authorized",
531
+ /** 403 — a query control the role's `controls` gate denies. Params: `control`. */
532
+ CONTROL_NOT_ALLOWED: "Control \"{control}\" is not allowed for your role",
533
+ /** 403 — a value outside the role's `controls` whitelist. Params: `control`, `value`. */
534
+ CONTROL_VALUE_NOT_ALLOWED: "Control \"{control}={value}\" is not allowed for your role",
535
+ /** 403 — a write through a relation no scope lists in `nestedWrites`. Params: `relation`. */
536
+ NESTED_WRITE_NOT_ALLOWED: "Nested writes through \"{relation}\" are not allowed",
537
+ /** 403 — a written row fails the scope `check` (WITH CHECK). */
538
+ ROW_OUT_OF_SCOPE: "Row outside your write scope",
539
+ /** 403 — a foreign key the write sets points at a row outside the caller's read scope. Params: `fields`. */
540
+ REFERENCE_OUT_OF_SCOPE: "Referenced row \"{fields}\" is outside your scope",
541
+ /** 400 — the query string does not parse. Params: `error` (the parser's text). */
542
+ INVALID_QUERY_STRING: "Invalid query string: {error}"
543
+ };
544
+ registerMessages(ARBAC_MESSAGES);
545
+ /** An `HttpError` with `code`, `params` and the code's English text. */
546
+ function arbacHttpError(status, code, params) {
547
+ return new HttpError(status, {
548
+ message: formatMessage(ARBAC_MESSAGES[code], params),
549
+ code,
550
+ ...params && { params }
551
+ });
552
+ }
505
553
  // src/db/write-refs.ts
506
554
  /**
507
555
  * The FK a `checkRefs` entry designates: one of its local fields, or the TO
@@ -560,7 +608,7 @@ function readPath(row, path) {
560
608
  return path in row ? row[path] : getPath(row, path);
561
609
  }
562
610
  function outOfScope(fk) {
563
- return new HttpError(403, `Referenced row "${fk.fields.join(", ")}" is outside your scope`);
611
+ return arbacHttpError(403, "REFERENCE_OUT_OF_SCOPE", { fields: fk.fields.join(", ") });
564
612
  }
565
613
  /** A patch row touches `fk` in part only — its tuple is completed from the pre-image. */
566
614
  function needsPreImage(row, fk) {
@@ -853,7 +901,10 @@ function scopesOwnedBy(scopes, resource, action) {
853
901
  }
854
902
  /** The 403 every ARBAC deny answers. */
855
903
  function insufficientPrivileges(resource, action) {
856
- return new HttpError(403, `Insufficient privileges for action "${action}" on resource "${resource}"`);
904
+ return arbacHttpError(403, "INSUFFICIENT_PRIVILEGES", {
905
+ action,
906
+ resource
907
+ });
857
908
  }
858
909
  async function loadPrincipal(user) {
859
910
  const userId = await user.getUserId();
@@ -1039,11 +1090,10 @@ const useArbac = (_ctx) => {
1039
1090
  };
1040
1091
  const evaluateOrThrow = async (opts) => {
1041
1092
  const result = await evaluate(opts);
1042
- if (!result.allowed) {
1043
- const r = opts?.resource || resource;
1044
- const a = opts?.action || action;
1045
- throw new HttpError(403, `Forbidden: ${r}/${a}`);
1046
- }
1093
+ if (!result.allowed) throw arbacHttpError(403, "ARBAC_FORBIDDEN", {
1094
+ resource: opts?.resource || resource,
1095
+ action: opts?.action || action
1096
+ });
1047
1097
  return {
1048
1098
  ...result,
1049
1099
  allowed: true
@@ -1118,7 +1168,7 @@ const arbacAuthorizeInterceptor = Object.assign(defineBeforeInterceptor(async ()
1118
1168
  } catch (error) {
1119
1169
  if (error instanceof HttpError) throw error;
1120
1170
  logger.warn(String(error));
1121
- throw new HttpError(401, "Not authorized");
1171
+ throw arbacHttpError(401, "ARBAC_NOT_AUTHORIZED");
1122
1172
  }
1123
1173
  }, TInterceptorPriority.GUARD), { __authTransports: {} });
1124
1174
  function delegatesToArbacPrepareRequest(ctx) {
@@ -2138,7 +2188,8 @@ const NOT_CONTROLS = /* @__PURE__ */ new Set(["filter", "insights"]);
2138
2188
  * gate is `false`, or everything it qualifies is unusable (`$index` /
2139
2189
  * `$fuzzy` / `$vector` name how `$search` runs, `$threshold` bounds
2140
2190
  * `$vector`, `$rowOrder` orders `first()` / `last()` in an aggregate
2141
- * `$select`, `$nulls` places NULLs in `$sort` and `$rowOrder` keys).
2191
+ * `$select`, `$nulls` places NULLs in `$sort` and `$rowOrder` keys, `$from`
2192
+ * is the inner level of an aggregate `$select`).
2142
2193
  */
2143
2194
  function isControlOff(control, list, policy) {
2144
2195
  if (!NOT_CONTROLS.has(control) && policy[`$${control}`] === false) return true;
@@ -2148,7 +2199,8 @@ function isControlOff(control, list, policy) {
2148
2199
  case "fuzzy": return list.includes("search") && off("search");
2149
2200
  case "vector": return off("search");
2150
2201
  case "threshold": return off("vector");
2151
- case "rowOrder": return off("groupBy") || off("select");
2202
+ case "rowOrder":
2203
+ case "from": return off("groupBy") || off("select");
2152
2204
  case "nulls": return off("sort") && (!list.includes("rowOrder") || off("rowOrder"));
2153
2205
  default: return false;
2154
2206
  }
@@ -2157,7 +2209,10 @@ function isControlOff(control, list, policy) {
2157
2209
  const AGGREGATE_ENVELOPE_KEYS = [
2158
2210
  "aggregateFns",
2159
2211
  "aggregateExpressions",
2160
- "bucketUnits"
2212
+ "bucketUnits",
2213
+ "conditionalAggregates",
2214
+ "distinctFieldLists",
2215
+ "nestedAggregates"
2161
2216
  ];
2162
2217
  /**
2163
2218
  * The `/meta` capabilities follow each read op's `controls` policy (`policies`;
@@ -2171,7 +2226,9 @@ const AGGREGATE_ENVELOPE_KEYS = [
2171
2226
  * field on that op's `$groupBy` whitelist, if any), `bucketable` (the same
2172
2227
  * plus `select` — a bucket is checked as the field it buckets), `numeric`
2173
2228
  * and the aggregate envelope keys (`groupBy` + `select`: every aggregate,
2174
- * calendar bucket or arithmetic `$select` is `$groupBy` use), `sortable`
2229
+ * calendar bucket or arithmetic `$select` is `$groupBy` use — conditional
2230
+ * aggregates and field lists included), `nestedAggregates` (those plus
2231
+ * `from`), `sortable`
2175
2232
  * (`sort`), `nullsPlacement` (`nulls`), `searchable` + `searchIndexes`
2176
2233
  * (`search`), `vectorSearchable` + the vector indexes (`search` +
2177
2234
  * `vector`), the non-default text indexes (`search` + `index`), a
@@ -2180,7 +2237,8 @@ const AGGREGATE_ENVELOPE_KEYS = [
2180
2237
  *
2181
2238
  * Returns `meta` itself when nothing changes.
2182
2239
  *
2183
- * @since 0.1.75 (`groupable`), 0.1.80 (the rest)
2240
+ * @since 0.1.75 (`groupable`), 0.1.80 (the rest), 0.2.5 (`conditionalAggregates`,
2241
+ * `distinctFieldLists`, `nestedAggregates` and `from`)
2184
2242
  */
2185
2243
  function gateMetaControls(meta, policies) {
2186
2244
  if (!Object.values(policies).some((p) => p && Object.keys(p).length > 0)) return meta;
@@ -2245,6 +2303,10 @@ function gateMetaControls(meta, policies) {
2245
2303
  delete out[key];
2246
2304
  changed = true;
2247
2305
  }
2306
+ if (out.nestedAggregates !== void 0 && !served(["from"])) {
2307
+ delete out.nestedAggregates;
2308
+ changed = true;
2309
+ }
2248
2310
  if (out.nullsPlacement && !served(["nulls"])) {
2249
2311
  delete out.nullsPlacement;
2250
2312
  changed = true;
@@ -2603,10 +2665,11 @@ function cachedRequestScopes() {
2603
2665
  */
2604
2666
  async function resolveRequestScopes() {
2605
2667
  const ctx = current();
2668
+ const prior = resolved();
2669
+ if (prior?.readBack) return prior.scopes;
2606
2670
  const arbac = useArbac(ctx);
2607
2671
  const cachedScopes = arbac.getScopes();
2608
2672
  const fromInterceptor = cachedScopes && scopesOwnedBy(cachedScopes, arbac.resource, arbac.action) ? cachedScopes : void 0;
2609
- const prior = resolved();
2610
2673
  if (prior && prior.resource === arbac.resource && prior.action === arbac.action && prior.source === fromInterceptor) return prior.scopes;
2611
2674
  const scopes = normalizeScopes(fromInterceptor !== void 0 ? {
2612
2675
  allowed: true,
@@ -2684,6 +2747,13 @@ function isScopedFieldVisible(scopes, path, source) {
2684
2747
  * caller's readable rows match the query; the action itself is authorized
2685
2748
  * by its source controller on every batch.
2686
2749
  *
2750
+ * A read endpoint (`query`, `pages`, `geo`, `one`) under a moost-db write
2751
+ * handler (`insert`, `update`, `replace`, `remove`, `removeComposite`) is
2752
+ * served only inside {@link readBackUnderReadGrant} (since 0.2.4), under the
2753
+ * read grant it installs — otherwise a 403, never the write grant. moost-db's
2754
+ * insert read-back (`Prefer: return=representation`) then answers the plain
2755
+ * insert result.
2756
+ *
2687
2757
  * @since 0.1.72
2688
2758
  */
2689
2759
  async function prepareArbacRequest(ctx, readable) {
@@ -2695,10 +2765,67 @@ async function prepareArbacRequest(ctx, readable) {
2695
2765
  await authorizeDelegatedQueryTarget();
2696
2766
  return;
2697
2767
  }
2768
+ if (READ_ENDPOINTS.has(ctx.endpoint) && !resolved()?.readBack && underWriteHandler()) {
2769
+ const { resource, action } = useArbac();
2770
+ throw insufficientPrivileges(resource, action);
2771
+ }
2698
2772
  const scopes = await resolveRequestScopes();
2699
2773
  if (ctx.endpoint === "insert" && ctx.onConflict === "ignore") resolved().insertIgnore = true;
2700
2774
  if (READ_ENDPOINTS.has(ctx.endpoint)) enforceRelationGates(await resolveRequestRelations(scopes, ctx.controls, readable, ctx.filter), visibilityFor(scopes, readable));
2701
2775
  }
2776
+ /** moost-db's write handler methods — a read under one of them must be a read-back. */
2777
+ const WRITE_HANDLERS = new Set([...WRITE_CRUD_OPS].flatMap((op) => DB_CRUD_HANDLERS[op]));
2778
+ function underWriteHandler() {
2779
+ const method = useControllerContext().getMethod();
2780
+ return method !== void 0 && WRITE_HANDLERS.has(method);
2781
+ }
2782
+ /**
2783
+ * Read back the row `id` after a write, exactly as `GET /one/:id` would
2784
+ * answer the caller (since 0.2.4) — the body of
2785
+ * `AsArbacDbController._readRepresentation`, and the way for a write handler
2786
+ * override to answer the written row:
2787
+ *
2788
+ * ```ts
2789
+ * await super.update(payload);
2790
+ * return readBackUnderReadGrant(id, () => this.getOne(String(id), ""));
2791
+ * ```
2792
+ *
2793
+ * `read` calls the controller's `/one` handler: `getOne` for a scalar `id`,
2794
+ * `getOneComposite` for a key object. The caller's grant on that handler is
2795
+ * evaluated (its `@ArbacResource` / `@ArbacAction`, credential attenuation
2796
+ * included) and installed as the request's scopes while `read` runs — its
2797
+ * row filter, projection and controls apply, and an overridden handler body
2798
+ * runs too — then the write's scopes are restored.
2799
+ *
2800
+ * Answers `undefined` instead of the row when: the caller has no grant on
2801
+ * that handler; the handler carries method-level interceptors (they would
2802
+ * not run on a direct call); `read` answers or throws an `HttpError` (e.g.
2803
+ * the row is outside the read filter → 404); or anything else fails (logged
2804
+ * as a warning, never answered — the write is already committed).
2805
+ */
2806
+ async function readBackUnderReadGrant(id, read) {
2807
+ const ctx = current();
2808
+ const prior = resolved();
2809
+ if (!prior) return void 0;
2810
+ try {
2811
+ const instance = useControllerContext(ctx).getController();
2812
+ const method = isKeyObject(id) ? "getOneComposite" : "getOne";
2813
+ if (getMoostMate().read(instance, method)?.interceptors?.length) return void 0;
2814
+ const ids = resolveHandlerArbacIds(instance, method);
2815
+ const [outcome] = await evaluateHandlerOutcomes([ids]);
2816
+ const scopes = normalizeScopes(outcome);
2817
+ if (!scopes) return void 0;
2818
+ storeResolved(ctx, ids, void 0, scopes);
2819
+ ctx.get(requestScopesKey).readBack = true;
2820
+ const row = await read();
2821
+ return row instanceof HttpError ? void 0 : row;
2822
+ } catch (error) {
2823
+ if (!(error instanceof HttpError)) useLogger("arbac", ctx).warn(`Read-back of the written row failed: ${String(error)}`);
2824
+ return;
2825
+ } finally {
2826
+ ctx.set(requestScopesKey, prior);
2827
+ }
2828
+ }
2702
2829
  /**
2703
2830
  * `authorizeForm` for the ARBAC DB controllers: a form is served iff the
2704
2831
  * caller may run at least one of the actions that take it as input — each
@@ -3078,7 +3205,6 @@ function setPath(target, path, value) {
3078
3205
  node[segs.at(-1)] = value;
3079
3206
  }
3080
3207
  // src/db/write-policy.ts
3081
- const OUT_OF_SCOPE = "Row outside your write scope";
3082
3208
  /**
3083
3209
  * Nested writes through nav props are denied unless a write scope opts the
3084
3210
  * relation in via `nestedWrites` (an unrestricted scope does not). A dotted
@@ -3092,7 +3218,7 @@ function assertNestedWritesAllowed(data, scopes, navFields) {
3092
3218
  for (const key of Object.keys(row)) {
3093
3219
  const dot = key.indexOf(".");
3094
3220
  const rel = dot === -1 ? key : key.slice(0, dot);
3095
- if (navFields.has(rel) && !effectiveScope(scopes).nestedWrites.has(rel)) throw new HttpError(403, `Nested writes through "${rel}" are not allowed`);
3221
+ if (navFields.has(rel) && !effectiveScope(scopes).nestedWrites.has(rel)) throw arbacHttpError(403, "NESTED_WRITE_NOT_ALLOWED", { relation: rel });
3096
3222
  }
3097
3223
  }
3098
3224
  }
@@ -3125,18 +3251,18 @@ async function assertCheckBeforeWrite(ctx, check) {
3125
3251
  try {
3126
3252
  predicate = compileScopeCheck(check);
3127
3253
  } catch (error) {
3128
- if (error instanceof UnsupportedCheckError) throw new HttpError(403, OUT_OF_SCOPE);
3254
+ if (error instanceof UnsupportedCheckError) throw arbacHttpError(403, "ROW_OUT_OF_SCOPE");
3129
3255
  throw error;
3130
3256
  }
3131
3257
  const fields = isPatchAction(ctx.action) ? checkFields(check) : void 0;
3132
3258
  const images = fields ? (await ctx.currentAll()).map((current, i) => current ? patchPostImage(current, ctx.rows[i], fields) : void 0) : ctx.rows;
3133
- for (const image of images) if (!image || !predicate(image)) throw new HttpError(403, OUT_OF_SCOPE);
3259
+ for (const image of images) if (!image || !predicate(image)) throw arbacHttpError(403, "ROW_OUT_OF_SCOPE");
3134
3260
  }
3135
3261
  /** WITH CHECK after the write (inside the transaction — a throw rolls back). */
3136
3262
  async function assertWrittenRowsInCheck(ctx, check) {
3137
3263
  if (ctx.filters.length === 0) return;
3138
3264
  const written = ctx.filters.length === 1 ? ctx.filters[0] : { $or: [...ctx.filters] };
3139
- if (await ctx.count({ $and: [written, check] }) !== ctx.filters.length) throw new HttpError(403, OUT_OF_SCOPE);
3265
+ if (await ctx.count({ $and: [written, check] }) !== ctx.filters.length) throw arbacHttpError(403, "ROW_OUT_OF_SCOPE");
3140
3266
  }
3141
3267
  /**
3142
3268
  * The in-transaction write guard of the ARBAC DB layer — the body of
@@ -3168,7 +3294,7 @@ async function guardArbacWrite(ctx, scopes, table, refs, ignoreConflicts = false
3168
3294
  if (!table.getAdapter().isInTransaction()) await assertCheckBeforeWrite(ctx, eff.check);
3169
3295
  else if (!hasPreImage(ctx.action)) {
3170
3296
  const verdict = insertRowsVerdict(ctx.rows, eff.check);
3171
- if (verdict === false || verdict === void 0 && ignoreConflicts) throw new HttpError(403, OUT_OF_SCOPE);
3297
+ if (verdict === false || verdict === void 0 && ignoreConflicts) throw arbacHttpError(403, "ROW_OUT_OF_SCOPE");
3172
3298
  }
3173
3299
  }
3174
3300
  /**
@@ -3205,6 +3331,15 @@ let AsArbacDbController = class AsArbacDbController extends AsDbController {
3205
3331
  return prepareArbacRequest(ctx, this.readable);
3206
3332
  }
3207
3333
  /**
3334
+ * The read-back of `Prefer: return=representation` on `POST /` (since
3335
+ * 0.2.4; opt in with `returnRepresentation()`): this controller's own
3336
+ * `/one` handler under the caller's grant on it — see
3337
+ * {@link readBackUnderReadGrant}.
3338
+ */
3339
+ _readRepresentation(id) {
3340
+ return readBackUnderReadGrant(id, () => isKeyObject(id) ? this.getOneComposite(textKey(id), "") : this.getOne(String(id), ""));
3341
+ }
3342
+ /**
3208
3343
  * The request filter ∧ the union of the scopes' `filter`s. Computed
3209
3344
  * synchronously, but typed with moost-db's async-capable contract
3210
3345
  * (`FilterExpr | Promise<FilterExpr>`) so a subclass may override it
@@ -3392,6 +3527,10 @@ let AsArbacDbController = class AsArbacDbController extends AsDbController {
3392
3527
  }
3393
3528
  };
3394
3529
  AsArbacDbController = __decorate([Inherit()], AsArbacDbController);
3530
+ /** A key object as `GET /one?…` receives it — every value as text. */
3531
+ function textKey(id) {
3532
+ return Object.fromEntries(Object.entries(id).map(([k, v]) => [k, String(v)]));
3533
+ }
3395
3534
  const preservedFieldsCache = /* @__PURE__ */ new WeakMap();
3396
3535
  /**
3397
3536
  * Test-friendly internal helper — exported for unit tests and helper
@@ -3422,10 +3561,13 @@ function enforceControlsPolicy(policy, controls) {
3422
3561
  const used = controls[key];
3423
3562
  if (used === void 0 || used === null) continue;
3424
3563
  if (Array.isArray(used) && used.length === 0 && key !== "$groupBy") continue;
3425
- if (gate === false) throw new HttpError(403, `Control "${key}" is not allowed for your role`);
3564
+ if (gate === false) throw arbacHttpError(403, "CONTROL_NOT_ALLOWED", { control: key });
3426
3565
  if (Array.isArray(gate)) {
3427
3566
  const usedValues = extractUsedControlValues(key, used, controls);
3428
- for (const v of usedValues) if (!gate.includes(v)) throw new HttpError(403, `Control "${key}=${v}" is not allowed for your role`);
3567
+ for (const v of usedValues) if (!gate.includes(v)) throw arbacHttpError(403, "CONTROL_VALUE_NOT_ALLOWED", {
3568
+ control: key,
3569
+ value: v
3570
+ });
3429
3571
  }
3430
3572
  }
3431
3573
  }
@@ -3446,6 +3588,10 @@ function enforceControlsPolicy(policy, controls) {
3446
3588
  * a calendar-bucket alias (`$select: [{ $bucket, $field, $as }]`) is
3447
3589
  * mapped to its source `$field` (`groupByFields` from `@uniqu/core`),
3448
3590
  * so the whitelist is checked against the column actually grouped on.
3591
+ * The outer level of a two-level aggregate (`controls.$from`) may group
3592
+ * by the inner level's columns — its `$groupBy` keys and `$select`
3593
+ * aliases: those are left out (the inner level, checked on its own as
3594
+ * `"nested"`, grouped on whitelisted columns only).
3449
3595
  *
3450
3596
  * For unknown controls we return an empty array; the caller then enforces
3451
3597
  * `false`-only semantics (controlled by `unionControlsPolicy`'s whitelist
@@ -3454,12 +3600,31 @@ function enforceControlsPolicy(policy, controls) {
3454
3600
  function extractUsedControlValues(key, value, controls) {
3455
3601
  if (!Array.isArray(value)) return [];
3456
3602
  if (key === "$with") return withPaths(value, "");
3457
- if (key === "$groupBy") return controls ? groupByFields({
3458
- $select: controls.$select,
3459
- $groupBy: value
3460
- }) : value.filter((x) => typeof x === "string");
3603
+ if (key === "$groupBy") {
3604
+ if (!controls) return value.filter((x) => typeof x === "string");
3605
+ const names = groupByFields({
3606
+ $select: controls.$select,
3607
+ $groupBy: value
3608
+ });
3609
+ const inner = innerColumns(controls.$from);
3610
+ return inner ? names.filter((name) => !inner.has(name)) : names;
3611
+ }
3461
3612
  return [];
3462
3613
  }
3614
+ /** The columns a two-level aggregate's inner level (`$from`) yields: its `$groupBy` keys and `$select` aliases. */
3615
+ function innerColumns(from) {
3616
+ if (!from || typeof from !== "object" || Array.isArray(from)) return void 0;
3617
+ const { $groupBy, $select } = from;
3618
+ const out = /* @__PURE__ */ new Set();
3619
+ if (Array.isArray($groupBy)) {
3620
+ for (const k of $groupBy) if (typeof k === "string") out.add(k);
3621
+ }
3622
+ if (Array.isArray($select)) for (const entry of $select) {
3623
+ const alias = entry?.$as;
3624
+ if (typeof alias === "string") out.add(alias);
3625
+ }
3626
+ return out;
3627
+ }
3463
3628
  /** Relation paths of a `$with` list, nested `controls.$with` as dotted paths. */
3464
3629
  function withPaths(list, prefix) {
3465
3630
  const out = [];
@@ -3490,7 +3655,7 @@ function remapUniquUrlSyntaxError(err) {
3490
3655
  if (!(err instanceof SyntaxError)) return err;
3491
3656
  const msg = err.message;
3492
3657
  if (!/at (?:pos )?\d+/.test(msg)) return err;
3493
- return new HttpError(400, `Invalid query string: ${msg}`);
3658
+ return arbacHttpError(400, "INVALID_QUERY_STRING", { error: msg });
3494
3659
  }
3495
3660
  // src/db/as-arbac-db-readable-controller.ts
3496
3661
  let AsArbacDbReadableController = class AsArbacDbReadableController extends AsDbReadableController {
@@ -3813,4 +3978,4 @@ async function useArbacDbScope() {
3813
3978
  })
3814
3979
  };
3815
3980
  }
3816
- export { ARBAC_DELEGATED_AUTH, Arbac, ArbacAction, ArbacAuthorize, ArbacResource, ArbacUserProvider, ArbacUserProviderToken, AsArbacDbController, AsArbacDbReadableController, AsArbacJsonValueHelpController, AsArbacValueHelpController, MoostArbac, applyAllowedFieldsAndSet, applyArbacControls, applyArbacMetaOverlay, applyArbacProjection, applyArbacRelationScopes, arbacActionRowScope, arbacAllowedActions, arbacAuthorizeInterceptor, arbacPatternToRegex, arbacRelationFilter, arbacRowFilter, authorizeArbacForm, buildScopeVisibility, cachedRequestScopes, checkArbacWrite, collectMethodNames, collectWithGrantNames, collectWritableFields, conjoinArbacDbScopes, conjoinScopeFilters, enforceControlsPolicy, extractUsedControlValues, getArbacMate, getArbacScopes, guardArbacRemove, guardArbacWrite, isMetaFieldVisible, isScopedFieldVisible, metaAlwaysVisibleFields, prepareArbacRequest, pruneMetaByVisibility, registerArbacDbTarget, requestFieldVisible, requireRequestScopes, resolveHandlerArbacIds, resolveRequestScopes, unionScopeProjection, useArbac, useArbacDbScope };
3981
+ export { ARBAC_DELEGATED_AUTH, ARBAC_MESSAGES, Arbac, ArbacAction, ArbacAuthorize, ArbacResource, ArbacUserProvider, ArbacUserProviderToken, AsArbacDbController, AsArbacDbReadableController, AsArbacJsonValueHelpController, AsArbacValueHelpController, MoostArbac, applyAllowedFieldsAndSet, applyArbacControls, applyArbacMetaOverlay, applyArbacProjection, applyArbacRelationScopes, arbacActionRowScope, arbacAllowedActions, arbacAuthorizeInterceptor, arbacPatternToRegex, arbacRelationFilter, arbacRowFilter, authorizeArbacForm, buildScopeVisibility, cachedRequestScopes, checkArbacWrite, collectMethodNames, collectWithGrantNames, collectWritableFields, conjoinArbacDbScopes, conjoinScopeFilters, enforceControlsPolicy, extractUsedControlValues, getArbacMate, getArbacScopes, guardArbacRemove, guardArbacWrite, isMetaFieldVisible, isScopedFieldVisible, metaAlwaysVisibleFields, prepareArbacRequest, pruneMetaByVisibility, readBackUnderReadGrant, registerArbacDbTarget, requestFieldVisible, requireRequestScopes, resolveHandlerArbacIds, resolveRequestScopes, unionScopeProjection, useArbac, useArbacDbScope };
@@ -82,7 +82,7 @@ type NavRelationKey<T> = keyof NavPropsOf<T> extends never ? string : (keyof Nav
82
82
  */
83
83
  type ProjectionOf<T> = IsUnknown<T> extends true ? TProjection : Partial<Record<OwnFieldKey<T>, 0 | 1>>;
84
84
  /** The Uniquery controls a gate can only allow or deny (`true` / `false`). */
85
- type BooleanControl = "$select" | "$sort" | "$nulls" | "$skip" | "$limit" | "$count" | "$page" | "$size" | "$search" | "$index" | "$fuzzy" | "$vector" | "$threshold" | "$actions" | "$rowOrder" | "$having" | "$center" | "$maxDistance" | "$minDistance";
85
+ type BooleanControl = "$select" | "$sort" | "$nulls" | "$skip" | "$limit" | "$count" | "$page" | "$size" | "$search" | "$index" | "$fuzzy" | "$vector" | "$threshold" | "$actions" | "$rowOrder" | "$having" | "$from" | "$center" | "$maxDistance" | "$minDistance";
86
86
  /**
87
87
  * Typed control gates, matching what `unionControlsPolicy` accepts: only
88
88
  * `$with` (nav relation names) and `$groupBy` (own field paths) take a
@@ -268,6 +268,13 @@ declare class AsArbacDbController<T extends TAtscriptAnnotatedType = TAtscriptAn
268
268
  * is resolved for the requested relations.
269
269
  */
270
270
  protected prepareRequest(ctx: TDbRequestContext): Promise<void>;
271
+ /**
272
+ * The read-back of `Prefer: return=representation` on `POST /` (since
273
+ * 0.2.4; opt in with `returnRepresentation()`): this controller's own
274
+ * `/one` handler under the caller's grant on it — see
275
+ * {@link readBackUnderReadGrant}.
276
+ */
277
+ protected _readRepresentation(id: unknown): Promise<TAtscriptDataType<T> | undefined>;
271
278
  /**
272
279
  * The request filter ∧ the union of the scopes' `filter`s. Computed
273
280
  * synchronously, but typed with moost-db's async-capable contract
@@ -429,6 +436,10 @@ declare function enforceControlsPolicy(policy: Record<string, ControlGate>, cont
429
436
  * a calendar-bucket alias (`$select: [{ $bucket, $field, $as }]`) is
430
437
  * mapped to its source `$field` (`groupByFields` from `@uniqu/core`),
431
438
  * so the whitelist is checked against the column actually grouped on.
439
+ * The outer level of a two-level aggregate (`controls.$from`) may group
440
+ * by the inner level's columns — its `$groupBy` keys and `$select`
441
+ * aliases: those are left out (the inner level, checked on its own as
442
+ * `"nested"`, grouped on whitelisted columns only).
432
443
  *
433
444
  * For unknown controls we return an empty array; the caller then enforces
434
445
  * `false`-only semantics (controlled by `unionControlsPolicy`'s whitelist
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aooth/arbac-moost",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "Moost RBAC integration for aoothjs (migrated from @moostjs/arbac)",
5
5
  "keywords": [
6
6
  "abac",
@@ -60,30 +60,30 @@
60
60
  "access": "public"
61
61
  },
62
62
  "dependencies": {
63
- "@uniqu/core": "^0.2.0",
64
- "@aooth/arbac": "0.2.3",
65
- "@aooth/user": "0.2.3",
66
- "@aooth/arbac-core": "0.2.3"
63
+ "@uniqu/core": "^0.2.1",
64
+ "@aooth/arbac": "0.2.5",
65
+ "@aooth/arbac-core": "0.2.5",
66
+ "@aooth/user": "0.2.5"
67
67
  },
68
68
  "devDependencies": {
69
- "@atscript/core": "^0.2.4",
70
- "@atscript/db": "^0.1.168",
71
- "@atscript/db-sql-tools": "^0.1.168",
72
- "@atscript/db-sqlite": "^0.1.168",
73
- "@atscript/moost-db": "^0.1.168",
74
- "@atscript/typescript": "^0.2.4",
75
- "@moostjs/event-http": "^0.7.2",
69
+ "@atscript/core": "^0.2.8",
70
+ "@atscript/db": "^0.1.171",
71
+ "@atscript/db-sql-tools": "^0.1.171",
72
+ "@atscript/db-sqlite": "^0.1.171",
73
+ "@atscript/moost-db": "^0.1.171",
74
+ "@atscript/typescript": "^0.2.8",
75
+ "@moostjs/event-http": "^0.7.3",
76
76
  "@types/better-sqlite3": "^7.6.13",
77
77
  "better-sqlite3": "^12.6.2",
78
- "unplugin-atscript": "^0.2.4"
78
+ "unplugin-atscript": "^0.2.8"
79
79
  },
80
80
  "peerDependencies": {
81
- "@atscript/db": "^0.1.168",
82
- "@atscript/moost-db": "^0.1.168",
83
- "@atscript/typescript": "^0.2.4",
84
- "@moostjs/event-http": "^0.7.2",
85
- "@wooksjs/event-core": "^0.8.0",
86
- "moost": "^0.7.2"
81
+ "@atscript/db": "^0.1.171",
82
+ "@atscript/moost-db": "^0.1.171",
83
+ "@atscript/typescript": "^0.2.8",
84
+ "@moostjs/event-http": "^0.7.3",
85
+ "@wooksjs/event-core": "^0.8.1",
86
+ "moost": "^0.7.3"
87
87
  },
88
88
  "peerDependenciesMeta": {
89
89
  "@atscript/db": {