@aooth/arbac-moost 0.2.4 → 0.2.6

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-D0cJ_iMd.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-D0cJ_iMd.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 { HttpError, 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 ARBAC_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 ARBAC_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 ARBAC_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 ARBAC_NESTED_WRITE_NOT_ALLOWED: "Nested writes through \"{relation}\" are not allowed";
353
+ /** 403 — a written row fails the scope `check` (WITH CHECK). */
354
+ readonly ARBAC_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 ARBAC_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 ARBAC_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
@@ -964,4 +995,4 @@ export declare class MoostArbac<TUserAttrs extends object, TScope extends object
964
995
  /** The registered custom scope field rules. @since 0.1.72 */
965
996
  getScopeFields(): TScopeFieldRules<TScope>;
966
997
  }
967
- 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,12 +1,12 @@
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
- import { AsDbController, AsDbReadableController, AsJsonValueHelpController, AsValueHelpController, DB_CRUD_HANDLERS, VALUE_HELP_CRUD_HANDLERS, badRequest, discoverRowLevelActions, getControllerFormType, getDbEndpoint, hasActionDelegations, resolveTerminalRef, stableMeta } from "@atscript/moost-db";
9
- import { groupByFields, walkFilter } from "@uniqu/core";
8
+ import { AsDbController, AsDbReadableController, AsJsonValueHelpController, AsValueHelpController, DB_CRUD_HANDLERS, VALUE_HELP_CRUD_HANDLERS, badRequest, discoverRowLevelActions, getControllerFormType, getDbEndpoint, hasActionDelegations, notFoundError, resolveTerminalRef, stableMeta } from "@atscript/moost-db";
9
+ import { groupByFields, resolveAlias, walkFilter } from "@uniqu/core";
10
10
  // src/db/helpers.ts
11
11
  /** `map.get(key)`, created with `create()` and stored on a miss. */
