@entifix/service-shell 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/auth/index.d.ts +1 -0
  2. package/dist/auth/index.d.ts.map +1 -1
  3. package/dist/auth/index.js +1 -0
  4. package/dist/auth/index.js.map +1 -1
  5. package/dist/auth/require-principal.d.ts +6 -0
  6. package/dist/auth/require-principal.d.ts.map +1 -1
  7. package/dist/auth/require-principal.js +6 -2
  8. package/dist/auth/require-principal.js.map +1 -1
  9. package/dist/auth/verified-context.d.ts +25 -0
  10. package/dist/auth/verified-context.d.ts.map +1 -0
  11. package/dist/auth/verified-context.js +40 -0
  12. package/dist/auth/verified-context.js.map +1 -0
  13. package/dist/entity-facet-routes.d.ts +6 -0
  14. package/dist/entity-facet-routes.d.ts.map +1 -1
  15. package/dist/entity-facet-routes.js +8 -5
  16. package/dist/entity-facet-routes.js.map +1 -1
  17. package/dist/entity-metadata-route.d.ts +2 -1
  18. package/dist/entity-metadata-route.d.ts.map +1 -1
  19. package/dist/entity-metadata-route.js +20 -3
  20. package/dist/entity-metadata-route.js.map +1 -1
  21. package/dist/entity-route-guard.d.ts +4 -2
  22. package/dist/entity-route-guard.d.ts.map +1 -1
  23. package/dist/entity-route-guard.js +12 -6
  24. package/dist/entity-route-guard.js.map +1 -1
  25. package/dist/entity-routes.d.ts +13 -1
  26. package/dist/entity-routes.d.ts.map +1 -1
  27. package/dist/entity-routes.js +20 -6
  28. package/dist/entity-routes.js.map +1 -1
  29. package/dist/idempotency.d.ts +59 -0
  30. package/dist/idempotency.d.ts.map +1 -0
  31. package/dist/idempotency.js +107 -0
  32. package/dist/idempotency.js.map +1 -0
  33. package/dist/index.d.ts +3 -0
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +3 -0
  36. package/dist/index.js.map +1 -1
  37. package/dist/metadata-composition.d.ts +28 -0
  38. package/dist/metadata-composition.d.ts.map +1 -0
  39. package/dist/metadata-composition.js +68 -0
  40. package/dist/metadata-composition.js.map +1 -0
  41. package/dist/narrowing.d.ts +27 -0
  42. package/dist/narrowing.d.ts.map +1 -0
  43. package/dist/narrowing.js +34 -0
  44. package/dist/narrowing.js.map +1 -0
  45. package/dist/sse.d.ts +7 -4
  46. package/dist/sse.d.ts.map +1 -1
  47. package/dist/sse.js +21 -5
  48. package/dist/sse.js.map +1 -1
  49. package/package.json +6 -6
@@ -3,4 +3,5 @@ export * from './require-organization.js';
3
3
  export * from './require-principal.js';
4
4
  export * from './require-service-crossing.js';
5
5
  export * from './shared-token.js';
6
+ export * from './verified-context.js';
6
7
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,wBAAwB,CAAC;AACvC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,mBAAmB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,wBAAwB,CAAC;AACvC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC"}
@@ -3,5 +3,6 @@ export * from './require-organization.js';
3
3
  export * from './require-principal.js';
4
4
  export * from './require-service-crossing.js';
5
5
  export * from './shared-token.js';
6
+ export * from './verified-context.js';
6
7
 
7
8
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/index.ts"],"sourcesContent":["export * from './failures.js';\nexport * from './require-organization.js';\nexport * from './require-principal.js';\nexport * from './require-service-crossing.js';\nexport * from './shared-token.js';\n"],"names":[],"mappings":"AAAA,cAAc,gBAAgB;AAC9B,cAAc,4BAA4B;AAC1C,cAAc,yBAAyB;AACvC,cAAc,gCAAgC;AAC9C,cAAc,oBAAoB"}
1
+ {"version":3,"sources":["../../src/auth/index.ts"],"sourcesContent":["export * from './failures.js';\nexport * from './require-organization.js';\nexport * from './require-principal.js';\nexport * from './require-service-crossing.js';\nexport * from './shared-token.js';\nexport * from './verified-context.js';\n"],"names":[],"mappings":"AAAA,cAAc,gBAAgB;AAC9B,cAAc,4BAA4B;AAC1C,cAAc,yBAAyB;AACvC,cAAc,gCAAgC;AAC9C,cAAc,oBAAoB;AAClC,cAAc,wBAAwB"}
@@ -49,6 +49,12 @@ export interface RequestPrincipal {
49
49
  * case the fleet produces.
50
50
  */
51
51
  readonly expiresAt?: number;
52
+ /**
53
+ * What the caller's active organization was provisioned for, off the
54
+ * verified token. Context for a resolver, never a
55
+ * grant: a variant requires an entitlement before its predicate is read.
56
+ */
57
+ readonly entitlements?: readonly string[];
52
58
  readonly attributes: Readonly<Record<string, unknown>>;
53
59
  }
54
60
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"require-principal.d.ts","sourceRoot":"","sources":["../../src/auth/require-principal.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,UAAU,EACf,iBAAiB,EAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,KAAK,WAAW,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEtE,OAAO,EAAE,MAAM,EAAU,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAIhD;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;IACvC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC;;;;;OAKG;IACH,QAAQ,CAAC,cA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Q,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC;;;;;OAKG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC;;;;;;;OAOG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;;;;;OAQG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;;;;;;OASG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;OAIG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,QAAQ,CAAC,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACxD;AA8DD;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,GAAI,CAAC,EAAE,CAAC,EAAE,CAAC,EACtC,KAAK,CAAC,SAAS,EAAE,gBAAgB,KAAK,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,iJAQ1D,CAAC;AAEL;;;;;;;;GAQG;AACH,eAAO,MAAM,iBAAiB,GAC3B,YAAY,UAAU,MACtB,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,SAAS,EAAE,gBAAgB,KAAK,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,qKAmBlE,CAAC"}
@@ -11,7 +11,9 @@ import { refuse } from './failures.js';
11
11
  const [scheme, value] = authorization.split(' ');
12
12
  return (scheme == null ? void 0 : scheme.toLowerCase()) === 'bearer' ? value : undefined;
13
13
  };
14
- /** Rebuild the request principal from verified token claims. */ const claimsToPrincipal = (claims)=>({
14
+ /** Rebuild the request principal from verified token claims. */ const claimsToPrincipal = (claims)=>{
15
+ var _claims_entitlements;
16
+ return {
15
17
  userId: claims.userId,
16
18
  subject: claims.subject,
17
19
  sessionId: claims.sessionId,
@@ -28,10 +30,12 @@ import { refuse } from './failures.js';
28
30
  // `TokenClaims` carries an index signature, so `exp` arrives as `unknown`
29
31
  // even though jose always sets it — hence the guard rather than a cast.
30
32
  expiresAt: typeof claims.exp === 'number' ? claims.exp : undefined,
33
+ entitlements: (_claims_entitlements = claims.entitlements) != null ? _claims_entitlements : [],
31
34
  // Rich/volatile attributes are not in the token; a handler that needs them
32
35
  // reads the session store by `sessionId`.
33
36
  attributes: {}
34
- });
37
+ };
38
+ };
35
39
  // `code` is a key in the shared `errors` catalog; `error` stays English for
36
40
  // logs. `permission` is deliberately still in the 403 — it says which grant was