12
12
  function getOrCreate(map, key, create) {
@@ -511,6 +511,45 @@ function requestRelations(readable) {
511
511
  const stored = ctx.has(requestRelationsKey) ? ctx.get(requestRelationsKey) : void 0;
512
512
  return stored && stored.readable === readable ? stored.relations : void 0;
513
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
+ ARBAC_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
+ ARBAC_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
+ ARBAC_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
+ ARBAC_NESTED_WRITE_NOT_ALLOWED: "Nested writes through \"{relation}\" are not allowed",
537
+ /** 403 — a written row fails the scope `check` (WITH CHECK). */
538
+ ARBAC_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
+ ARBAC_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
+ ARBAC_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
+ }
514
553
  // src/db/write-refs.ts
515
554
  /**
516
555
  * The FK a `checkRefs` entry designates: one of its local fields, or the TO
@@ -569,7 +608,7 @@ function readPath(row, path) {
569
608
  return path in row ? row[path] : getPath(row, path);
570
609
  }
571
610
  function outOfScope(fk) {
572
- return new HttpError(403, `Referenced row "${fk.fields.join(", ")}" is outside your scope`);
611
+ return arbacHttpError(403, "ARBAC_REFERENCE_OUT_OF_SCOPE", { fields: fk.fields.join(", ") });
573
612
  }
574
613
  /** A patch row touches `fk` in part only — its tuple is completed from the pre-image. */
575
614
  function needsPreImage(row, fk) {
@@ -862,7 +901,10 @@ function scopesOwnedBy(scopes, resource, action) {
862
901
  }
863
902
  /** The 403 every ARBAC deny answers. */
864
903
  function insufficientPrivileges(resource, action) {
865
- return new HttpError(403, `Insufficient privileges for action "${action}" on resource "${resource}"`);
904
+ return arbacHttpError(403, "ARBAC_INSUFFICIENT_PRIVILEGES", {
905
+ action,
906
+ resource
907
+ });
866
908
  }
867
909
  async function loadPrincipal(user) {
868
910
  const userId = await user.getUserId();
@@ -1048,11 +1090,10 @@ const useArbac = (_ctx) => {
1048
1090
  };
1049
1091
  const evaluateOrThrow = async (opts) => {
1050
1092
  const result = await evaluate(opts);
1051
- if (!result.allowed) {
1052
- const r = opts?.resource || resource;
1053
- const a = opts?.action || action;
1054
- throw new HttpError(403, `Forbidden: ${r}/${a}`);
1055
- }
1093
+ if (!result.allowed) throw arbacHttpError(403, "ARBAC_FORBIDDEN", {
1094
+ resource: opts?.resource || resource,
1095
+ action: opts?.action || action
1096
+ });
1056
1097
  return {
1057
1098
  ...result,
1058
1099
  allowed: true
@@ -1127,7 +1168,7 @@ const arbacAuthorizeInterceptor = Object.assign(defineBeforeInterceptor(async ()
1127
1168
  } catch (error) {
1128
1169
  if (error instanceof HttpError) throw error;
1129
1170
  logger.warn(String(error));
1130
- throw new HttpError(401, "Not authorized");
1171
+ throw arbacHttpError(401, "ARBAC_NOT_AUTHORIZED");
1131
1172
  }
1132
1173
  }, TInterceptorPriority.GUARD), { __authTransports: {} });
1133
1174
  function delegatesToArbacPrepareRequest(ctx) {
@@ -2147,7 +2188,8 @@ const NOT_CONTROLS = /* @__PURE__ */ new Set(["filter", "insights"]);
2147
2188
  * gate is `false`, or everything it qualifies is unusable (`$index` /
2148
2189
  * `$fuzzy` / `$vector` name how `$search` runs, `$threshold` bounds
2149
2190
  * `$vector`, `$rowOrder` orders `first()` / `last()` in an aggregate
2150
- * `$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`).
2151
2193
  */
2152
2194
  function isControlOff(control, list, policy) {
2153
2195
  if (!NOT_CONTROLS.has(control) && policy[`$${control}`] === false) return true;
@@ -2157,7 +2199,8 @@ function isControlOff(control, list, policy) {
2157
2199
  case "fuzzy": return list.includes("search") && off("search");
2158
2200
  case "vector": return off("search");
2159
2201
  case "threshold": return off("vector");
2160
- case "rowOrder": return off("groupBy") || off("select");
2202
+ case "rowOrder":
2203
+ case "from": return off("groupBy") || off("select");
2161
2204
  case "nulls": return off("sort") && (!list.includes("rowOrder") || off("rowOrder"));
2162
2205
  default: return false;
2163
2206
  }
@@ -2166,7 +2209,10 @@ function isControlOff(control, list, policy) {
2166
2209
  const AGGREGATE_ENVELOPE_KEYS = [
2167
2210
  "aggregateFns",
2168
2211
  "aggregateExpressions",
2169
- "bucketUnits"
2212
+ "bucketUnits",
2213
+ "conditionalAggregates",
2214
+ "distinctFieldLists",
2215
+ "nestedAggregates"
2170
2216
  ];
2171
2217
  /**
2172
2218
  * The `/meta` capabilities follow each read op's `controls` policy (`policies`;
@@ -2180,7 +2226,9 @@ const AGGREGATE_ENVELOPE_KEYS = [
2180
2226
  * field on that op's `$groupBy` whitelist, if any), `bucketable` (the same
2181
2227
  * plus `select` — a bucket is checked as the field it buckets), `numeric`
2182
2228
  * and the aggregate envelope keys (`groupBy` + `select`: every aggregate,
2183
- * 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`
2184
2232
  * (`sort`), `nullsPlacement` (`nulls`), `searchable` + `searchIndexes`
2185
2233
  * (`search`), `vectorSearchable` + the vector indexes (`search` +
2186
2234
  * `vector`), the non-default text indexes (`search` + `index`), a
@@ -2189,7 +2237,8 @@ const AGGREGATE_ENVELOPE_KEYS = [
2189
2237
  *
2190
2238
  * Returns `meta` itself when nothing changes.
2191
2239
  *
2192
- * @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`)
2193
2242
  */
2194
2243
  function gateMetaControls(meta, policies) {
2195
2244
  if (!Object.values(policies).some((p) => p && Object.keys(p).length > 0)) return meta;
@@ -2254,6 +2303,10 @@ function gateMetaControls(meta, policies) {
2254
2303
  delete out[key];
2255
2304
  changed = true;
2256
2305
  }
2306
+ if (out.nestedAggregates !== void 0 && !served(["from"])) {
2307
+ delete out.nestedAggregates;
2308
+ changed = true;
2309
+ }
2257
2310
  if (out.nullsPlacement && !served(["nulls"])) {
2258
2311
  delete out.nullsPlacement;
2259
2312
  changed = true;
@@ -3152,7 +3205,6 @@ function setPath(target, path, value) {
3152
3205
  node[segs.at(-1)] = value;
3153
3206
  }
3154
3207
  // src/db/write-policy.ts
3155
- const OUT_OF_SCOPE = "Row outside your write scope";
3156
3208
  /**
3157
3209
  * Nested writes through nav props are denied unless a write scope opts the
3158
3210
  * relation in via `nestedWrites` (an unrestricted scope does not). A dotted
@@ -3166,7 +3218,7 @@ function assertNestedWritesAllowed(data, scopes, navFields) {
3166
3218
  for (const key of Object.keys(row)) {
3167
3219
  const dot = key.indexOf(".");
3168
3220
  const rel = dot === -1 ? key : key.slice(0, dot);
3169
- 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, "ARBAC_NESTED_WRITE_NOT_ALLOWED", { relation: rel });
3170
3222
  }
3171
3223
  }
3172
3224
  }
@@ -3184,7 +3236,7 @@ async function assertIdFiltersInScope(table, idFilters, filter) {
3184
3236
  if (await table.count({
3185
3237
  filter: filter ? { $and: [idFilter, filter] } : idFilter,
3186
3238
  controls: {}
3187
- }) < ids.length) throw new HttpError(404, "Not found");
3239
+ }) < ids.length) throw notFoundError();
3188
3240
  }
3189
3241
  /**
3190
3242
  * WITH CHECK before the write (adapters without real transactions): insert /
@@ -3199,18 +3251,18 @@ async function assertCheckBeforeWrite(ctx, check) {
3199
3251
  try {
3200
3252
  predicate = compileScopeCheck(check);
3201
3253
  } catch (error) {
3202
- if (error instanceof UnsupportedCheckError) throw new HttpError(403, OUT_OF_SCOPE);
3254
+ if (error instanceof UnsupportedCheckError) throw arbacHttpError(403, "ARBAC_ROW_OUT_OF_SCOPE");
3203
3255
  throw error;
3204
3256
  }
3205
3257
  const fields = isPatchAction(ctx.action) ? checkFields(check) : void 0;
3206
3258
  const images = fields ? (await ctx.currentAll()).map((current, i) => current ? patchPostImage(current, ctx.rows[i], fields) : void 0) : ctx.rows;
3207
- 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, "ARBAC_ROW_OUT_OF_SCOPE");
3208
3260
  }
3209
3261
  /** WITH CHECK after the write (inside the transaction — a throw rolls back). */
3210
3262
  async function assertWrittenRowsInCheck(ctx, check) {
3211
3263
  if (ctx.filters.length === 0) return;
3212
3264
  const written = ctx.filters.length === 1 ? ctx.filters[0] : { $or: [...ctx.filters] };
3213
- 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, "ARBAC_ROW_OUT_OF_SCOPE");
3214
3266
  }
3215
3267
  /**
3216
3268
  * The in-transaction write guard of the ARBAC DB layer — the body of
@@ -3234,7 +3286,7 @@ async function guardArbacWrite(ctx, scopes, table, refs, ignoreConflicts = false
3234
3286
  const eff = effectiveScope(scopes);
3235
3287
  if (eff.filter && hasPreImage(ctx.action)) await assertIdFiltersInScope(table, ctx.rows.map((_row, i) => {
3236
3288
  const filter = ctx.filterFor(i);
3237
- if (!filter) throw new HttpError(404, "Not found");
3289
+ if (!filter) throw notFoundError();
3238
3290
  return filter;
3239
3291
  }), eff.filter);
3240
3292
  await assertRefsInScope(ctx, scopes, refs);
@@ -3242,7 +3294,7 @@ async function guardArbacWrite(ctx, scopes, table, refs, ignoreConflicts = false
3242
3294
  if (!table.getAdapter().isInTransaction()) await assertCheckBeforeWrite(ctx, eff.check);
3243
3295
  else if (!hasPreImage(ctx.action)) {
3244
3296
  const verdict = insertRowsVerdict(ctx.rows, eff.check);
3245
- 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, "ARBAC_ROW_OUT_OF_SCOPE");
3246
3298
  }
3247
3299
  }
3248
3300
  /**
@@ -3262,7 +3314,7 @@ async function guardArbacRemove(ctx, scopes, table) {
3262
3314
  if (await table.count({
3263
3315
  filter: { $and: [ctx.filter, filter] },
3264
3316
  controls: {}
3265
- }) === 0) throw new HttpError(404, "Not found");
3317
+ }) === 0) throw notFoundError();
3266
3318
  }
3267
3319
  // src/db/as-arbac-db-controller.ts
3268
3320
  let AsArbacDbController = class AsArbacDbController extends AsDbController {
@@ -3509,10 +3561,13 @@ function enforceControlsPolicy(policy, controls) {
3509
3561
  const used = controls[key];
3510
3562
  if (used === void 0 || used === null) continue;
3511
3563
  if (Array.isArray(used) && used.length === 0 && key !== "$groupBy") continue;
3512
- if (gate === false) throw new HttpError(403, `Control "${key}" is not allowed for your role`);
3564
+ if (gate === false) throw arbacHttpError(403, "ARBAC_CONTROL_NOT_ALLOWED", { control: key });
3513
3565
  if (Array.isArray(gate)) {
3514
3566
  const usedValues = extractUsedControlValues(key, used, controls);
3515
- 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, "ARBAC_CONTROL_VALUE_NOT_ALLOWED", {
3568
+ control: key,
3569
+ value: v
3570
+ });
3516
3571
  }
3517
3572
  }
3518
3573
  }
@@ -3533,6 +3588,10 @@ function enforceControlsPolicy(policy, controls) {
3533
3588
  * a calendar-bucket alias (`$select: [{ $bucket, $field, $as }]`) is
3534
3589
  * mapped to its source `$field` (`groupByFields` from `@uniqu/core`),
3535
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).
3536
3595
  *
3537
3596
  * For unknown controls we return an empty array; the caller then enforces
3538
3597
  * `false`-only semantics (controlled by `unionControlsPolicy`'s whitelist
@@ -3541,12 +3600,38 @@ function enforceControlsPolicy(policy, controls) {
3541
3600
  function extractUsedControlValues(key, value, controls) {
3542
3601
  if (!Array.isArray(value)) return [];
3543
3602
  if (key === "$with") return withPaths(value, "");
3544
- if (key === "$groupBy") return controls ? groupByFields({
3545
- $select: controls.$select,
3546
- $groupBy: value
3547
- }) : 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
+ }
3548
3612
  return [];
3549
3613
  }
3614
+ /**
3615
+ * The columns a two-level aggregate's inner level (`$from`) yields: its
3616
+ * `$groupBy` keys and its computed `$select` columns by output name — the
3617
+ * `$as`, else uniqu's default alias (`count(*)` → `count_star`, as moost-db
3618
+ * and the db core name them). The outer level reads only these, so a name
3619
+ * here is the inner column even when a table field has the same name.
3620
+ */
3621
+ function innerColumns(from) {
3622
+ if (!from || typeof from !== "object" || Array.isArray(from)) return void 0;
3623
+ const { $groupBy, $select } = from;
3624
+ const out = /* @__PURE__ */ new Set();
3625
+ if (Array.isArray($groupBy)) {
3626
+ for (const k of $groupBy) if (typeof k === "string") out.add(k);
3627
+ }
3628
+ if (Array.isArray($select)) for (const entry of $select) {
3629
+ if (entry === null || typeof entry !== "object") continue;
3630
+ const alias = resolveAlias(entry);
3631
+ if (typeof alias === "string" && alias) out.add(alias);
3632
+ }
3633
+ return out;
3634
+ }
3550
3635
  /** Relation paths of a `$with` list, nested `controls.$with` as dotted paths. */
3551
3636
  function withPaths(list, prefix) {
3552
3637
  const out = [];
@@ -3577,7 +3662,7 @@ function remapUniquUrlSyntaxError(err) {
3577
3662
  if (!(err instanceof SyntaxError)) return err;
3578
3663
  const msg = err.message;
3579
3664
  if (!/at (?:pos )?\d+/.test(msg)) return err;
3580
- return new HttpError(400, `Invalid query string: ${msg}`);
3665
+ return arbacHttpError(400, "ARBAC_INVALID_QUERY_STRING", { error: msg });
3581
3666
  }
3582
3667
  // src/db/as-arbac-db-readable-controller.ts
3583
3668
  let AsArbacDbReadableController = class AsArbacDbReadableController extends AsDbReadableController {
@@ -3872,7 +3957,7 @@ async function useArbacDbScope() {
3872
3957
  isFieldVisible,
3873
3958
  scope
3874
3959
  });
3875
- if (!f) throw new HttpError(404, "Not found");
3960
+ if (!f) throw notFoundError();
3876
3961
  return f;
3877
3962
  })), eff.filter);
3878
3963
  },
@@ -3900,4 +3985,4 @@ async function useArbacDbScope() {
3900
3985
  })
3901
3986
  };
3902
3987
  }