37
41
  // missing, which is diagnostic, not a leak.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/require-principal.ts"],"sourcesContent":["import {\n parsePermission,\n type Permission,\n PolicyDecisionTag,\n} from '@entifix/authz';\nimport { type TokenClaims, TokenServiceTag } from '@entifix/business';\nimport { ACCESS_COOKIE, Forbidden, Unauthenticated } from '@entifix/core';\nimport { Effect, Option } from 'effect';\nimport { HttpServerRequest } from 'effect/http';\n\nimport { refuse } from './failures.js';\n\n/**\n * The authenticated subject as a service sees it. Structurally identical to\n * `business-ts-authn`'s `Principal`, re-declared here so the shared shell does\n * not depend on a single domain package.\n */\nexport interface RequestPrincipal {\n readonly userId: TokenClaims['userId'];\n readonly subject: string;\n readonly sessionId: string;\n readonly roles: readonly string[];\n /**\n * The organization this request acts for — the storage routing key, absent\n * for a caller with no tenant scope (a buyer, or an operator). Kept out of\n * `attributes` deliberately: attributes are policy inputs, this decides which\n * database a handler reads.\n */\n readonly organizationId?: string;\n /**\n * Which population the caller belongs to — buyer, vendor staff, or platform\n * staff. Carried so a handler never has to infer it from an absent\n * `organizationId`, which a buyer and an operator share.\n *\n * Context, not a grant: what the caller may *do* still comes from `roles`\n * through {@link PolicyDecisionTag}.\n */\n readonly partyRole?: string;\n /**\n * The party behind the account — the `Individual` id, absent for an account\n * with no party record.\n *\n * Same rule as the two fields above: it comes from the verified token and\n * never from anything the caller sets on the request. It says *whose* records\n * these are, which is what a route scoping a read to its caller needs; it\n * says nothing about what may be done with them.\n */\n readonly partyId?: string;\n /**\n * When the verified token stops being valid, as a Unix timestamp in seconds.\n *\n * Every REST route is already bounded by it implicitly — verification is\n * stateless, so the next call after expiry simply fails. A **held-open**\n * response has no next call, so `GET /api/transaction/events` reads it and\n * closes the connection there. Absent when the token carries no\n * `exp`, which a signed one always does; the guard is for the type, not for a\n * case the fleet produces.\n */\n readonly expiresAt?: number;\n readonly attributes: Readonly<Record<string, unknown>>;\n}\n\n/** Extract a bearer token from an `Authorization` header, if present. */\nconst bearerToken = (authorization: string | undefined): string | undefined => {\n if (authorization === undefined) {\n return undefined;\n }\n const [scheme, value] = authorization.split(' ');\n return scheme?.toLowerCase() === 'bearer' ? value : undefined;\n};\n\n/** Rebuild the request principal from verified token claims. */\nconst claimsToPrincipal = (claims: TokenClaims): RequestPrincipal => ({\n userId: claims.userId,\n subject: claims.subject,\n sessionId: claims.sessionId,\n roles: claims.roles,\n // The organization comes from the *verified* token and nowhere else — never\n // from a route parameter, a query string or a body, all of which the caller\n // controls. That is what makes tenant isolation a property of the session\n // rather than of every handler remembering to check.\n organizationId: claims.activeOrganizationId,\n // Same rule, same reason: it comes from the verified token, never from\n // anything the caller can set on the request.\n partyRole: claims.partyRole,\n partyId: claims.partyId,\n // `TokenClaims` carries an index signature, so `exp` arrives as `unknown`\n // even though jose always sets it — hence the guard rather than a cast.\n expiresAt: typeof claims.exp === 'number' ? claims.exp : undefined,\n // Rich/volatile attributes are not in the token; a handler that needs them\n // reads the session store by `sessionId`.\n attributes: {},\n});\n\n// `code` is a key in the shared `errors` catalog; `error` stays English for\n// logs. `permission` is deliberately still in the 403 — it says which grant was\n// missing, which is diagnostic, not a leak.\nconst unauthenticated = refuse(new Unauthenticated());\n\nconst forbidden = (permission: Permission) =>\n refuse(new Forbidden({ permission }));\n\n/**\n * Resolve the caller's principal from the request, or `None`. Reads the token\n * from the `entifix_at` cookie (the Next app forwards it) or an\n * `Authorization: Bearer` header and verifies it statelessly via\n * {@link TokenServiceTag} — no store round trip on the hot path.\n */\nconst resolvePrincipal = Effect.gen(function* () {\n const req = yield* HttpServerRequest.HttpServerRequest;\n const token =\n req.cookies[ACCESS_COOKIE] ?? bearerToken(req.headers['authorization']);\n if (token === undefined) {\n return Option.none<RequestPrincipal>();\n }\n\n const tokens = yield* TokenServiceTag;\n const claims = yield* tokens.verify(token).pipe(Effect.option);\n return Option.map(claims, claimsToPrincipal);\n});\n\n/**\n * Guard a handler behind a valid access token — authentication only. Any\n * missing or invalid token is a `401`; the wrapped handler's own errors are\n * left intact.\n */\nexport const requirePrincipal = <A, E, R>(\n use: (principal: RequestPrincipal) => Effect.Effect<A, E, R>,\n) =>\n Effect.gen(function* () {\n const principal = yield* resolvePrincipal;\n if (Option.isNone(principal)) {\n return yield* unauthenticated;\n }\n return yield* use(principal.value);\n });\n\n/**\n * Guard a handler behind a permission. Authenticates as above, then asks\n * {@link PolicyDecisionTag} whether this subject may perform the action — so\n * the two failure modes stay distinguishable: `401` means \"sign in\", `403`\n * means \"signed in, not allowed\".\n *\n * **This is the authorization boundary.** Filtering a nav menu or hiding a page\n * is presentation; a route that skips this guard is open regardless.\n */\nexport const requirePermission =\n (permission: Permission) =>\n <A, E, R>(use: (principal: RequestPrincipal) => Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const principal = yield* resolvePrincipal;\n if (Option.isNone(principal)) {\n return yield* unauthenticated;\n }\n\n const { resource, action } = parsePermission(permission);\n const policy = yield* PolicyDecisionTag;\n const allowed = policy.decide({\n subject: { roles: principal.value.roles },\n resource,\n action,\n });\n if (!allowed) {\n return yield* forbidden(permission);\n }\n\n return yield* use(principal.value);\n });\n"],"names":["parsePermission","PolicyDecisionTag","TokenServiceTag","ACCESS_COOKIE","Forbidden","Unauthenticated","Effect","Option","HttpServerRequest","refuse","bearerToken","authorization","undefined","scheme","value","split","toLowerCase","claimsToPrincipal","claims","userId","subject","sessionId","roles","organizationId","activeOrganizationId","partyRole","partyId","expiresAt","exp","attributes","unauthenticated","forbidden","permission","resolvePrincipal","gen","req","token","cookies","headers","none","tokens","verify","pipe","option","map","requirePrincipal","use","principal","isNone","requirePermission","resource","action","policy","allowed","decide"],"mappings":"AAAA,SACEA,eAAe,EAEfC,iBAAiB,QACZ,iBAAiB;AACxB,SAA2BC,eAAe,QAAQ,oBAAoB;AACtE,SAASC,aAAa,EAAEC,SAAS,EAAEC,eAAe,QAAQ,gBAAgB;AAC1E,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AACxC,SAASC,iBAAiB,QAAQ,cAAc;AAEhD,SAASC,MAAM,QAAQ,gBAAgB;AAoDvC,uEAAuE,GACvE,MAAMC,cAAc,CAACC;IACnB,IAAIA,kBAAkBC,WAAW;QAC/B,OAAOA;IACT;IACA,MAAM,CAACC,QAAQC,MAAM,GAAGH,cAAcI,KAAK,CAAC;IAC5C,OAAOF,CAAAA,0BAAAA,OAAQG,WAAW,QAAO,WAAWF,QAAQF;AACtD;AAEA,8DAA8D,GAC9D,MAAMK,oBAAoB,CAACC,SAA2C,CAAA;QACpEC,QAAQD,OAAOC,MAAM;QACrBC,SAASF,OAAOE,OAAO;QACvBC,WAAWH,OAAOG,SAAS;QAC3BC,OAAOJ,OAAOI,KAAK;QACnB,4EAA4E;QAC5E,4EAA4E;QAC5E,0EAA0E;QAC1E,qDAAqD;QACrDC,gBAAgBL,OAAOM,oBAAoB;QAC3C,uEAAuE;QACvE,8CAA8C;QAC9CC,WAAWP,OAAOO,SAAS;QAC3BC,SAASR,OAAOQ,OAAO;QACvB,0EAA0E;QAC1E,wEAAwE;QACxEC,WAAW,OAAOT,OAAOU,GAAG,KAAK,WAAWV,OAAOU,GAAG,GAAGhB;QACzD,2EAA2E;QAC3E,0CAA0C;QAC1CiB,YAAY,CAAC;IACf,CAAA;AAEA,4EAA4E;AAC5E,gFAAgF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AACE,SAAS;gBACZ,OAAO,OAAOtB,UAAUC;YAC1B;YAEA,OAAO,OAAOc,IAAIC,UAAUjC,KAAK;QACnC,GAAG"}
1
+ {"version":3,"sources":["../../src/auth/require-principal.ts"],"sourcesContent":["import {\n parsePermission,\n type Permission,\n PolicyDecisionTag,\n} from '@entifix/authz';\nimport { type TokenClaims, TokenServiceTag } from '@entifix/business';\nimport { ACCESS_COOKIE, Forbidden, Unauthenticated } from '@entifix/core';\nimport { Effect, Option } from 'effect';\nimport { HttpServerRequest } from 'effect/http';\n\nimport { refuse } from './failures.js';\n\n/**\n * The authenticated subject as a service sees it. Structurally identical to\n * `business-ts-authn`'s `Principal`, re-declared here so the shared shell does\n * not depend on a single domain package.\n */\nexport interface RequestPrincipal {\n readonly userId: TokenClaims['userId'];\n readonly subject: string;\n readonly sessionId: string;\n readonly roles: readonly string[];\n /**\n * The organization this request acts for — the storage routing key, absent\n * for a caller with no tenant scope (a buyer, or an operator). Kept out of\n * `attributes` deliberately: attributes are policy inputs, this decides which\n * database a handler reads.\n */\n readonly organizationId?: string;\n /**\n * Which population the caller belongs to — buyer, vendor staff, or platform\n * staff. Carried so a handler never has to infer it from an absent\n * `organizationId`, which a buyer and an operator share.\n *\n * Context, not a grant: what the caller may *do* still comes from `roles`\n * through {@link PolicyDecisionTag}.\n */\n readonly partyRole?: string;\n /**\n * The party behind the account — the `Individual` id, absent for an account\n * with no party record.\n *\n * Same rule as the two fields above: it comes from the verified token and\n * never from anything the caller sets on the request. It says *whose* records\n * these are, which is what a route scoping a read to its caller needs; it\n * says nothing about what may be done with them.\n */\n readonly partyId?: string;\n /**\n * When the verified token stops being valid, as a Unix timestamp in seconds.\n *\n * Every REST route is already bounded by it implicitly — verification is\n * stateless, so the next call after expiry simply fails. A **held-open**\n * response has no next call, so `GET /api/transaction/events` reads it and\n * closes the connection there. Absent when the token carries no\n * `exp`, which a signed one always does; the guard is for the type, not for a\n * case the fleet produces.\n */\n readonly expiresAt?: number;\n /**\n * What the caller's active organization was provisioned for, off the\n * verified token. Context for a resolver, never a\n * grant: a variant requires an entitlement before its predicate is read.\n */\n readonly entitlements?: readonly string[];\n readonly attributes: Readonly<Record<string, unknown>>;\n}\n\n/** Extract a bearer token from an `Authorization` header, if present. */\nconst bearerToken = (authorization: string | undefined): string | undefined => {\n if (authorization === undefined) {\n return undefined;\n }\n const [scheme, value] = authorization.split(' ');\n return scheme?.toLowerCase() === 'bearer' ? value : undefined;\n};\n\n/** Rebuild the request principal from verified token claims. */\nconst claimsToPrincipal = (claims: TokenClaims): RequestPrincipal => ({\n userId: claims.userId,\n subject: claims.subject,\n sessionId: claims.sessionId,\n roles: claims.roles,\n // The organization comes from the *verified* token and nowhere else — never\n // from a route parameter, a query string or a body, all of which the caller\n // controls. That is what makes tenant isolation a property of the session\n // rather than of every handler remembering to check.\n organizationId: claims.activeOrganizationId,\n // Same rule, same reason: it comes from the verified token, never from\n // anything the caller can set on the request.\n partyRole: claims.partyRole,\n partyId: claims.partyId,\n // `TokenClaims` carries an index signature, so `exp` arrives as `unknown`\n // even though jose always sets it — hence the guard rather than a cast.\n expiresAt: typeof claims.exp === 'number' ? claims.exp : undefined,\n entitlements: claims.entitlements ?? [],\n // Rich/volatile attributes are not in the token; a handler that needs them\n // reads the session store by `sessionId`.\n attributes: {},\n});\n\n// `code` is a key in the shared `errors` catalog; `error` stays English for\n// logs. `permission` is deliberately still in the 403 — it says which grant was\n// missing, which is diagnostic, not a leak.\nconst unauthenticated = refuse(new Unauthenticated());\n\nconst forbidden = (permission: Permission) =>\n refuse(new Forbidden({ permission }));\n\n/**\n * Resolve the caller's principal from the request, or `None`. Reads the token\n * from the `entifix_at` cookie (the Next app forwards it) or an\n * `Authorization: Bearer` header and verifies it statelessly via\n * {@link TokenServiceTag} — no store round trip on the hot path.\n */\nconst resolvePrincipal = Effect.gen(function* () {\n const req = yield* HttpServerRequest.HttpServerRequest;\n const token =\n req.cookies[ACCESS_COOKIE] ?? bearerToken(req.headers['authorization']);\n if (token === undefined) {\n return Option.none<RequestPrincipal>();\n }\n\n const tokens = yield* TokenServiceTag;\n const claims = yield* tokens.verify(token).pipe(Effect.option);\n return Option.map(claims, claimsToPrincipal);\n});\n\n/**\n * Guard a handler behind a valid access token — authentication only. Any\n * missing or invalid token is a `401`; the wrapped handler's own errors are\n * left intact.\n */\nexport const requirePrincipal = <A, E, R>(\n use: (principal: RequestPrincipal) => Effect.Effect<A, E, R>,\n) =>\n Effect.gen(function* () {\n const principal = yield* resolvePrincipal;\n if (Option.isNone(principal)) {\n return yield* unauthenticated;\n }\n return yield* use(principal.value);\n });\n\n/**\n * Guard a handler behind a permission. Authenticates as above, then asks\n * {@link PolicyDecisionTag} whether this subject may perform the action — so\n * the two failure modes stay distinguishable: `401` means \"sign in\", `403`\n * means \"signed in, not allowed\".\n *\n * **This is the authorization boundary.** Filtering a nav menu or hiding a page\n * is presentation; a route that skips this guard is open regardless.\n */\nexport const requirePermission =\n (permission: Permission) =>\n <A, E, R>(use: (principal: RequestPrincipal) => Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const principal = yield* resolvePrincipal;\n if (Option.isNone(principal)) {\n return yield* unauthenticated;\n }\n\n const { resource, action } = parsePermission(permission);\n const policy = yield* PolicyDecisionTag;\n const allowed = policy.decide({\n subject: { roles: principal.value.roles },\n resource,\n action,\n });\n if (!allowed) {\n return yield* forbidden(permission);\n }\n\n return yield* use(principal.value);\n });\n"],"names":["parsePermission","PolicyDecisionTag","TokenServiceTag","ACCESS_COOKIE","Forbidden","Unauthenticated","Effect","Option","HttpServerRequest","refuse","bearerToken","authorization","undefined","scheme","value","split","toLowerCase","claimsToPrincipal","claims","userId","subject","sessionId","roles","organizationId","activeOrganizationId","partyRole","partyId","expiresAt","exp","entitlements","attributes","unauthenticated","forbidden","permission","resolvePrincipal","gen","req","token","cookies","headers","none","tokens","verify","pipe","option","map","requirePrincipal","use","principal","isNone","requirePermission","resource","action","policy","allowed","decide"],"mappings":"AAAA,SACEA,eAAe,E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context, Effect } from 'effect';
3
+ import type { RequestPrincipal } from './require-principal.js';
4
+ declare const VerifiedContextConfigTag_base: Context.ServiceClass<VerifiedContextConfigTag, "@entifix/service-shell/VerifiedContextConfig", Readonly<Record<string, unknown>>>;
5
+ /**
6
+ * The configuration dials a resolver's predicates may read, provided by the
7
+ * composition root. Optional: a service that resolves nothing on a dial
8
+ * provides none, and its contexts carry an empty `config`.
9
+ */
10
+ export declare class VerifiedContextConfigTag extends VerifiedContextConfigTag_base {
11
+ }
12
+ /**
13
+ * The verified context of a caller: what their verified token says, and the
14
+ * service's dials — never anything the request carries
15
+ * ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)).
16
+ * No principal is an anonymous caller: no organization, no party, nothing held.
17
+ */
18
+ export declare const verifiedContextOf: (principal: RequestPrincipal | undefined, config?: Readonly<Record<string, unknown>>) => VerifiedContext;
19
+ /**
20
+ * Runs `use` with the caller's verified context built and provided as
21
+ * {@link VerifiedContextTag} — the one place a request's context is made.
22
+ */
23
+ export declare const withVerifiedContext: <A, E, R>(principal: RequestPrincipal | undefined, use: (verified: VerifiedContext) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, VerifiedContextTag>>;
24
+ export {};
25
+ //# sourceMappingURL=verified-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verified-context.d.ts","sourceRoot":"","sources":["../../src/auth/verified-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,eAAe,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAE7E,OAAO,EAAE,OAAO,EAAE,MAAM,EAAU,MAAM,QAAQ,CAAC;AAEjD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;;AAE/D;;;;GAIG;AACH,qBAAa,wBAAyB,SAAQ,6BAGK;CAAG;AAEtD;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,GAC5B,WAAW,gBAAgB,GAAG,SAAS,EACvC,SAAQ,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAM,KAC7C,eAaC,CAAC;AAEL;;;GAGG;AACH,eAAO,MAAM,mBAAmB,GAAI,CAAC,EAAE,CAAC,EAAE,CAAC,EACzC,WAAW,gBAAgB,GAAG,SAAS,EACvC,KAAK,CAAC,QAAQ,EAAE,eAAe,KAAK,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,KACzD,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,kBAAkB,CAAC,CAUjD,CAAC"}
@@ -0,0 +1,40 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { VerifiedContextTag } from '@entifix/business';
3
+ import { verifiedContext } from '@entifix/business/verified';
4
+ import { Context, Effect, Option } from 'effect';
5
+ /**
6
+ * The configuration dials a resolver's predicates may read, provided by the
7
+ * composition root. Optional: a service that resolves nothing on a dial
8
+ * provides none, and its contexts carry an empty `config`.
9
+ */ export class VerifiedContextConfigTag extends Context.Service()('@entifix/service-shell/VerifiedContextConfig') {
10
+ }
11
+ /**
12
+ * The verified context of a caller: what their verified token says, and the
13
+ * service's dials — never anything the request carries
14
+ * ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)).
15
+ * No principal is an anonymous caller: no organization, no party, nothing held.
16
+ */ export const verifiedContextOf = (principal, config = {})=>{
17
+ var _ref, _ref1;
18
+ return verifiedContext(_extends({}, (principal == null ? void 0 : principal.organizationId) === undefined ? {} : {
19
+ organizationId: principal.organizationId
20
+ }, (principal == null ? void 0 : principal.partyId) === undefined ? {} : {
21
+ partyId: principal.partyId
22
+ }, (principal == null ? void 0 : principal.partyRole) === undefined ? {} : {
23
+ partyRole: principal.partyRole
24
+ }, {
25
+ entitlements: (_ref = principal == null ? void 0 : principal.entitlements) != null ? _ref : [],
26
+ roles: (_ref1 = principal == null ? void 0 : principal.roles) != null ? _ref1 : [],
27
+ flags: [],
28
+ config
29
+ }));
30
+ };
31
+ /**
32
+ * Runs `use` with the caller's verified context built and provided as
33
+ * {@link VerifiedContextTag} — the one place a request's context is made.
34
+ */ export const withVerifiedContext = (principal, use)=>Effect.gen(function*() {
35
+ const config = yield* Effect.serviceOption(VerifiedContextConfigTag);
36
+ const verified = verifiedContextOf(principal, Option.getOrElse(config, ()=>({})));
37
+ return yield* use(verified).pipe(Effect.provideService(VerifiedContextTag, verified));
38
+ });
39
+
40
+ //# sourceMappingURL=verified-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auth/verified-context.ts"],"sourcesContent":["import { type VerifiedContext, VerifiedContextTag } from '@entifix/business';\nimport { verifiedContext } from '@entifix/business/verified';\nimport { Context, Effect, Option } from 'effect';\n\nimport type { RequestPrincipal } from './require-principal.js';\n\n/**\n * The configuration dials a resolver's predicates may read, provided by the\n * composition root. Optional: a service that resolves nothing on a dial\n * provides none, and its contexts carry an empty `config`.\n */\nexport class VerifiedContextConfigTag extends Context.Service<\n VerifiedContextConfigTag,\n Readonly<Record<string, unknown>>\n>()('@entifix/service-shell/VerifiedContextConfig') {}\n\n/**\n * The verified context of a caller: what their verified token says, and the\n * service's dials — never anything the request carries\n * ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)).\n * No principal is an anonymous caller: no organization, no party, nothing held.\n */\nexport const verifiedContextOf = (\n principal: RequestPrincipal | undefined,\n config: Readonly<Record<string, unknown>> = {},\n): VerifiedContext =>\n verifiedContext({\n ...(principal?.organizationId === undefined\n ? {}\n : { organizationId: principal.organizationId }),\n ...(principal?.partyId === undefined ? {} : { partyId: principal.partyId }),\n ...(principal?.partyRole === undefined\n ? {}\n : { partyRole: principal.partyRole }),\n entitlements: principal?.entitlements ?? [],\n roles: principal?.roles ?? [],\n flags: [],\n config,\n });\n\n/**\n * Runs `use` with the caller's verified context built and provided as\n * {@link VerifiedContextTag} — the one place a request's context is made.\n */\nexport const withVerifiedContext = <A, E, R>(\n principal: RequestPrincipal | undefined,\n use: (verified: VerifiedContext) => Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, Exclude<R, VerifiedContextTag>> =>\n Effect.gen(function* () {\n const config = yield* Effect.serviceOption(VerifiedContextConfigTag);\n const verified = verifiedContextOf(\n principal,\n Option.getOrElse(config, () => ({})),\n );\n return yield* use(verified).pipe(\n Effect.provideService(VerifiedContextTag, verified),\n );\n });\n"],"names":["VerifiedContextTag","verifiedContext","Context","Effect","Option","VerifiedContextConfigTag","Service","verifiedContextOf","principal","config","organizationId","undefined","partyId","partyRole","entitlements","roles","flags","withVerifiedContext","use","gen","serviceOption","verified","getOrElse","pipe","provideService"],"mappings":";AAAA,SAA+BA,kBAAkB,QAAQ,oBAAoB;AAC7E,SAASC,eAAe,QAAQ,6BAA6B;AAC7D,SAASC,OAAO,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAIjD;;;;CAIC,GACD,OAAO,MAAMC,iCAAiCH,QAAQI,OAAO,GAGzD;AAAiD;AAErD;;;;;CAKC,GACD,OAAO,MAAMC,oBAAoB,CAC/BC,WACAC,SAA4C,CAAC,CAAC;;WAE9CR,gBAAgB,aACVO,CAAAA,6BAAAA,UAAWE,cAAc,MAAKC,YAC9B,CAAC,IACD;QAAED,gBAAgBF,UAAUE,cAAc;IAAC,GAC3CF,CAAAA,6BAAAA,UAAWI,OAAO,MAAKD,YAAY,CAAC,IAAI;QAAEC,SAASJ,UAAUI,OAAO;IAAC,GACrEJ,CAAAA,6BAAAA,UAAWK,SAAS,MAAKF,YACzB,CAAC,IACD;QAAEE,WAAWL,UAAUK,SAAS;IAAC;QACrCC,YAAY,UAAEN,6BAAAA,UAAWM,YAAY,mBAAI,EAAE;QAC3CC,KAAK,WAAEP,6BAAAA,UAAWO,KAAK,oBAAI,EAAE;QAC7BC,OAAO,EAAE;QACTP;;EACC;AAEL;;;CAGC,GACD,OAAO,MAAMQ,sBAAsB,CACjCT,WACAU,MAEAf,OAAOgB,GAAG,CAAC;QACT,MAAMV,SAAS,OAAON,OAAOiB,aAAa,CAACf;QAC3C,MAAMgB,WAAWd,kBACfC,WACAJ,OAAOkB,SAAS,CAACb,QAAQ,IAAO,CAAA,CAAC,CAAA;QAEnC,OAAO,OAAOS,IAAIG,UAAUE,IAAI,CAC9BpB,OAAOqB,cAAc,CAACxB,oBAAoBqB;IAE9C,GAAG"}
@@ -3,6 +3,7 @@ import { type Entity, type EntityConstructor } from '@entifix/core';
3
3
  import { Effect } from 'effect';
4
4
  import { HttpRouter } from 'effect/http';
5
5
  import { type EntityReadScope, type EntityRouteContext, type EntityRouteGuard } from './entity-route-guard.js';
6
+ import { type NarrowingRules } from './narrowing.js';
6
7
  import { type FailurePolicy } from './respond.js';
7
8
  export interface EntityFacetRoutesOptions<T extends Entity, R, G extends EntityRouteGuard = EntityRouteGuard> {
8
9
  /** Who may count: the guard the entity's `list` has, as a rule. */
@@ -15,6 +16,11 @@ export interface EntityFacetRoutesOptions<T extends Entity, R, G extends EntityR
15
16
  * would not.
16
17
  */
17
18
  readonly scope?: (context: EntityRouteContext) => Effect.Effect<EntityReadScope<T>, never, R>;
19
+ /**
20
+ * The same narrowing the entity's `list` takes, as resolver rules — so a
21
+ * count equals the narrowed list. Replaces `scope`; naming both throws.
22
+ */
23
+ readonly narrowing?: NarrowingRules<T>;
18
24
  /** How the count's failures are answered and logged. */
19
25
  readonly policy?: FailurePolicy;
20
26
  }
@@ -1 +1 @@
1
- {"version":3,"file":"entity-facet-routes.d.ts","sourceRoot":"","sources":["../src/entity-facet-routes.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,4BAA4B,EAG7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,iBAAiB,EAMvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,UAAU,EAAyC,MAAM,aAAa,CAAC;AAEhF,OA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,EACpB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EAGtB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAGL,KAAK,cAAc,EACpB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAEL,KAAK,aAAa,EAEnB,MAAM,cAAc,CAAC;AAGtB,MAAM,WAAW,wBAAwB,CACvC,CAAC,SAAS,MAAM,EAChB,CAAC,EACD,CAAC,SAAS,gBAAgB,GAAG,gBAAgB;IAE7C,mEAAmE;IACnE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAClB,0EAA0E;IAC1E,QAAQ,CAAC,QAAQ,CAAC,EAAE,IAAI,MAAM,EAAE,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,CACf,OAAO,EAAE,kBAAkB,KACxB,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;IACjD;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,CAAC;IACvC,wDAAwD;IACxD,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,CAAC;CACjC;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,qBAAqB,GAChC,CAAC,SAAS,MAAM,EAChB,CAAC,GAAG,KAAK,EAGT,KAAK,CAAC,CAAC,SAAS,gBAAgB,GAAG,KAAK,EAExC,mBAAmB,iBAAiB,CAAC,CAAC,CAAC,EACvC,SAAS,wBAAwB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;;0JAyF3C,CAAC"}
@@ -4,6 +4,7 @@ import { envelopeEntityName, makeEntityFacetsEnvelope, parseFacetQueryParams } f
4
4
  import { Effect } from 'effect';
5
5
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';
6
6
  import { guardRoute } from './entity-route-guard.js';
7
+ import { narrowingFor } from './narrowing.js';
7
8
  import { defaultFailurePolicy, respond } from './respond.js';
8
9
  import { legacyAnswer } from './route-responses.js';
9
10
  /**
@@ -30,19 +31,21 @@ import { legacyAnswer } from './route-responses.js';
30
31
  catch: (error)=>error
31
32
  });
32
33
  });
33
- const scoped = (queries, scope)=>scope === 'all' || scope === 'none' ? queries : queries.map((query)=>{
34
+ const narrowed = (queries, narrowing)=>narrowing === 'unscoped' ? queries : queries.map((query)=>{
34
35
  var _query_filtering;
35
36
  return _extends({}, query, {
36
37
  filtering: [
37
38
  ...(_query_filtering = query.filtering) != null ? _query_filtering : [],
38
- scope.filter
39
+ narrowing
39
40
  ]
40
41
  });
41
42
  });
43
+ if (options.narrowing !== undefined && options.scope !== undefined) throw new Error(`the facet route for '${envelopeEntityName(entityConstructor)}' names both ` + '`narrowing` and `scope`; `narrowing` replaces `scope`, so name one.');
44
+ /** A scope, as the narrowing this route applies. */ const asNarrowing = (scope)=>scope === 'all' ? 'unscoped' : scope === 'none' ? 'nothing' : scope.filter;
42
45
  const count = (context)=>Effect.gen(function*() {
43
46
  const queries = yield* readQueries;
44
- const scope = options.scope ? yield* options.scope(context) : 'all';
45
- if (scope === 'none') {
47
+ const narrowing = options.narrowing !== undefined && context.verified !== undefined ? narrowingFor(options.narrowing, context.verified) : asNarrowing(options.scope ? yield* options.scope(context) : 'all');
48
+ if (narrowing === 'nothing') {
46
49
  // Still parsed: whether a query is well-formed must not depend on who
47
50
  // asked.
48
51
  const empty = Object.fromEntries(queries.map(({ member })=>[
@@ -55,7 +58,7 @@ import { legacyAnswer } from './route-responses.js';
55
58
  const counter = yield* factory.for(entityConstructor, _extends({}, context.organizationId === undefined ? {} : {
56
59
  organizationId: context.organizationId
57
60
  }));
58
- const counts = yield* facetCountsUCFactory(scoped(queries, scope)).pipe(Effect.provideService(EntityFacetCounterTag, counter));
61
+ const counts = yield* facetCountsUCFactory(narrowed(queries, narrowing)).pipe(Effect.provideService(EntityFacetCounterTag, counter));
59
62
  return yield* HttpServerResponse.json(makeEntityFacetsEnvelope(entityConstructor, counts));
60
63
  }).pipe(Effect.catch(legacyAnswer('invalidQuery')));
61
64
  const handler = respond(guardRoute(entityConstructor, options.guard, 'read', count), (_options_policy = options.policy) != null ? _options_policy : defaultFailurePolicy);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/entity-facet-routes.ts"],"sourcesContent":["import {\n EntityFacetCounterFactoryTag,\n EntityFacetCounterTag,\n facetCountsUCFactory,\n} from '@entifix/business';\nimport type { EntifixFailure } from '@entifix/core';\nimport {\n EntifixBuildError,\n type Entity,\n type EntityConstructor,\n type EntityFacetCounts,\n type EntityFacetQuery,\n envelopeEntityName,\n makeEntityFacetsEnvelope,\n parseFacetQueryParams,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n guardRoute,\n type GuardServices,\n} from './entity-route-guard.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from './respond.js';\nimport { legacyAnswer } from './route-responses.js';\n\nexport interface EntityFacetRoutesOptions<\n T extends Entity,\n R,\n G extends EntityRouteGuard = EntityRouteGuard,\n> {\n /** Who may count: the guard the entity's `list` has, as a rule. */\n readonly guard: G;\n /** Defaults to `/api/<entity key>`; the route is `<basePath>/$facets`. */\n readonly basePath?: `/${string}`;\n /**\n * Narrows the counts to the records this caller may see — the same scope\n * the entity's `list` takes, so a count never reveals a record the list\n * would not.\n */\n readonly scope?: (\n context: EntityRouteContext,\n ) => Effect.Effect<EntityReadScope<T>, never, R>;\n /** How the count's failures are answered and logged. */\n readonly policy?: FailurePolicy;\n}\n\n/**\n * `GET <base>/$facets` — how many of the entity's records hold each value of\n * each `facet` member, each under its own `rsql.<member>` filtering — bound to\n * storage through the host's {@link EntityFacetCounterFactoryTag}.\n *\n * A route of its own beside `makeEntityRoutes` rather than a sixth verb, so it\n * is the one route set that requires a counter: a host that mounts it without\n * binding one fails to compile, and a host that never counts binds nothing.\n *\n * The query is parsed against the entity's metadata, so only a `filterable`\n * member is counted and every malformed request is a `400`. A scope is\n * **conjoined into every facet's filtering**, never substituted, so no query\n * string can count past it; `'none'` answers every member empty.\n */\nexport const makeEntityFacetRoutes = <\n T extends Entity,\n R = never,\n // `never` for the reason `makeEntityRoutes` gives: a caller naming `R`\n // explicitly must not widen the guard to every kind there is.\n const G extends EntityRouteGuard = never,\n>(\n entityConstructor: EntityConstructor<T>,\n options: EntityFacetRoutesOptions<T, R, G>,\n) => {\n const base: `/${string}` =\n options.basePath ?? `/api/${envelopeEntityName(entityConstructor)}`;\n\n const readQueries = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const search = new URL(request.url, 'http://localhost').searchParams;\n return yield* Effect.try({\n try: () => parseFacetQueryParams(entityConstructor, search),\n catch: error => error as EntifixBuildError,\n });\n });\n\n const scoped = (\n queries: EntityFacetQuery<T>[],\n scope: EntityReadScope<T>,\n ): EntityFacetQuery<T>[] =>\n scope === 'all' || scope === 'none'\n ? queries\n : queries.map(query => ({\n ...query,\n filtering: [...(query.filtering ?? []), scope.filter],\n }));\n\n const count = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const queries = yield* readQueries;\n const scope = options.scope\n ? yield* options.scope(context)\n : ('all' as const);\n if (scope === 'none') {\n // Still parsed: whether a query is well-formed must not depend on who\n // asked.\n const empty: EntityFacetCounts = Object.fromEntries(\n queries.map(({ member }) => [member, []]),\n );\n return yield* HttpServerResponse.json(\n makeEntityFacetsEnvelope(entityConstructor, empty),\n );\n }\n const factory = yield* EntityFacetCounterFactoryTag;\n const counter = yield* factory.for(entityConstructor, {\n ...(context.organizationId === undefined\n ? {}\n : { organizationId: context.organizationId }),\n });\n const counts = yield* facetCountsUCFactory<T>(\n scoped(queries, scope),\n ).pipe(Effect.provideService(EntityFacetCounterTag, counter));\n return yield* HttpServerResponse.json(\n makeEntityFacetsEnvelope(entityConstructor, counts),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidQuery')));\n\n const handler = respond(\n guardRoute(\n entityConstructor,\n options.guard,\n 'read',\n count,\n ) as Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n EntifixFailure,\n | R\n | EntityFacetCounterFactoryTag\n | GuardServices<G>\n | HttpServerRequest.HttpServerRequest\n | HttpRouter.RouteContext\n >,\n options.policy ?? defaultFailurePolicy,\n );\n\n return HttpRouter.addAll([\n HttpRouter.route('GET', `${base}/$facets`, handler),\n ]);\n};\n"],"names":["EntityFacetCounterFactoryTag","EntityFacetCounterTag","facetCountsUCFactory","envelopeEntityName","makeEntityFacetsEnvelope","parseFacetQueryParams","Effect","HttpRouter","HttpServerRequest","HttpServerResponse","guardRoute","defaultFailurePolicy","respond","legacyAnswer","makeEntityFacetRoutes","entityConstructor","options","base","basePath","readQueries","gen","request","search","URL","url","searchParams","try","catch","error","scoped","queries","scope","map","query","filtering","filter","count","context","empty","Object","fromEntries","member","json","factory","counter","for","organizationId","undefined","counts","pipe","provideService","handler","guard","policy","addAll","route"],"mappings":";AAAA,SACEA,4BAA4B,EAC5BC,qBAAqB,EACrBC,oBAAoB,QACf,oBAAoB;AAE3B,SAMEC,kBAAkB,EAClBC,wBAAwB,EACxBC,qBAAqB,QAChB,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,UAAU,EAAEC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEhF,SAIEC,UAAU,QAEL,0BAA0B;AACjC,SACEC,oBAAoB,EAEpBC,OAAO,QACF,eAAe;AACtB,SAASC,YAAY,QAAQ,uBAAuB;AAuBpD;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,wBAAwB,CAOnCC,mBACAC;QAGEA,mBAmEAA;IApEF,MAAMC,QACJD,oBAAAA,QAAQE,QAAQ,YAAhBF,oBAAoB,CAAC,KAAK,EAAEb,mBAAmBY,oBAAoB;IAErE,MAAMI,cAAcb,OAAOc,GAAG,CAAC;QAC7B,MAAMC,UAAU,OA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MAAMsC,UAAUvC,QACdF,WACEK,mBACAC,QAAQoC,KAAK,EACb,QACAhB,SAUFpB,kBAAAA,QAAQqC,MAAM,YAAdrC,kBAAkBL;IAGpB,OAAOJ,WAAW+C,MAAM,CAAC;QACvB/C,WAAWgD,KAAK,CAAC,OAAO,GAAGtC,KAAK,QAAQ,CAAC,EAAEkC;KAC5C;AACH,EAAE"}
1
+ {"version":3,"sources":["../src/entity-facet-routes.ts"],"sourcesContent":["import {\n EntityFacetCounterFactoryTag,\n EntityFacetCounterTag,\n facetCountsUCFactory,\n} from '@entifix/business';\nimport type { EntifixFailure } from '@entifix/core';\nimport {\n EntifixBuildError,\n type Entity,\n type EntityConstructor,\n type EntityFacetCounts,\n type EntityFacetQuery,\n envelopeEntityName,\n makeEntityFacetsEnvelope,\n parseFacetQueryParams,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport {\n type EntityReadScope,\n type EntityRouteContext,\n type EntityRouteGuard,\n guardRoute,\n type GuardServices,\n} from './entity-route-guard.js';\nimport {\n type Narrowing,\n narrowingFor,\n type NarrowingRules,\n} from './narrowing.js';\nimport {\n defaultFailurePolicy,\n type FailurePolicy,\n respond,\n} from './respond.js';\nimport { legacyAnswer } from './route-responses.js';\n\nexport interface EntityFacetRoutesOptions<\n T extends Entity,\n R,\n G extends EntityRouteGuard = EntityRouteGuard,\n> {\n /** Who may count: the guard the entity's `list` has, as a rule. */\n readonly guard: G;\n /** Defaults to `/api/<entity key>`; the route is `<basePath>/$facets`. */\n readonly basePath?: `/${string}`;\n /**\n * Narrows the counts to the records this caller may see — the same scope\n * the entity's `list` takes, so a count never reveals a record the list\n * would not.\n */\n readonly scope?: (\n context: EntityRouteContext,\n ) => Effect.Effect<EntityReadScope<T>, never, R>;\n /**\n * The same narrowing the entity's `list` takes, as resolver rules — so a\n * count equals the narrowed list. Replaces `scope`; naming both throws.\n */\n readonly narrowing?: NarrowingRules<T>;\n /** How the count's failures are answered and logged. */\n readonly policy?: FailurePolicy;\n}\n\n/**\n * `GET <base>/$facets` — how many of the entity's records hold each value of\n * each `facet` member, each under its own `rsql.<member>` filtering — bound to\n * storage through the host's {@link EntityFacetCounterFactoryTag}.\n *\n * A route of its own beside `makeEntityRoutes` rather than a sixth verb, so it\n * is the one route set that requires a counter: a host that mounts it without\n * binding one fails to compile, and a host that never counts binds nothing.\n *\n * The query is parsed against the entity's metadata, so only a `filterable`\n * member is counted and every malformed request is a `400`. A scope is\n * **conjoined into every facet's filtering**, never substituted, so no query\n * string can count past it; `'none'` answers every member empty.\n */\nexport const makeEntityFacetRoutes = <\n T extends Entity,\n R = never,\n // `never` for the reason `makeEntityRoutes` gives: a caller naming `R`\n // explicitly must not widen the guard to every kind there is.\n const G extends EntityRouteGuard = never,\n>(\n entityConstructor: EntityConstructor<T>,\n options: EntityFacetRoutesOptions<T, R, G>,\n) => {\n const base: `/${string}` =\n options.basePath ?? `/api/${envelopeEntityName(entityConstructor)}`;\n\n const readQueries = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const search = new URL(request.url, 'http://localhost').searchParams;\n return yield* Effect.try({\n try: () => parseFacetQueryParams(entityConstructor, search),\n catch: error => error as EntifixBuildError,\n });\n });\n\n const narrowed = (\n queries: EntityFacetQuery<T>[],\n narrowing: Exclude<Narrowing<T>, 'nothing'>,\n ): EntityFacetQuery<T>[] =>\n narrowing === 'unscoped'\n ? queries\n : queries.map(query => ({\n ...query,\n filtering: [...(query.filtering ?? []), narrowing],\n }));\n\n if (options.narrowing !== undefined && options.scope !== undefined)\n throw new Error(\n `the facet route for '${envelopeEntityName(entityConstructor)}' names both ` +\n '`narrowing` and `scope`; `narrowing` replaces `scope`, so name one.',\n );\n\n /** A scope, as the narrowing this route applies. */\n const asNarrowing = (scope: EntityReadScope<T>): Narrowing<T> =>\n scope === 'all' ? 'unscoped' : scope === 'none' ? 'nothing' : scope.filter;\n\n const count = (context: EntityRouteContext) =>\n Effect.gen(function* () {\n const queries = yield* readQueries;\n const narrowing =\n options.narrowing !== undefined && context.verified !== undefined\n ? narrowingFor(options.narrowing, context.verified)\n : asNarrowing(\n options.scope ? yield* options.scope(context) : ('all' as const),\n );\n if (narrowing === 'nothing') {\n // Still parsed: whether a query is well-formed must not depend on who\n // asked.\n const empty: EntityFacetCounts = Object.fromEntries(\n queries.map(({ member }) => [member, []]),\n );\n return yield* HttpServerResponse.json(\n makeEntityFacetsEnvelope(entityConstructor, empty),\n );\n }\n const factory = yield* EntityFacetCounterFactoryTag;\n const counter = yield* factory.for(entityConstructor, {\n ...(context.organizationId === undefined\n ? {}\n : { organizationId: context.organizationId }),\n });\n const counts = yield* facetCountsUCFactory<T>(\n narrowed(queries, narrowing),\n ).pipe(Effect.provideService(EntityFacetCounterTag, counter));\n return yield* HttpServerResponse.json(\n makeEntityFacetsEnvelope(entityConstructor, counts),\n );\n }).pipe(Effect.catch(legacyAnswer('invalidQuery')));\n\n const handler = respond(\n guardRoute(\n entityConstructor,\n options.guard,\n 'read',\n count,\n ) as Effect.Effect<\n HttpServerResponse.HttpServerResponse,\n EntifixFailure,\n | R\n | EntityFacetCounterFactoryTag\n | GuardServices<G>\n | HttpServerRequest.HttpServerRequest\n | HttpRouter.RouteContext\n >,\n options.policy ?? defaultFailurePolicy,\n );\n\n return HttpRouter.addAll([\n HttpRouter.route('GET', `${base}/$facets`, handler),\n ]);\n};\n"],"names":["EntityFacetCounterFactoryTag","EntityFacetCounterTag","facetCountsUCFactory","envelopeEntityName","makeEntityFacetsEnvelope","parseFacetQueryParams","Effect","HttpRouter","HttpServerRequest","HttpServerResponse","guardRoute","narrowingFor","defaultFailurePolicy","respond","legacyAnswer","makeEntityFacetRoutes","entityConstructor","options","base","basePath","readQueries","gen","request","search","URL","url","searchParams","try","catch","error","narrowed","queries","narrowing","map","query","filtering","undefined","scope","Error","asNarrowing","filter","count","context","verified","empty","Object","fromEntries","member","json","factory","counter","for","organizationId","counts","pipe","prov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E"}
@@ -2,6 +2,7 @@ import { PolicyDecisionTag } from '@entifix/authz';
2
2
  import { type Entity, type EntityConstructor } from '@entifix/core';
3
3
  import { Effect } from 'effect';
4
4
  import { HttpServerRequest, HttpServerResponse } from 'effect/http';
5
+ import { type MetadataCompositions } from './metadata-composition.js';
5
6
  /**
6
7
  * `GET /api/<entity>/$metadata` — what this caller may do with one entity.
7
8
  *
@@ -20,5 +21,5 @@ import { HttpServerRequest, HttpServerResponse } from 'effect/http';
20
21
  * database handle here would leave a vendor with no active organization unable
21
22
  * to see their own affordances.
22
23
  */
23
- export declare const entityMetadataRoute: <TEntity extends Entity>(entityConstructor: EntityConstructor<TEntity>) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, import("@entifix/business").TokenServiceTag | PolicyDecisionTag | HttpServerRequest.HttpServerRequest>;
24
+ export declare const entityMetadataRoute: <TEntity extends Entity>(entityConstructor: EntityConstructor<TEntity>, compositions?: MetadataCompositions) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, import("@entifix/business").TokenServiceTag | PolicyDecisionTag | HttpServerRequest.HttpServerRequest>;
24
25
  //# sourceMappingURL=entity-metadata-route.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"entity-metadata-route.d.ts","sourceRoot":"","sources":["../src/entity-metadata-route.ts"],"names":[],"mappings":"AAEA,OAAO,EAKL,iBAAiB,EAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAEL,KAAK,MAAM,EAEX,KAAK,iBAAiB,EAKvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAKpE;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,mBAAmB,GAAI,OAAO,SAAS,MAAM,EACxD,mBAAmB,iBAAiB,CAAC,OAAO,CAAC,uKA6D5C,CAAC"}
1
+ {"version":3,"file":"entity-metadata-route.d.ts","sourceRoot":"","sources":["../src/entity-metadata-route.ts"],"names":[],"mappings":"AAEA,OAAO,EAKL,iBAAiB,EAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAEL,KAAK,MAAM,EAEX,KAAK,iBAAiB,EAKvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGpE,OAAO,EAGL,KAAK,oBAAoB,EAC1B,MAAM,2BAA2B,CAAC;AAGnC;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,mBAAmB,GAAI,OAAO,SAAS,MAAM,EACxD,mBAAmB,iBAAiB,CAAC,OAAO,CAAC,EAC7C,eAAc,oBAAyB,uKAqFxC,CAAC"}
@@ -1,9 +1,11 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  import { createHash } from 'node:crypto';
2
3
  import { parsePermission, permissionForEntity, permissionForUseCase, PolicyDecisionTag } from '@entifix/authz';
3
4
  import { describeEntityUseCases, ENTITY_ACTIONS, extractMetaEntity, makeEntityMetadataEnvelope, NotFound } from '@entifix/core';
4
5
  import { Effect } from 'effect';
5
6
  import { HttpServerRequest, HttpServerResponse } from 'effect/http';
6
- import { requirePrincipal } from './auth/index.js';
7
+ import { requirePrincipal, withVerifiedContext } from './auth/index.js';
8
+ import { assertCompositionsDeclared, compositionFor } from './metadata-composition.js';
7
9
  import { respond } from './respond.js';
8
10
  /**
9
11
  * `GET /api/<entity>/$metadata` — what this caller may do with one entity.
@@ -22,7 +24,9 @@ import { respond } from './respond.js';
22
24
  * service: the document describes the model, not tenant data, and resolving a
23
25
  * database handle here would leave a vendor with no active organization unable
24
26
  * to see their own affordances.
25
- */ export const entityMetadataRoute = (entityConstructor)=>respond(requirePrincipal((principal)=>Effect.gen(function*() {
27
+ */ export const entityMetadataRoute = (entityConstructor, compositions = {})=>{
28
+ assertCompositionsDeclared(describeEntityUseCases(entityConstructor), compositions);
29
+ return respond(requirePrincipal((principal)=>Effect.gen(function*() {
26
30
  const policy = yield* PolicyDecisionTag;
27
31
  const allows = (permission)=>{
28
32
  const { resource, action } = parsePermission(permission);
@@ -45,7 +49,19 @@ import { respond } from './respond.js';
45
49
  }
46
50
  const document = {
47
51
  actions: ENTITY_ACTIONS.filter((action)=>allows(permissionForEntity(entityConstructor, action))),
48
- useCases: describeEntityUseCases(entityConstructor).filter((descriptor)=>allows(permissionForUseCase(entityConstructor, descriptor.key)))
52
+ useCases: yield* withVerifiedContext(principal, (verified)=>Effect.succeed(describeEntityUseCases(entityConstructor).filter((descriptor)=>allows(permissionForUseCase(entityConstructor, descriptor.key)))// A verb the caller resolves to nothing is omitted, like one
53
+ // they may not invoke; the rest carry what they resolve to.
54
+ .flatMap((descriptor)=>{
55
+ const composition = compositionFor(descriptor, verified, compositions);
56
+ if (composition === 'unreachable') return [];
57
+ return composition === undefined ? [
58
+ descriptor
59
+ ] : [
60
+ _extends({}, descriptor, {
61
+ composition
62
+ })
63
+ ];
64
+ })))
49
65
  };
50
66
  // The ETag hashes the *computed* document, not the descriptor set the
51
67
  // deployment declares. Two principals with different grants get different
@@ -68,6 +84,7 @@ import { respond } from './respond.js';
68
84
  headers: cacheHeaders(etag)
69
85
  });
70
86
  })));
87
+ };
71
88
  /**
72
89
  * The response varies by principal, so it must never land in a shared cache.
73
90
  * `Vary` names **both** credential carriers because the shell reads the access
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/entity-metadata-route.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport {\n parsePermission,\n type Permission,\n permissionForEntity,\n permissionForUseCase,\n PolicyDecisionTag,\n} from '@entifix/authz';\nimport {\n describeEntityUseCases,\n type Entity,\n ENTITY_ACTIONS,\n type EntityConstructor,\n type EntityMetadataDocument,\n extractMetaEntity,\n makeEntityMetadataEnvelope,\n NotFound,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { requirePrincipal } from './auth/index.js';\nimport { respond } from './respond.js';\n\n/**\n * `GET /api/<entity>/$metadata` — what this caller may do with one entity.\n *\n * Mounted **per entity, at a literal path**, not as a `/api/:entity/$metadata`\n * wildcard. `HttpRouter` resolves through `find-my-way-ts`, where a static\n * segment beats a parametric one and there is no backtracking once the\n * parametric branch has matched: alongside an existing `/api/<entity>/:id`, a\n * wildcard `$metadata` route never runs at all — the by-id handler wins with\n * `id === \"$metadata\"`, misses, and answers its own `404`. The endpoint would\n * read as \"this entity has no metadata\" while appearing mounted. A literal wins\n * regardless of registration order, which is why the base exports a route for\n * one entity and each service registers it for each of its own.\n *\n * Deliberately **not** behind `requireOrganization`, even on a tenant-plane\n * service: the document describes the model, not tenant data, and resolving a\n * database handle here would leave a vendor with no active organization unable\n * to see their own affordances.\n */\nexport const entityMetadataRoute = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n) =>\n respond(\n requirePrincipal(principal =>\n Effect.gen(function* () {\n const policy = yield* PolicyDecisionTag;\n const allows = (permission: Permission): boolean => {\n const { resource, action } = parsePermission(permission);\n return policy.decide({\n subject: { roles: principal.roles },\n resource,\n action,\n });\n };\n\n // SECURITY BOUNDARY. The document names domains, entity keys and verbs —\n // it is a map of the model — so an entity the caller may not read answers\n // exactly as one this service does not host. A `403` here would make the\n // endpoint an oracle: walk it and learn the shape of everything you are\n // not allowed to see. Same category as `redactConfiguration`, not\n // diagnostics polish.\n if (!allows(permissionForEntity(entityConstructor, 'read'))) {\n return yield* notFound(entityConstructor);\n }\n\n const document: EntityMetadataDocument = {\n actions: ENTITY_ACTIONS.filter(action =>\n allows(permissionForEntity(entityConstructor, action)),\n ),\n useCases: describeEntityUseCases(entityConstructor).filter(\n descriptor =>\n allows(permissionForUseCase(entityConstructor, descriptor.key)),\n ),\n };\n\n // The ETag hashes the *computed* document, not the descriptor set the\n // deployment declares. Two principals with different grants get different\n // documents from the same model, so a hash of the model would `304` one\n // caller onto another's affordances. Hashing the permission set instead\n // would read `ROLE_PERMISSIONS` directly and go around `PolicyDecisionTag`,\n // so an injected ABAC policy could change affordances without changing the\n // tag. Computing first costs a metadata read and a handful of pure\n // `decide` calls — no IO.\n const body = JSON.stringify(\n makeEntityMetadataEnvelope(entityConstructor, document),\n );\n const etag = `\"${createHash('sha256').update(body).digest('hex')}\"`;\n\n const request = yield* HttpServerRequest.HttpServerRequest;\n if (request.headers['if-none-match'] === etag) {\n return HttpServerResponse.empty({ status: 304 }).pipe(\n HttpServerResponse.setHeaders(cacheHeaders(etag)),\n );\n }\n\n return HttpServerResponse.text(body, {\n contentType: 'application/json',\n headers: cacheHeaders(etag),\n });\n }),\n ),\n );\n\n/**\n * The response varies by principal, so it must never land in a shared cache.\n * `Vary` names **both** credential carriers because the shell reads the access\n * token from the `entifix_at` cookie *or* an `Authorization: Bearer` header, and a\n * cache keyed on only one of them would serve across the other.\n */\nconst cacheHeaders = (etag: string) => ({\n etag,\n 'cache-control': 'private, no-cache',\n vary: 'Cookie, Authorization',\n});\n\n/** Indistinguishable from the `404` a service gives for an entity it does not host. */\nconst notFound = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n) =>\n Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n"],"names":["createHash","parsePermission","permissionForEntity","permissionForUseCase","PolicyDecisionTag","describeEntityUseCases","ENTITY_ACTIONS","extractMetaEntity","makeEntityMetadataEnvelope","NotFound","Effect","HttpServerRequest","HttpServerResponse","requirePrincipal","respond","entityMetadataRoute","entityConstructor","principal","gen","policy","allows","permission","resource","action","decide","subject","roles","notFound","document","actions","filter","useCases","descriptor","key","body","JSON","stringify","etag","update","digest","request","headers","empty","status","pipe","setHeaders","cacheHeaders","text","contentType","vary","fail","entity"],"mappings":"AAAA,SAASA,UAAU,QAAQ,cAAc;AAEzC,SACEC,eAAe,EAEfC,mBAAmB,EACnBC,oBAAoB,EACpBC,iBAAiB,Q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C,MAAM,CAACJ,MAAMK,MAAM,CAAC,OAAO,CAAC,CAAC;YAEnE,MAAMC,UAAU,OAAO7B,kBAAkBA,iBAAiB;YAC1D,IAAI6B,QAAQC,OAAO,CAAC,gBAAgB,KAAKJ,MAAM;gBAC7C,OAAOzB,mBAAmB8B,KAAK,CAAC;oBAAEC,QAAQ;gBAAI,GAAGC,IAAI,CACnDhC,mBAAmBiC,UAAU,CAACC,aAAaT;YAE/C;YAEA,OAAOzB,mBAAmBmC,IAAI,CAACb,MAAM;gBACnCc,aAAa;gBACbP,SAASK,aAAaT;YACxB;QACF,KAEF;AAEJ;;;;;CAKC,GACD,MAAMS,eAAe,CAACT,OAAkB,CAAA;QACtCA;QACA,iBAAiB;QACjBY,MAAM;IACR,CAAA;AAEA,qFAAqF,GACrF,MAAMtB,WAAW,CACfX,oBAEAN,OAAOwC,IAAI,CACT,IAAIzC,SAAS;QAAE0C,QAAQ5C,kBAAkBS,mBAAmBiB,GAAG;IAAC"}
1
+ {"version":3,"sources":["../src/entity-metadata-route.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport {\n parsePermission,\n type Permission,\n permissionForEntity,\n permissionForUseCase,\n PolicyDecisionTag,\n} from '@entifix/authz';\nimport {\n describeEntityUseCases,\n type Entity,\n ENTITY_ACTIONS,\n type EntityConstructor,\n type EntityMetadataDocument,\n extractMetaEntity,\n makeEntityMetadataEnvelope,\n NotFound,\n} from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { requirePrincipal, withVerifiedContext } from './auth/index.js';\nimport {\n assertCompositionsDeclared,\n compositionFor,\n type MetadataCompositions,\n} from './metadata-composition.js';\nimport { respond } from './respond.js';\n\n/**\n * `GET /api/<entity>/$metadata` — what this caller may do with one entity.\n *\n * Mounted **per entity, at a literal path**, not as a `/api/:entity/$metadata`\n * wildcard. `HttpRouter` resolves through `find-my-way-ts`, where a static\n * segment beats a parametric one and there is no backtracking once the\n * parametric branch has matched: alongside an existing `/api/<entity>/:id`, a\n * wildcard `$metadata` route never runs at all — the by-id handler wins with\n * `id === \"$metadata\"`, misses, and answers its own `404`. The endpoint would\n * read as \"this entity has no metadata\" while appearing mounted. A literal wins\n * regardless of registration order, which is why the base exports a route for\n * one entity and each service registers it for each of its own.\n *\n * Deliberately **not** behind `requireOrganization`, even on a tenant-plane\n * service: the document describes the model, not tenant data, and resolving a\n * database handle here would leave a vendor with no active organization unable\n * to see their own affordances.\n */\nexport const entityMetadataRoute = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n compositions: MetadataCompositions = {},\n) => {\n assertCompositionsDeclared(\n describeEntityUseCases(entityConstructor),\n compositions,\n );\n return respond(\n requirePrincipal(principal =>\n Effect.gen(function* () {\n const policy = yield* PolicyDecisionTag;\n const allows = (permission: Permission): boolean => {\n const { resource, action } = parsePermission(permission);\n return policy.decide({\n subject: { roles: principal.roles },\n resource,\n action,\n });\n };\n\n // SECURITY BOUNDARY. The document names domains, entity keys and verbs —\n // it is a map of the model — so an entity the caller may not read answers\n // exactly as one this service does not host. A `403` here would make the\n // endpoint an oracle: walk it and learn the shape of everything you are\n // not allowed to see. Same category as `redactConfiguration`, not\n // diagnostics polish.\n if (!allows(permissionForEntity(entityConstructor, 'read'))) {\n return yield* notFound(entityConstructor);\n }\n\n const document: EntityMetadataDocument = {\n actions: ENTITY_ACTIONS.filter(action =>\n allows(permissionForEntity(entityConstructor, action)),\n ),\n useCases: yield* withVerifiedContext(principal, verified =>\n Effect.succeed(\n describeEntityUseCases(entityConstructor)\n .filter(descriptor =>\n allows(\n permissionForUseCase(entityConstructor, descriptor.key),\n ),\n )\n // A verb the caller resolves to nothing is omitted, like one\n // they may not invoke; the rest carry what they resolve to.\n .flatMap(descriptor => {\n const composition = compositionFor(\n descriptor,\n verified,\n compositions,\n );\n if (composition === 'unreachable') return [];\n return composition === undefined\n ? [descriptor]\n : [{ ...descriptor, composition }];\n }),\n ),\n ),\n };\n\n // The ETag hashes the *computed* document, not the descriptor set the\n // deployment declares. Two principals with different grants get different\n // documents from the same model, so a hash of the model would `304` one\n // caller onto another's affordances. Hashing the permission set instead\n // would read `ROLE_PERMISSIONS` directly and go around `PolicyDecisionTag`,\n // so an injected ABAC policy could change affordances without changing the\n // tag. Computing first costs a metadata read and a handful of pure\n // `decide` calls — no IO.\n const body = JSON.stringify(\n makeEntityMetadataEnvelope(entityConstructor, document),\n );\n const etag = `\"${createHash('sha256').update(body).digest('hex')}\"`;\n\n const request = yield* HttpServerRequest.HttpServerRequest;\n if (request.headers['if-none-match'] === etag) {\n return HttpServerResponse.empty({ status: 304 }).pipe(\n HttpServerResponse.setHeaders(cacheHeaders(etag)),\n );\n }\n\n return HttpServerResponse.text(body, {\n contentType: 'application/json',\n headers: cacheHeaders(etag),\n });\n }),\n ),\n );\n};\n\n/**\n * The response varies by principal, so it must never land in a shared cache.\n * `Vary` names **both** credential carriers because the shell reads the access\n * token from the `entifix_at` cookie *or* an `Authorization: Bearer` header, and a\n * cache keyed on only one of them would serve across the other.\n */\nconst cacheHeaders = (etag: string) => ({\n etag,\n 'cache-control': 'private, no-cache',\n vary: 'Cookie, Authorization',\n});\n\n/** Indistinguishable from the `404` a service gives for an entity it does not host. */\nconst notFound = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n) =>\n Effect.fail(\n new NotFound({ entity: extractMetaEntity(entityConstructor).key }),\n );\n"],"names":["createHash","parsePermission","permissionForEntity","permissionForUseCase","PolicyDecisionTag","describeEntityUseCases","ENTITY_ACTIONS","extractMetaEntity","makeEntityMetadataEnvelope","NotFound","Effect","HttpServerRequest","HttpServerResponse","requirePrincipal","withVerifiedContext","assertCompositionsDeclared","compositionFor","respond","entityMetadataRoute","entityConstructor","compositions","principal","gen","policy","allows","permission","resource","action","decide","subject","roles","notFound","document","actions","filter","useCases","verified","succeed","descriptor","key","flatMap","composition","undefined","body","JSON","stringify","etag","update","digest","request","headers","empty","status","pipe","setHeaders","cache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ossingPolicyTag } from '@entifix/authz';
2
- import type { RepositoryScope, TokenServiceTag } from '@entifix/business';
2
+ import type { RepositoryScope, TokenServiceTag, VerifiedContext } from '@entifix/business';
3
3
  import type { Entity, EntityConstructor, FilterGroup } from '@entifix/core';
4
4
  import type { Effect } from 'effect';
5
5
  import { type RequestPrincipal, type ServiceCrossingTokenTag } from './auth/index.js';
@@ -29,6 +29,8 @@ export type EntityRouteGuard = {
29
29
  /** What a route learned about its caller from its guard. */
30
30
  export interface EntityRouteContext extends RepositoryScope {
31
31
  readonly principal?: RequestPrincipal;
32
+ /** The caller's verified context, built by the guard from the principal. */
33
+ readonly verified?: VerifiedContext;
32
34
  }
33
35
  /**
34
36
  * Which records of an entity a caller may see.
@@ -56,5 +58,5 @@ export type GuardServices<G extends EntityRouteGuard> = TokenServiceTag | Policy
56
58
  * check that enforces it, so the entity routes and the facet route cannot
57
59
  * enforce the same guard differently.
58
60
  */
59
- export declare const guardRoute: <T extends Entity, A, E, R>(entityConstructor: EntityConstructor<T>, guard: EntityRouteGuard, action: Action, use: (context: EntityRouteContext) => Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, TokenServiceTag | PolicyDecisionTag | import("effect/http/HttpServerRequest").HttpServerRequest | R> | Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, ServiceCrossingPolicyTag | import("effect/http/HttpServerRequest").HttpServerRequest | ServiceCrossingTokenTag | R>;
61
+ export declare const guardRoute: <T extends Entity, A, E, R>(entityConstructor: EntityConstructor<T>, guard: EntityRouteGuard, action: Action, use: (context: EntityRouteContext) => Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, TokenServiceTag | PolicyDecisionTag | import("effect/http/HttpServerRequest").HttpServerRequest | Exclude<R, import("@entifix/business").VerifiedContextTag>> | Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, ServiceCrossingPolicyTag | import("effect/http/HttpServerRequest").HttpServerRequest | ServiceCrossingTokenTag | Exclude<R, import("@entifix/business").VerifiedContextTag>>;
60
62
  //# sourceMappingURL=entity-route-guard.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"entity-route-guard.d.ts","sourceRoot":"","sources":["../src/entity-route-guard.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,MAAM,EAEX,KAAK,iBAAiB,EACtB,KAAK,wBAAwB,EAC9B,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,KAAK,EAAE,MAAM,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,EACL,KAAK,gBAAgB,EAKrB,KAAK,uBAAuB,EAC7B,MAAM,iBAAiB,CAAC;AAEzB;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,gBAAgB,GACxB;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAA;CAAE,GAC3B;IAAE,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAA;CAAE,GAC/B;IAAE,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAA;CAAE,GACjC;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAA;CAAE,CAAC;AAElE,4DAA4D;AAC5D,MAAM,WAAW,kBAAmB,SAAQ,eAAe;IACzD,QAAQ,CAAC,SAAS,CAAC,EAAE,gBAAgB,CAAC;CACvC;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,MAAM,IACxC,KAAK,GACL,MAAM,GACN;IACE,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC;IAChC,QAAQ,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,CAAC,K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AAA;CAAE,GACjC;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAA;CAAE,CAAC;AAElE,4DAA4D;AAC5D,MAAM,WAAW,kBAAmB,SAAQ,eAAe;IACzD,QAAQ,CAAC,SAAS,CAAC,EAAE,gBAAgB,CAAC;IACtC,4EAA4E;IAC5E,QAAQ,CAAC,QAAQ,CAAC,EAAE,eAAe,CAAC;CACrC;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,MAAM,IACxC,KAAK,GACL,MAAM,GACN;IACE,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC;IAChC,QAAQ,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,OAAO,CAAC;CAC3C,CAAC;AAEN;;;;GAIG;AACH,MAAM,MAAM,aAAa,CAAC,CAAC,SAAS,gBAAgB,IAChD,eAAe,GACf,iBAAiB,GACjB,CAAC,CAAC,SAAS;IAAE,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAA;CAAE,GACpC,uBAAuB,GAAG,wBAAwB,GAClD,KAAK,CAAC,CAAC;AAEf;;;;;GAKG;AACH,eAAO,MAAM,UAAU,GAAI,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAClD,mBAAmB,iBAAiB,CAAC,CAAC,CAAC,EACvC,OAAO,gBAAgB,EACvB,QAAQ,MAAM,EACd,KAAK,CAAC,OAAO,EAAE,kBAAkB,KAAK,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,qfAyB7D,CAAC"}
@@ -1,5 +1,6 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  import { permissionForEntity } from '@entifix/authz';
2
- import { requireCrossing, requireOrganization, requirePermission, requireServiceCrossing } from './auth/index.js';
3
+ import { requireCrossing, requireOrganization, requirePermission, requireServiceCrossing, withVerifiedContext } from './auth/index.js';
3
4
  /**
4
5
  * Runs `use` behind `guard`, checking the permission the entity derives for
5
6
  * `action` — the one place a derived route turns a stated guard into the
@@ -7,22 +8,27 @@ import { requireCrossing, requireOrganization, requirePermission, requireService
7
8
  * enforce the same guard differently.
8
9
  */ export const guardRoute = (entityConstructor, guard, action, use)=>{
9
10
  const permission = permissionForEntity(entityConstructor, action);
11
+ // Every guard ends here: the context is built once, from what the guard
12
+ // verified, and provided to everything the route runs.
13
+ const verify = (context)=>withVerifiedContext(context.principal, (verified)=>use(_extends({}, context, {
14
+ verified
15
+ })));
10
16
  switch(guard.kind){
11
17
  case 'public':
12
- return use({});
18
+ return verify({});
13
19
  case 'permission':
14
- return requirePermission(permission)((principal)=>use({
20
+ return requirePermission(permission)((principal)=>verify({
15
21
  principal
16
22
  }));
17
23
  case 'organization':
18
- return requireOrganization(permission)((organizationId, principal)=>use({
24
+ return requireOrganization(permission)((organizationId, principal)=>verify({
19
25
  organizationId,
20
26
  principal
21
27
  }));
22
28
  case 'crossing':
23
- return guard.organization ? requireServiceCrossing(permission)((organizationId)=>use({
29
+ return guard.organization ? requireServiceCrossing(permission)((organizationId)=>verify({
24
30
  organizationId
25
- })) : requireCrossing(permission)(use({}));
31
+ })) : requireCrossing(permission)(verify({}));
26
32
  }
27
33
  };
28
34
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/entity-route-guard.ts"],"sourcesContent":["import {\n type Action,\n permissionForEntity,\n type PolicyDecisionTag,\n type ServiceCrossingPolicyTag,\n} from '@entifix/authz';\nimport type { RepositoryScope, TokenServiceTag } from '@entifix/business';\nimport type { Entity, EntityConstructor, FilterGroup } from '@entifix/core';\nimport type { Effect } from 'effect';\n\nimport {\n type RequestPrincipal,\n requireCrossing,\n requireOrganization,\n requirePermission,\n requireServiceCrossing,\n type ServiceCrossingTokenTag,\n} from './auth/index.js';\n\n/**\n * Who may reach a route, and where the organization a per-organization store\n * needs comes from.\n *\n * - `public` — anybody; nothing is checked and no organization is known.\n * - `permission` — a verified session holding the permission the entity\n * derives for the verb.\n * - `organization` — the same, plus the session's active organization, which\n * is what a per-organization store opens.\n * - `crossing` — the fleet's crossing token and no session at all. With\n * `organization: true` the caller names the organization in a header, which\n * only a caller that has proved it is the fleet may do.\n */\nexport type EntityRouteGuard =\n | { readonly kind: 'public' }\n | { readonly kind: 'permission' }\n | { readonly kind: 'organization' }\n | { readonly kind: 'crossing'; readonly organization: boolean };\n\n/** What a route learned about its caller from its guard. */\nexport interface EntityRouteContext extends RepositoryScope {\n readonly principal?: RequestPrincipal;\n}\n\n/**\n * Which records of an entity a caller may see.\n *\n * `filter` narrows a list and `includes` decides a by-id read — both are\n * needed, because `id` is the one member no query can name. `'none'` is a\n * caller who holds the read grant and owns nothing: an empty page and a `404`,\n * never a `403`, because owning no records is not an error.\n */\nexport type EntityReadScope<T extends Entity> =\n | 'all'\n | 'none'\n | {\n readonly filter: FilterGroup<T>;\n readonly includes: (entity: T) => boolean;\n };\n\n/**\n * What a route needs from the host for its guard: a session's services always\n * (a `$metadata` read and a session guard both read the caller), the fleet's\n * crossing services only when a guard is a crossing.\n */\nexport type GuardServices<G extends EntityRouteGuard> =\n | TokenServiceTag\n | PolicyDecisionTag\n | (G extends { readonly kind: 'crossing' }\n ? ServiceCrossingTokenTag | ServiceCrossingPolicyTag\n : never);\n\n/**\n * Runs `use` behind `guard`, checking the permission the entity derives for\n * `action` — the one place a derived route turns a stated guard into the\n * check that enforces it, so the entity routes and the facet route cannot\n * enforce the same guard differently.\n */\nexport const guardRoute = <T extends Entity, A, E, R>(\n entityConstructor: EntityConstructor<T>,\n guard: EntityRouteGuard,\n action: Action,\n use: (context: EntityRouteContext) => Effect.Effect<A, E, R>,\n) => {\n const permission = permissionForEntity(entityConstructor, action);\n switch (guard.kind) {\n case 'public':\n return use({});\n case 'permission':\n return requirePermission(permission)(principal => use({ principal }));\n case 'organization':\n return requireOrganization(permission)((organizationId, principal) =>\n use({ organizationId, principal }),\n );\n case 'crossing':\n return guard.organization\n ? requireServiceCrossing(permission)(organizationId =>\n use({ organizationId }),\n )\n : requireCrossing(permission)(use({}));\n }\n};\n"],"names":["permissionForEntity","requireCrossing","requireOrganization","requirePermission","requireServiceCrossing","guardRoute","entityConstructor","guard","action","use","permission","kind","principal","organizationId","organization"],"mappings":"AAAA,SAEEA,mBAAmB,QAGd,iBAAiB;AAKxB,SAEEC,eAAe,EACfC,mBAAmB,EACnBC,iBAAiB,EACjBC,sBAAsB,QAEjB,kBAAkB;AAsDzB;;;;;CAKC,GACD,OAAO,MAAMC,aAAa,CACxBC,mBACAC,OACAC,QACAC;IAEA,MAAMC,aAAaV,oBAAoBM,mBAAmBE;IAC1D,OAAQD,MAAMI,IAAI;QAChB,KAAK;YACH,OAAOF,IAAI,CAAC;QACd,KAAK;YACH,OAAON,kBAAkBO,YAAYE,CAAAA,YAAaH,IAAI;oBAAEG;gBAAU;QACpE,KAAK;YACH,OAAOV,oBAAoBQ,YAAY,CAACG,gBAAgBD,YACtDH,IAAI;oBAAEI;oBAAgBD;gBAAU;QAEpC,KAAK;YACH,OAAOL,MAAMO,YAAY,GACrBV,uBAAuBM,YAAYG,CAAAA,iBACjCJ,IAAI;oBAAEI;gBAAe,MAEvBZ,gBAAgBS,YAAYD,IAAI,CAAC;IACzC;AACF,EAAE"}
1
+ {"version":3,"sources":["../src/entity-route-guard.ts"],"sourcesContent":["import {\n type Action,\n permissionForEntity,\n type PolicyDecisionTag,\n type ServiceCrossingPolicyTag,\n} from '@entifix/authz';\nimport type {\n RepositoryScope,\n TokenServiceTag,\n VerifiedContext,\n} from '@entifix/business';\nimport type { Entity, EntityConstructor, FilterGroup } from '@entifix/core';\nimport type { Effect } from 'effect';\n\nimport {\n type RequestPrincipal,\n requireCrossing,\n requireOrganization,\n requirePermission,\n requireServiceCrossing,\n type ServiceCrossingTokenTag,\n withVerifiedContext,\n} from './auth/index.js';\n\n/**\n * Who may reach a route, and where the organization a per-organization store\n * needs comes from.\n *\n * - `public` — anybody; nothing is checked and no organization is known.\n * - `permission` — a verified session holding the permission the entity\n * derives for the verb.\n * - `organization` — the same, plus the session's active organization, which\n * is what a per-organization store opens.\n * - `crossing` — the fleet's crossing token and no session at all. With\n * `organization: true` the caller names the organization in a header, which\n * only a caller that has proved it is the fleet may do.\n */\nexport type EntityRouteGuard =\n | { readonly kind: 'public' }\n | { readonly kind: 'permission' }\n | { readonly kind: 'organization' }\n | { readonly kind: 'crossing'; readonly organization: boolean };\n\n/** What a route learned about its caller from its guard. */\nexport interface EntityRouteContext extends RepositoryScope {\n readonly principal?: RequestPrincipal;\n /** The caller's verified context, built by the guard from the principal. */\n readonly verified?: VerifiedContext;\n}\n\n/**\n * Which records of an entity a caller may see.\n *\n * `filter` narrows a list and `includes` decides a by-id read — both are\n * needed, because `id` is the one member no query can name. `'none'` is a\n * caller who holds the read grant and owns nothing: an empty page and a `404`,\n * never a `403`, because owning no records is not an error.\n */\nexport type EntityReadScope<T extends Entity> =\n | 'all'\n | 'none'\n | {\n readonly filter: FilterGroup<T>;\n readonly includes: (entity: T) => boolean;\n };\n\n/**\n * What a route needs from the host for its guard: a session's services always\n * (a `$metadata` read and a session guard both read the caller), the fleet's\n * crossing services only when a guard is a crossing.\n */\nexport type GuardServices<G extends EntityRouteGuard> =\n | TokenServiceTag\n | PolicyDecisionTag\n | (G extends { readonly kind: 'crossing' }\n ? ServiceCrossingTokenTag | ServiceCrossingPolicyTag\n : never);\n\n/**\n * Runs `use` behind `guard`, checking the permission the entity derives for\n * `action` — the one place a derived route turns a stated guard into the\n * check that enforces it, so the entity routes and the facet route cannot\n * enforce the same guard differently.\n */\nexport const guardRoute = <T extends Entity, A, E, R>(\n entityConstructor: EntityConstructor<T>,\n guard: EntityRouteGuard,\n action: Action,\n use: (context: EntityRouteContext) => Effect.Effect<A, E, R>,\n) => {\n const permission = permissionForEntity(entityConstructor, action);\n // Every guard ends here: the context is built once, from what the guard\n // verified, and provided to everything the route runs.\n const verify = (context: EntityRouteContext) =>\n withVerifiedContext(context.principal, verified =>\n use({ ...context, verified }),\n );\n switch (guard.kind) {\n case 'public':\n return verify({});\n case 'permission':\n return requirePermission(permission)(principal => verify({ principal }));\n case 'organization':\n return requireOrganization(permission)((organizationId, principal) =>\n verify({ organizationId, principal }),\n );\n case 'crossing':\n return guard.organization\n ? requireServiceCrossing(permission)(organizationId =>\n verify({ organizationId }),\n )\n : requireCrossing(permission)(verify({}));\n }\n};\n"],"names":["permissionForEntity","requireCrossing","requireOrganization","requirePermission","requireServiceCrossing","withVerifiedContext","guardRoute","entityConstructor","guard","action","use","permission","verify","context","principal","verified","kind","organizationId","organization"],"mappings":";AAAA,SAEEA,mBAAmB,QAGd,iBAAiB;AASxB,SAEEC,eAAe,EACfC,mBAAmB,EACnBC,iBAAiB,EACjBC,sBAAsB,EAEtBC,mBAAmB,QACd,kBAAkB;AAwDzB;;;;;CAKC,GACD,OAAO,MAAMC,aAAa,CACxBC,mBACAC,OACAC,QACAC;IAEA,MAAMC,aAAaX,oBAAoBO,mBAAmBE;IAC1D,wEAAwE;IACxE,uDAAuD;IACvD,MAAMG,SAAS,CAACC,UACdR,oBAAoBQ,QAAQC,SAAS,EAAEC,CAAAA,WACrCL,IAAI,aAAKG;gBAASE;;IAEtB,OAAQP,MAAMQ,IAAI;QAChB,KAAK;YACH,OAAOJ,OAAO,CAAC;QACjB,KAAK;YACH,OAAOT,kBAAkBQ,YAAYG,CAAAA,YAAaF,OAAO;oBAAEE;gBAAU;QACvE,KAAK;YACH,OAAOZ,oBAAoBS,YAAY,CAACM,gBAAgBH,YACtDF,OAAO;oBAAEK;oBAAgBH;gBAAU;QAEvC,KAAK;YACH,OAAON,MAAMU,YAAY,GACrBd,uBAAuBO,YAAYM,CAAAA,iBACjCL,OAAO;oBAAEK;gBAAe,MAE1BhB,gBAAgBU,YAAYC,OAAO,CAAC;IAC5C;AACF,EAAE"}
@@ -3,6 +3,8 @@ import { type EntifixBuildError, type EntifixEnvelopeLink, type Entity, type Ent
3
3
  import { Effect } from 'effect';
4
4
  import { HttpRouter, HttpServerResponse } from 'effect/http';
5
5
  import { type EntityReadScope, type EntityRouteContext, type EntityRouteGuard } from './entity-route-guard.js';
6
+ import type { MetadataCompositions } from './metadata-composition.js';
7
+ import { type NarrowingRules } from './narrowing.js';
6
8
  import { type FailurePolicy } from './respond.js';
7
9
  import { type EntityRouteRefusal, routeFailure } from './route-responses.js';
8
10
  /** The five generic verbs a route set can mount. */
@@ -25,7 +27,17 @@ export interface EntityRoutesOptions<T extends Entity, R, G extends EntityRouteG
25
27
  };
26
28
  /** Defaults to `/api/<entity key>`. */
27
29
  readonly basePath?: `/${string}`;
28
- /** Narrows the reads to what this caller may see. */
30
+ /**
31
+ * Narrows the reads to what this caller may see, as resolver rules over the
32
+ * verified context. Replaces `scope`; a route set naming both throws.
33
+ */
34
+ readonly narrowing?: NarrowingRules<T>;
35
+ /**
36
+ * The variant rules, recipes and catalog the entity's `@useCase()` verbs
37
+ * name, so `$metadata` can report what each resolves to for the caller.
38
+ */
39
+ readonly compositions?: MetadataCompositions;
40
+ /** Narrows the reads to what this caller may see. Superseded by `narrowing`. */
29
41
  readonly scope?: (context: EntityRouteContext) => Effect.Effect<EntityReadScope<T>, never, R>;
30
42
  /**
31
43
  * Runs on every create and update, after the body is read and before the