3903
- 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, readBackUnderReadGrant, registerArbacDbTarget, requestFieldVisible, requireRequestScopes, resolveHandlerArbacIds, resolveRequestScopes, unionScopeProjection, useArbac, useArbacDbScope };
3988
+ 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
@@ -436,6 +436,10 @@ declare function enforceControlsPolicy(policy: Record<string, ControlGate>, cont
436
436
  * a calendar-bucket alias (`$select: [{ $bucket, $field, $as }]`) is
437
437
  * mapped to its source `$field` (`groupByFields` from `@uniqu/core`),
438
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).
439
443
  *
440
444
  * For unknown controls we return an empty array; the caller then enforces
441
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.4",
3
+ "version": "0.2.6",
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.4",
65
- "@aooth/user": "0.2.4",
66
- "@aooth/arbac-core": "0.2.4"
63
+ "@uniqu/core": "^0.2.1",
64
+ "@aooth/user": "0.2.6",
65
+ "@aooth/arbac": "0.2.6",
66
+ "@aooth/arbac-core": "0.2.6"
67
67
  },
68
68
  "devDependencies": {
69
- "@atscript/core": "^0.2.4",
70
- "@atscript/db": "^0.1.169",
71
- "@atscript/db-sql-tools": "^0.1.169",
72
- "@atscript/db-sqlite": "^0.1.169",
73
- "@atscript/moost-db": "^0.1.169",
74
- "@atscript/typescript": "^0.2.4",
75
- "@moostjs/event-http": "^0.7.2",
69
+ "@atscript/core": "^0.2.9",
70
+ "@atscript/db": "^0.1.174",
71
+ "@atscript/db-sql-tools": "^0.1.174",
72
+ "@atscript/db-sqlite": "^0.1.174",
73
+ "@atscript/moost-db": "^0.1.174",
74
+ "@atscript/typescript": "^0.2.9",
75
+ "@moostjs/event-http": "^0.7.4",
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.9"
79
79
  },
80
80
  "peerDependencies": {
81
- "@atscript/db": "^0.1.169",
82
- "@atscript/moost-db": "^0.1.169",
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.174",
82
+ "@atscript/moost-db": "^0.1.174",
83
+ "@atscript/typescript": "^0.2.9",
84
+ "@moostjs/event-http": "^0.7.4",
85
+ "@wooksjs/event-core": "^0.8.1",
86
+ "moost": "^0.7.4"
87
87
  },
88
88
  "peerDependenciesMeta": {
89
89
  "@atscript/db": {