@entifix/service-shell 0.8.0 → 0.10.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 (64) hide show
  1. package/README.md +7 -7
  2. package/dist/auth/failures.d.ts +23 -0
  3. package/dist/auth/failures.d.ts.map +1 -0
  4. package/dist/auth/failures.js +20 -0
  5. package/dist/auth/failures.js.map +1 -0
  6. package/dist/auth/index.d.ts +1 -0
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js +1 -0
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/auth/require-organization.d.ts +1 -2
  11. package/dist/auth/require-organization.d.ts.map +1 -1
  12. package/dist/auth/require-organization.js +2 -7
  13. package/dist/auth/require-organization.js.map +1 -1
  14. package/dist/auth/require-principal.d.ts +3 -3
  15. package/dist/auth/require-principal.d.ts.map +1 -1
  16. package/dist/auth/require-principal.js +6 -14
  17. package/dist/auth/require-principal.js.map +1 -1
  18. package/dist/auth/require-service-crossing.d.ts +3 -3
  19. package/dist/auth/require-service-crossing.d.ts.map +1 -1
  20. package/dist/auth/require-service-crossing.js +18 -21
  21. package/dist/auth/require-service-crossing.js.map +1 -1
  22. package/dist/auth/shared-token.d.ts +2 -2
  23. package/dist/auth/shared-token.d.ts.map +1 -1
  24. package/dist/auth/shared-token.js +7 -8
  25. package/dist/auth/shared-token.js.map +1 -1
  26. package/dist/entity-facet-routes.d.ts +38 -0
  27. package/dist/entity-facet-routes.d.ts.map +1 -0
  28. package/dist/entity-facet-routes.js +67 -0
  29. package/dist/entity-facet-routes.js.map +1 -0
  30. package/dist/entity-metadata-route.d.ts +1 -1
  31. package/dist/entity-metadata-route.d.ts.map +1 -1
  32. package/dist/entity-metadata-route.js +6 -9
  33. package/dist/entity-metadata-route.js.map +1 -1
  34. package/dist/entity-route-guard.d.ts +60 -0
  35. package/dist/entity-route-guard.d.ts.map +1 -0
  36. package/dist/entity-route-guard.js +29 -0
  37. package/dist/entity-route-guard.js.map +1 -0
  38. package/dist/entity-routes.d.ts +17 -61
  39. package/dist/entity-routes.d.ts.map +1 -1
  40. package/dist/entity-routes.js +19 -77
  41. package/dist/entity-routes.js.map +1 -1
  42. package/dist/health-routes.d.ts.map +1 -1
  43. package/dist/health-routes.js +3 -2
  44. package/dist/health-routes.js.map +1 -1
  45. package/dist/index.d.ts +2 -0
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +2 -0
  48. package/dist/index.js.map +1 -1
  49. package/dist/make-service.d.ts.map +1 -1
  50. package/dist/make-service.js +4 -2
  51. package/dist/make-service.js.map +1 -1
  52. package/dist/respond.d.ts +92 -0
  53. package/dist/respond.d.ts.map +1 -0
  54. package/dist/respond.js +178 -0
  55. package/dist/respond.js.map +1 -0
  56. package/dist/route-responses.d.ts +44 -0
  57. package/dist/route-responses.d.ts.map +1 -0
  58. package/dist/route-responses.js +104 -0
  59. package/dist/route-responses.js.map +1 -0
  60. package/dist/service-description-route.d.ts +1 -1
  61. package/dist/service-description-route.d.ts.map +1 -1
  62. package/dist/service-description-route.js +2 -1
  63. package/dist/service-description-route.js.map +1 -1
  64. package/package.json +12 -12
package/README.md CHANGED
@@ -16,17 +16,17 @@ pnpm add @opentelemetry/api @effect/opentelemetry @opentelemetry/sdk-trace-base
16
16
 
17
17
  ## Entry points
18
18
 
19
- | Import | What it holds |
20
- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
21
- | `@entifix/service-shell` | What a route set is written against: `makeEntityRoutes`, `requirePrincipal`, `requirePermission`, `requireOrganization`, `requireServiceCrossing`, `requireSharedToken`, `entityMetadataRoute`, health and SSE routes |
22
- | `@entifix/service-shell/runtime` | Running a service: `makeService`, `makeServerLayer`, `loadRemoteConfiguration`. Needs `@effect/platform-node` |
23
- | `@entifix/service-shell/observability` | `makeObservabilityLayer` and the OpenTelemetry wiring. Needs `@effect/opentelemetry` and the OpenTelemetry SDK packages |
24
- | `@entifix/service-shell/testing` | `serveTestService`, a service on an ephemeral port for a spec |
19
+ | Import | What it holds |
20
+ | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
21
+ | `@entifix/service-shell` | What a route set is written against: `makeEntityRoutes`, `makeEntityFacetRoutes` (`GET <entity>/$facets`, over the host's `EntityFacetCounterFactoryTag`), `requirePrincipal`, `requirePermission`, `requireOrganization`, `requireServiceCrossing`, `requireSharedToken`, `entityMetadataRoute`, health and SSE routes |
22
+ | `@entifix/service-shell/runtime` | Running a service: `makeService`, `makeServerLayer`, `loadRemoteConfiguration`. Needs `@effect/platform-node` |
23
+ | `@entifix/service-shell/observability` | `makeObservabilityLayer` and the OpenTelemetry wiring. Needs `@effect/opentelemetry` and the OpenTelemetry SDK packages |
24
+ | `@entifix/service-shell/testing` | `serveTestService`, a service on an ephemeral port for a spec |
25
25
 
26
26
  The runtime and observability halves are optional peers: a package that only declares routes installs neither. The configuration service's URL and credential, and the header and secret that gate `GET /api/$service`, are values the host passes — `loadRemoteConfiguration({ url, headers })` and `makeService({ description: { header, token } })`.
27
27
 
28
28
  ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
29
- | `@entifix/service-shell` | `makeService`, `makeServerLayer`, `makeEntityRoutes`, `requirePrincipal`, `requirePermission`, `requireOrganization`, `entityMetadataRoute`, `loadRemoteConfiguration`, `makeObservabilityLayer`, `serveTestService` |
29
+ | `@entifix/service-shell` | `makeService`, `makeServerLayer`, `makeEntityRoutes`, `makeEntityFacetRoutes`, `requirePrincipal`, `requirePermission`, `requireOrganization`, `entityMetadataRoute`, `loadRemoteConfiguration`, `makeObservabilityLayer`, `serveTestService` |
30
30
 
31
31
  ---
32
32
 
@@ -0,0 +1,23 @@
1
+ import { Effect } from 'effect';
2
+ import type { HttpServerResponse } from 'effect/http';
3
+ import { problemResponse } from '../respond.js';
4
+ declare const NoActiveOrganization_base: import("effect/Schema").Class<NoActiveOrganization, import("effect/Schema").TaggedStruct<"NoActiveOrganization", Record<never, never>>, import("effect/Cause").YieldableError & import("@entifix/core").FailureFacts<"noActiveOrganization", "conflict">>;
5
+ /**
6
+ * A signed-in caller whose session names no organization, on a route that acts
7
+ * for one. A member of several organizations hits it before choosing one; the
8
+ * code is what a client renders as "select an organization" instead of
9
+ * "forbidden".
10
+ */
11
+ export declare class NoActiveOrganization extends NoActiveOrganization_base {
12
+ }
13
+ /**
14
+ * A guard's refusal, answered as the problem body \`respond\` would write.
15
+ *
16
+ * ⚠️ The guards answer rather than fail because a host's routes that are not
17
+ * yet mounted through \`mountRoutes\` would otherwise meet an unhandled typed
18
+ * failure where they used to meet a \`401\`. The wire is the same either way;
19
+ * the guard functions go when the endpoint router replaces them.
20
+ */
21
+ export declare const refuse: (failure: Parameters<typeof problemResponse>[0]) => Effect.Effect<HttpServerResponse.HttpServerResponse>;
22
+ export {};
23
+ //# sourceMappingURL=failures.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"failures.d.ts","sourceRoot":"","sources":["../../src/auth/failures.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;;AAEhD;;;;;GAKG;AACH,qBAAa,oBAAqB,SAAQ,yBAGzC;CAAG;AAEJ;;;;;;;GAOG;AACH,eAAO,MAAM,MAAM,GACjB,SAAS,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC,CAAC,CAAC,KAC7C,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,kBAAkB,CACZ,CAAC"}
@@ -0,0 +1,20 @@
1
+ import { Failure } from '@entifix/core';
2
+ import { Effect } from 'effect';
3
+ import { problemResponse } from '../respond.js';
4
+ /**
5
+ * A signed-in caller whose session names no organization, on a route that acts
6
+ * for one. A member of several organizations hits it before choosing one; the
7
+ * code is what a client renders as "select an organization" instead of
8
+ * "forbidden".
9
+ */ export class NoActiveOrganization extends Failure.conflict()('NoActiveOrganization', 'noActiveOrganization') {
10
+ }
11
+ /**
12
+ * A guard's refusal, answered as the problem body \`respond\` would write.
13
+ *
14
+ * ⚠️ The guards answer rather than fail because a host's routes that are not
15
+ * yet mounted through \`mountRoutes\` would otherwise meet an unhandled typed
16
+ * failure where they used to meet a \`401\`. The wire is the same either way;
17
+ * the guard functions go when the endpoint router replaces them.
18
+ */ export const refuse = (failure)=>Effect.succeed(problemResponse(failure));
19
+
20
+ //# sourceMappingURL=failures.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auth/failures.ts"],"sourcesContent":["import { Failure } from '@entifix/core';\nimport { Effect } from 'effect';\nimport type { HttpServerResponse } from 'effect/http';\n\nimport { problemResponse } from '../respond.js';\n\n/**\n * A signed-in caller whose session names no organization, on a route that acts\n * for one. A member of several organizations hits it before choosing one; the\n * code is what a client renders as \"select an organization\" instead of\n * \"forbidden\".\n */\nexport class NoActiveOrganization extends Failure.conflict<NoActiveOrganization>()(\n 'NoActiveOrganization',\n 'noActiveOrganization',\n) {}\n\n/**\n * A guard's refusal, answered as the problem body \\`respond\\` would write.\n *\n * ⚠️ The guards answer rather than fail because a host's routes that are not\n * yet mounted through \\`mountRoutes\\` would otherwise meet an unhandled typed\n * failure where they used to meet a \\`401\\`. The wire is the same either way;\n * the guard functions go when the endpoint router replaces them.\n */\nexport const refuse = (\n failure: Parameters<typeof problemResponse>[0],\n): Effect.Effect<HttpServerResponse.HttpServerResponse> =>\n Effect.succeed(problemResponse(failure));\n"],"names":["Failure","Effect","problemResponse","NoActiveOrganization","conflict","refuse","failure","succeed"],"mappings":"AAAA,SAASA,OAAO,QAAQ,gBAAgB;AACxC,SAASC,MAAM,QAAQ,SAAS;AAGhC,SAASC,eAAe,QAAQ,gBAAgB;AAEhD;;;;;CAKC,GACD,OAAO,MAAMC,6BAA6BH,QAAQI,QAAQ,GACxD,wBACA;AACC;AAEH;;;;;;;CAOC,GACD,OAAO,MAAMC,SAAS,CACpBC,UAEAL,OAAOM,OAAO,CAACL,gBAAgBI,UAAU"}
@@ -1,3 +1,4 @@
1
+ export * from './failures.js';
1
2
  export * from './require-organization.js';
2
3
  export * from './require-principal.js';
3
4
  export * from './require-service-crossing.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,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"}
@@ -1,3 +1,4 @@
1
+ export * from './failures.js';
1
2
  export * from './require-organization.js';
2
3
  export * from './require-principal.js';
3
4
  export * from './require-service-crossing.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/index.ts"],"sourcesContent":["export * 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,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';\n"],"names":[],"mappings":"AAAA,cAAc,gBAAgB;AAC9B,cAAc,4BAA4B;AAC1C,cAAc,yBAAyB;AACvC,cAAc,gCAAgC;AAC9C,cAAc,oBAAoB"}
@@ -1,6 +1,5 @@
1
1
  import type { Permission } from '@entifix/authz';
2
2
  import { Effect } from 'effect';
3
- import { HttpServerResponse } from 'effect/http';
4
3
  import { type RequestPrincipal } from './require-principal.js';
5
4
  /**
6
5
  * Guard a **tenant-plane** handler: authenticate, check the permission, and
@@ -29,5 +28,5 @@ import { type RequestPrincipal } from './require-principal.js';
29
28
  * the other path honours a caller-named organization only *after* the caller has
30
29
  * proved it is the fleet.
31
30
  */
32
- export declare const requireOrganization: (permission: Permission) => <A, E, R>(use: (organizationId: string, principal: RequestPrincipal) => Effect.Effect<A, E, R>) => Effect.Effect<HttpServerResponse.HttpServerResponse | A, import("effect/http/HttpBody").HttpBodyError | E, import("@entifix/authz").PolicyDecisionTag | import("@entifix/business").TokenServiceTag | import("effect/http/HttpServerRequest").HttpServerRequest | R>;
31
+ export declare const requireOrganization: (permission: Permission) => <A, E, R>(use: (organizationId: string, principal: RequestPrincipal) => Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, import("@entifix/business").TokenServiceTag | import("@entifix/authz").PolicyDecisionTag | import("effect/http/HttpServerRequest").HttpServerRequest | R>;
33
32
  //# sourceMappingURL=require-organization.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"require-organization.d.ts","sourceRoot":"","sources":["../../src/auth/require-organization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EACL,KAAK,gBAAgB,EAEtB,MAAM,wBAAwB,CAAC;AAkBhC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,mBAAmB,GAC7B,YAAY,UAAU,MACtB,CAAC,EAAE,CAAC,EAAE,CAAC,EACN,KAAK,CACH,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,gBAAgB,KACxB,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,yQAa1B,CAAC"}
1
+ {"version":3,"file":"require-organization.d.ts","sourceRoot":"","sources":["../../src/auth/require-organization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,OAAO,EACL,KAAK,gBAAgB,EAEtB,MAAM,wBAAwB,CAAC;AAehC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,mBAAmB,GAC7B,YAAY,UAAU,MACtB,CAAC,EAAE,CAAC,EAAE,CAAC,EACN,KAAK,CACH,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,gBAAgB,KACxB,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,gPAa1B,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { Effect } from 'effect';
2
- import { HttpServerResponse } from 'effect/http';
2
+ import { NoActiveOrganization, refuse } from './failures.js';
3
3
  import { requirePermission } from './require-principal.js';
4
4
  /**
5
5
  * `409` rather than `403`: the caller is authenticated and permitted, but the
@@ -11,12 +11,7 @@ import { requirePermission } from './require-principal.js';
11
11
  * organization" instead of "forbidden" — a claim a host has to check its
12
12
  * catalog against, because for a while it was simply false and the code
13
13
  * reached the browser as its own literal text.
14
- */ const noOrganization = HttpServerResponse.json({
15
- error: 'no active organization',
16
- code: 'noActiveOrganization'
17
- }, {
18
- status: 409
19
- });
14
+ */ const noOrganization = refuse(new NoActiveOrganization());
20
15
  /**
21
16
  * Guard a **tenant-plane** handler: authenticate, check the permission, and
22
17
  * require that the session names an organization.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/require-organization.ts"],"sourcesContent":["import type { Permission } from '@entifix/authz';\nimport { Effect } from 'effect';\nimport { HttpServerResponse } from 'effect/http';\n\nimport {\n type RequestPrincipal,\n requirePermission,\n} from './require-principal.js';\n\n/**\n * `409` rather than `403`: the caller is authenticated and permitted, but the\n * session names no organization, so there is no storage to read. An operator\n * hits this by design — crossing into a tenant is an explicit, audited\n * act-as-organization re-mint, never a widening of the default —\n * and a member of several organizations hits it before choosing one. The `code`\n * is a key in the shared `errors` catalog, so a client renders \"select an\n * organization\" instead of \"forbidden\" — a claim a host has to check its\n * catalog against, because for a while it was simply false and the code\n * reached the browser as its own literal text.\n */\nconst noOrganization = HttpServerResponse.json(\n { error: 'no active organization', code: 'noActiveOrganization' },\n { status: 409 },\n);\n\n/**\n * Guard a **tenant-plane** handler: authenticate, check the permission, and\n * require that the session names an organization.\n *\n * **This is the first of exactly two ways a request resolves the organization\n * it acts for, and the only *user-facing* one**.\n * The second is {@link requireServiceCrossing}: an explicit `organizationId`\n * presented with a service token *and* a narrow route permission, for a\n * platform-plane caller acting for an organization it was handed rather than one\n * it picked.\n *\n * There is no third path, no fallback and no operator branch. A request\n * satisfying neither guard never reaches a tenant handle at all, which is what\n * keeps the most sensitive capability in the system from being the *absence* of\n * a condition.\n *\n * The organization is handed to the handler so it can resolve its own storage\n * through a `TenantDatabaseResolver`. Resolution happens **inside the request**\n * — the connection pool is a boot-time `Layer`, and a per-request `Layer` would\n * rebuild the pool per request.\n *\n * Here the value comes from the verified token and nowhere else. A route\n * parameter or a body field naming an organization would be caller-controlled,\n * which is the whole failure this guard exists to prevent — and is exactly why\n * the other path honours a caller-named organization only *after* the caller has\n * proved it is the fleet.\n */\nexport const requireOrganization =\n (permission: Permission) =>\n <A, E, R>(\n use: (\n organizationId: string,\n principal: RequestPrincipal,\n ) => Effect.Effect<A, E, R>,\n ) =>\n requirePermission(permission)(principal =>\n // `Effect.gen` rather than a ternary: the two branches have different\n // success types, and a conditional expression would unify them against\n // the first one instead of widening. `requirePrincipal` yields for the\n // same reason.\n Effect.gen(function* () {\n if (principal.organizationId === undefined) {\n return yield* noOrganization;\n }\n return yield* use(principal.organizationId, principal);\n }),\n );\n"],"names":["Effect","HttpServerResponse","requirePermission","noOrganization","json","error","code","status","requireOrganization","permission","use","principal","gen","organizationId","undefined"],"mappings":"AACA,SAASA,MAAM,QAAQ,SAAS;AAChC,SAASC,kBAAkB,QAAQ,cAAc;AAEjD,SAEEC,iBAAiB,QACZ,yBAAyB;AAEhC;;;;;;;;;;CAUC,GACD,MAAMC,iBAAiBF,mBAAmBG,IAAI,CAC5C;IAAEC,OAAO;IAA0BC,MAAM;AAAuB,GAChE;IAAEC,QAAQ;AAAI;AAGhB;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,MAAMC,sBACX,CAACC,aACD,CACEC,MAKAR,kBAAkBO,YAAYE,CAAAA,YAC5B,sEAAsE;YACtE,uEAAuE;YACvE,uEAAuE;YACvE,eAAe;YACfX,OAAOY,GAAG,CAAC;gBACT,IAAID,UAAUE,cAAc,KAAKC,WAAW;oBAC1C,OAAO,OAAOX;gBAChB;gBACA,OAAO,OAAOO,IAAIC,UAAUE,cAAc,EAAEF;YAC9C,IACA"}
1
+ {"version":3,"sources":["../../src/auth/require-organization.ts"],"sourcesContent":["import type { Permission } from '@entifix/authz';\nimport { Effect } from 'effect';\n\nimport { NoActiveOrganization, refuse } from './failures.js';\nimport {\n type RequestPrincipal,\n requirePermission,\n} from './require-principal.js';\n\n/**\n * `409` rather than `403`: the caller is authenticated and permitted, but the\n * session names no organization, so there is no storage to read. An operator\n * hits this by design — crossing into a tenant is an explicit, audited\n * act-as-organization re-mint, never a widening of the default —\n * and a member of several organizations hits it before choosing one. The `code`\n * is a key in the shared `errors` catalog, so a client renders \"select an\n * organization\" instead of \"forbidden\" — a claim a host has to check its\n * catalog against, because for a while it was simply false and the code\n * reached the browser as its own literal text.\n */\nconst noOrganization = refuse(new NoActiveOrganization());\n\n/**\n * Guard a **tenant-plane** handler: authenticate, check the permission, and\n * require that the session names an organization.\n *\n * **This is the first of exactly two ways a request resolves the organization\n * it acts for, and the only *user-facing* one**.\n * The second is {@link requireServiceCrossing}: an explicit `organizationId`\n * presented with a service token *and* a narrow route permission, for a\n * platform-plane caller acting for an organization it was handed rather than one\n * it picked.\n *\n * There is no third path, no fallback and no operator branch. A request\n * satisfying neither guard never reaches a tenant handle at all, which is what\n * keeps the most sensitive capability in the system from being the *absence* of\n * a condition.\n *\n * The organization is handed to the handler so it can resolve its own storage\n * through a `TenantDatabaseResolver`. Resolution happens **inside the request**\n * — the connection pool is a boot-time `Layer`, and a per-request `Layer` would\n * rebuild the pool per request.\n *\n * Here the value comes from the verified token and nowhere else. A route\n * parameter or a body field naming an organization would be caller-controlled,\n * which is the whole failure this guard exists to prevent — and is exactly why\n * the other path honours a caller-named organization only *after* the caller has\n * proved it is the fleet.\n */\nexport const requireOrganization =\n (permission: Permission) =>\n <A, E, R>(\n use: (\n organizationId: string,\n principal: RequestPrincipal,\n ) => Effect.Effect<A, E, R>,\n ) =>\n requirePermission(permission)(principal =>\n // `Effect.gen` rather than a ternary: the two branches have different\n // success types, and a conditional expression would unify them against\n // the first one instead of widening. `requirePrincipal` yields for the\n // same reason.\n Effect.gen(function* () {\n if (principal.organizationId === undefined) {\n return yield* noOrganization;\n }\n return yield* use(principal.organizationId, principal);\n }),\n );\n"],"names":["Effect","NoActiveOrganization","refuse","requirePermission","noOrganization","requireOrganization","permission","use","principal","gen","organizationId","undefined"],"mappings":"AACA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAASC,oBAAoB,EAAEC,MAAM,QAAQ,gBAAgB;AAC7D,SAEEC,iBAAiB,QACZ,yBAAyB;AAEhC;;;;;;;;;;CAUC,GACD,MAAMC,iBAAiBF,OAAO,IAAID;AAElC;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,MAAMI,sBACX,CAACC,aACD,CACEC,MAKAJ,kBAAkBG,YAAYE,CAAAA,YAC5B,sEAAsE;YACtE,uEAAuE;YACvE,uEAAuE;YACvE,eAAe;YACfR,OAAOS,GAAG,CAAC;gBACT,IAAID,UAAUE,cAAc,KAAKC,WAAW;oBAC1C,OAAO,OAAOP;gBAChB;gBACA,OAAO,OAAOG,IAAIC,UAAUE,cAAc,EAAEF;YAC9C,IACA"}
@@ -1,7 +1,7 @@
1
1
  import { type Permission, PolicyDecisionTag } from '@entifix/authz';
2
2
  import { type TokenClaims, TokenServiceTag } from '@entifix/business';
3
3
  import { Effect } from 'effect';
4
- import { HttpServerRequest, HttpServerResponse } from 'effect/http';
4
+ import { HttpServerRequest } from 'effect/http';
5
5
  /**
6
6
  * The authenticated subject as a service sees it. Structurally identical to
7
7
  * `business-ts-authn`'s `Principal`, re-declared here so the shared shell does
@@ -56,7 +56,7 @@ export interface RequestPrincipal {
56
56
  * missing or invalid token is a `401`; the wrapped handler's own errors are
57
57
  * left intact.
58
58
  */
59
- export declare const requirePrincipal: <A, E, R>(use: (principal: RequestPrincipal) => Effect.Effect<A, E, R>) => Effect.Effect<HttpServerResponse.HttpServerResponse | A, import("effect/http/HttpBody").HttpBodyError | E, TokenServiceTag | HttpServerRequest.HttpServerRequest | R>;
59
+ export declare const requirePrincipal: <A, E, R>(use: (principal: RequestPrincipal) => Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, TokenServiceTag | HttpServerRequest.HttpServerRequest | R>;
60
60
  /**
61
61
  * Guard a handler behind a permission. Authenticates as above, then asks
62
62
  * {@link PolicyDecisionTag} whether this subject may perform the action — so
@@ -66,5 +66,5 @@ export declare const requirePrincipal: <A, E, R>(use: (principal: RequestPrincip
66
66
  * **This is the authorization boundary.** Filtering a nav menu or hiding a page
67
67
  * is presentation; a route that skips this guard is open regardless.
68
68
  */
69
- export declare const requirePermission: (permission: Permission) => <A, E, R>(use: (principal: RequestPrincipal) => Effect.Effect<A, E, R>) => Effect.Effect<HttpServerResponse.HttpServerResponse | A, import("effect/http/HttpBody").HttpBodyError | E, PolicyDecisionTag | TokenServiceTag | HttpServerRequest.HttpServerRequest | R>;
69
+ export declare const requirePermission: (permission: Permission) => <A, E, R>(use: (principal: RequestPrincipal) => Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, TokenServiceTag | PolicyDecisionTag | HttpServerRequest.HttpServerRequest | R>;
70
70
  //# sourceMappingURL=require-principal.d.ts.map
@@ -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,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEpE;;;;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,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,QAAQ,CAAC,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACxD;AAmED;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,GAAI,CAAC,EAAE,CAAC,EAAE,CAAC,EACtC,KAAK,CAAC,SAAS,EAAE,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,CAAC,CAAC;CACxD;AA6DD;;;;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"}
@@ -1,8 +1,9 @@
1
1
  import { parsePermission, PolicyDecisionTag } from '@entifix/authz';
2
2
  import { TokenServiceTag } from '@entifix/business';
3
- import { ACCESS_COOKIE } from '@entifix/core';
3
+ import { ACCESS_COOKIE, Forbidden, Unauthenticated } from '@entifix/core';
4
4
  import { Effect, Option } from 'effect';
5
- import { HttpServerRequest, HttpServerResponse } from 'effect/http';
5
+ import { HttpServerRequest } from 'effect/http';
6
+ import { refuse } from './failures.js';
6
7
  /** Extract a bearer token from an `Authorization` header, if present. */ const bearerToken = (authorization)=>{
7
8
  if (authorization === undefined) {
8
9
  return undefined;
@@ -34,19 +35,10 @@ import { HttpServerRequest, HttpServerResponse } from 'effect/http';
34
35
  // `code` is a key in the shared `errors` catalog; `error` stays English for
35
36
  // logs. `permission` is deliberately still in the 403 — it says which grant was
36
37
  // missing, which is diagnostic, not a leak.
37
- const unauthenticated = HttpServerResponse.json({
38
- error: 'unauthenticated',
39
- code: 'unauthenticated'
40
- }, {
41
- status: 401
42
- });
43
- const forbidden = (permission)=>HttpServerResponse.json({
44
- error: 'forbidden',
45
- code: 'forbidden',
38
+ const unauthenticated = refuse(new Unauthenticated());
39
+ const forbidden = (permission)=>refuse(new Forbidden({
46
40
  permission
47
- }, {
48
- status: 403
49
- });
41
+ }));
50
42
  /**
51
43
  * Resolve the caller's principal from the request, or `None`. Reads the token
52
44
  * from the `entifix_at` cookie (the Next app forwards it) or an
@@ -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 } from '@entifix/core';\nimport { Effect, Option } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\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 = HttpServerResponse.json(\n { error: 'unauthenticated', code: 'unauthenticated' },\n { status: 401 },\n);\n\nconst forbidden = (permission: Permission) =>\n HttpServerResponse.json(\n { error: 'forbidden', code: 'forbidden', permission },\n { status: 403 },\n );\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","Effect","Option","HttpServerRequest","HttpServerResponse","bearerToken","authorization","undefined","scheme","value","split","toLowerCase","claimsToPrincipal","claims","userId","subject","sessionId","roles","organizationId","activeOrganizationId","partyRole","partyId","expiresAt","exp","attributes","unauthenticated","json","error","code","status","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,a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AAiB;IACtD,MAAMgC,SACJD,6BAAAA,IAAIE,OAAO,CAACpC,cAAc,YAA1BkC,6BAA8B7B,YAAY6B,IAAIG,OAAO,CAAC,gBAAgB;IACxE,IAAIF,UAAU5B,WAAW;QACvB,OAAOL,OAAOoC,IAAI;IACpB;IAEA,MAAMC,SAAS,OAAOxC;IACtB,MAAMc,SAAS,OAAO0B,OAAOC,MAAM,CAACL,OAAOM,IAAI,CAACxC,OAAOyC,MAAM;IAC7D,OAAOxC,OAAOyC,GAAG,CAAC9B,QAAQD;AAC5B;AAEA;;;;CAIC,GACD,OAAO,MAAMgC,mBAAmB,CAC9BC,MAEA5C,OAAOgC,GAAG,CAAC;QACT,MAAMa,YAAY,OAAOd;QACzB,IAAI9B,OAAO6C,MAAM,CAACD,YAAY;YAC5B,OAAO,OAAOrB;QAChB;QACA,OAAO,OAAOoB,IAAIC,UAAUrC,KAAK;IACnC,GAAG;AAEL;;;;;;;;CAQC,GACD,OAAO,MAAMuC,oBACX,CAACjB,aACD,CAAUc,MACR5C,OAAOgC,GAAG,CAAC;YACT,MAAMa,YAAY,OAAOd;YACzB,IAAI9B,OAAO6C,MAAM,CAACD,YAAY;gBAC5B,OAAO,OAAOrB;YAChB;YAEA,MAAM,EAAEwB,QAAQ,EAAEC,MAAM,EAAE,GAAGrD,gBAAgBkC;YAC7C,MAAMoB,SAAS,OAAOrD;YACtB,MAAMsD,UAAUD,OAAOE,MAAM,CAAC;gBAC5BtC,SAAS;oBAAEE,OAAO6B,UAAUrC,KAAK,CAACQ,KAAK;gBAAC;gBACxCgC;gBACAC;YACF;YACA,IAAI,CAACE,SAAS;gBACZ,OAAO,OAAOtB,UAAUC;YAC1B;YAEA,OAAO,OAAOc,IAAIC,UAAUrC,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 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,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,MAAM4B,mBAAmB,CAC9BC,MAEAxC,OAAO4B,GAAG,CAAC;QACT,MAAMa,YAAY,OAAOd;QACzB,IAAI1B,OAAOyC,MAAM,CAACD,YAAY;YAC5B,OAAO,OAAOjB;QAChB;QACA,OAAO,OAAOgB,IAAIC,UAAUjC,KAAK;IACnC,GAAG;AAEL;;;;;;;;CAQC,GACD,OAAO,MAAMmC,oBACX,CAACjB,aACD,CAAUc,MACRxC,OAAO4B,GAAG,CAAC;YACT,MAAMa,YAAY,OAAOd;YACzB,IAAI1B,OAAOyC,MAAM,CAACD,YAAY;gBAC5B,OAAO,OAAOjB;YAChB;YAEA,MAAM,EAAEoB,QAAQ,EAAEC,MAAM,EAAE,GAAGnD,gBAAgBgC;YAC7C,MAAMoB,SAAS,OAAOnD;YACtB,MAAMoD,UAAUD,OAAOE,MAAM,CAAC;gBAC5BlC,SAAS;oBAAEE,OAAOyB,UAAUjC,KAAK,CAACQ,KAAK;gBAAC;gBACxC4B;gBACAC;YACF;YACA,IAAI,CAACE,SAAS;gBACZ,OAAO,OAAOtB,UAAUC;YAC1B;YAEA,OAAO,OAAOc,IAAIC,UAAUjC,KAAK;QACnC,GAAG"}
@@ -1,6 +1,6 @@
1
1
  import { type Permission, ServiceCrossingPolicyTag } from '@entifix/authz';
2
2
  import { Context, Effect } from 'effect';
3
- import { HttpServerRequest, HttpServerResponse } from 'effect/http';
3
+ import { HttpServerRequest } from 'effect/http';
4
4
  /**
5
5
  * The header carrying the crossing secret.
6
6
  *
@@ -83,7 +83,7 @@ export declare class ServiceCrossingTokenTag extends ServiceCrossingTokenTag_bas
83
83
  * the key, and the request log. What would remove it is an RS256 service token
84
84
  * carrying a scope claim, which is named work rather than a gap nobody noticed.
85
85
  */
86
- export declare const requireServiceCrossing: (permission: Permission) => <A, E, R>(use: (organizationId: string) => Effect.Effect<A, E, R>) => Effect.Effect<HttpServerResponse.HttpServerResponse | A, import("effect/http/HttpBody").HttpBodyError | E, ServiceCrossingPolicyTag | HttpServerRequest.HttpServerRequest | ServiceCrossingTokenTag | R>;
86
+ export declare const requireServiceCrossing: (permission: Permission) => <A, E, R>(use: (organizationId: string) => Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, ServiceCrossingPolicyTag | HttpServerRequest.HttpServerRequest | ServiceCrossingTokenTag | R>;
87
87
  /**
88
88
  * The same fleet check, for a participant that has **no organization to name**.
89
89
  *
@@ -105,6 +105,6 @@ export declare const requireServiceCrossing: (permission: Permission) => <A, E,
105
105
  * holding it can act, bounded by the permission and by which slices are
106
106
  * configured with the key.
107
107
  */
108
- export declare const requireCrossing: (permission: Permission) => <A, E, R>(route: Effect.Effect<A, E, R>) => Effect.Effect<HttpServerResponse.HttpServerResponse | A, import("effect/http/HttpBody").HttpBodyError | E, ServiceCrossingPolicyTag | HttpServerRequest.HttpServerRequest | ServiceCrossingTokenTag | R>;
108
+ export declare const requireCrossing: (permission: Permission) => <A, E, R>(route: Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, ServiceCrossingPolicyTag | HttpServerRequest.HttpServerRequest | ServiceCrossingTokenTag | R>;
109
109
  export {};
110
110
  //# sourceMappingURL=require-service-crossing.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"require-service-crossing.d.ts","sourceRoot":"","sources":["../../src/auth/require-service-crossing.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,UAAU,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEpE;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,qBAAqB,CAAC;AAExD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,mBAAmB,sBAAsB,CAAC;AAEvD;;;GAGG;AACH,eAAO,MAAM,i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AM,KAAK,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,oLAwB7D,CAAC;AAEP;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,eAAe,GACzB,YAAY,UAAU,MACtB,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,oLAenC,CAAC"}
@@ -1,7 +1,9 @@
1
1
  import { timingSafeEqual } from 'node:crypto';
2
2
  import { ServiceCrossingPolicyTag } from '@entifix/authz';
3
+ import { Forbidden, Invalid, Unauthenticated } from '@entifix/core';
3
4
  import { Context, Effect } from 'effect';
4
- import { HttpServerRequest, HttpServerResponse } from 'effect/http';
5
+ import { HttpServerRequest } from 'effect/http';
6
+ import { refuse } from './failures.js';
5
7
  /**
6
8
  * The header carrying the crossing secret.
7
9
  *
@@ -40,33 +42,28 @@ import { HttpServerRequest, HttpServerResponse } from 'effect/http';
40
42
  */ export class ServiceCrossingTokenTag extends Context.Service()('ServiceCrossingTokenTag') {
41
43
  }
42
44
  /** Constant-time comparison, so the secret cannot be recovered byte by byte. */ const matches = (provided, expected)=>{
43
- if (provided === undefined) return false;
45
+ // An empty credential is refused outright, on either side: two empty
46
+ // buffers compare equal, so an unset secret would admit an empty header.
47
+ if (provided === undefined || provided === '' || expected === '') return false;
44
48
  const left = Buffer.from(provided);
45
49
  const right = Buffer.from(expected);
46
50
  // `timingSafeEqual` throws on a length mismatch, so lengths are compared
47
51
  // first — the length of a shared secret is not what protects it.
48
52
  return left.length === right.length && timingSafeEqual(left, right);
49
53
  };
50
- const unauthenticated = HttpServerResponse.json({
51
- error: 'unauthenticated',
52
- code: 'unauthenticated'
53
- }, {
54
- status: 401
55
- });
56
- const forbidden = (permission)=>HttpServerResponse.json({
57
- error: 'forbidden',
58
- code: 'forbidden',
54
+ const unauthenticated = refuse(new Unauthenticated());
55
+ const forbidden = (permission)=>refuse(new Forbidden({
59
56
  permission
60
- }, {
61
- status: 403
62
- });
63
- const organizationRequired = HttpServerResponse.json({
64
- error: 'the crossing must name an organization',
65
- code: 'invalidRequest',
66
- detail: `${ORGANIZATION_HEADER} is required`
67
- }, {
68
- status: 400
69
- });
57
+ }));
58
+ const organizationRequired = refuse(new Invalid({
59
+ errors: [
60
+ {
61
+ pointer: `/headers/${ORGANIZATION_HEADER}`,
62
+ detail: `${ORGANIZATION_HEADER} is required`,
63
+ code: 'organizationRequired'
64
+ }
65
+ ]
66
+ }));
70
67
  /**
71
68
  * Guard a **service-to-service** tenant crossing: the second — and only other —
72
69
  * way a request resolves the organization it acts for.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/require-service-crossing.ts"],"sourcesContent":["import { timingSafeEqual } from 'node:crypto';\n\nimport { type Permission, ServiceCrossingPolicyTag } from '@entifix/authz';\nimport { Context, Effect } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\n/**\n * The header carrying the crossing secret.\n *\n * ⚠️ **Deliberately not `x-service-token`.** That header is config-service's\n * fleet lookup, and the two secrets are not comparable: one grants a\n * configuration *read*, this one a tenant-data *write* for any organization the\n * caller names. Sharing the header name is how a proxy configured to forward the\n * fleet token ends up presenting it to a route that writes stock, and how a\n * copy-pasted value looks right while being the wrong secret entirely.\n */\nexport const CROSSING_TOKEN_HEADER = 'x-crossing-token';\n\n/**\n * The header naming the organization the caller is acting for.\n *\n * It rides beside the token rather than inside the request body because\n * entities are organization-agnostic by rule — no `organizationId` member, no\n * tenant filter — so there is nowhere in an entity envelope for it to live. A\n * header also serves the crossings that carry no body at all (releasing a hold,\n * converting one), which a body field would have needed a second convention for.\n *\n * On its own it grants **nothing**: it is only read after the token has proved\n * the caller is the fleet, so the input the caller controls is never the input\n * that authorizes.\n */\nexport const ORGANIZATION_HEADER = 'x-organization-id';\n\n/**\n * The header a saga dispatch carries its command id in — what a participant\n * dedupes a redelivered command on, and what its unit of work claims.\n */\nexport const COMMAND_ID_HEADER = 'x-command-id';\n\n/**\n * The crossing secret this service expects, provided at the composition root\n * from its own configuration.\n *\n * A `Context.Tag` rather than an environment read, which is the difference from\n * {@link requireServiceToken}: the value is a per-service secret held in\n * config-service as an `is_secret` row, so it arrives through the same boot\n * fetch as `mongo.uri` and can be rotated without redeploying a container.\n */\nexport class ServiceCrossingTokenTag extends Context.Service<\n ServiceCrossingTokenTag,\n string\n>()('ServiceCrossingTokenTag') {}\n\n/** Constant-time comparison, so the secret cannot be recovered byte by byte. */\nconst matches = (provided: string | undefined, expected: string): boolean => {\n if (provided === undefined) return false;\n const left = Buffer.from(provided);\n const right = Buffer.from(expected);\n // `timingSafeEqual` throws on a length mismatch, so lengths are compared\n // first — the length of a shared secret is not what protects it.\n return left.length === right.length && timingSafeEqual(left, right);\n};\n\nconst unauthenticated = HttpServerResponse.json(\n { error: 'unauthenticated', code: 'unauthenticated' },\n { status: 401 },\n);\n\nconst forbidden = (permission: Permission) =>\n HttpServerResponse.json(\n { error: 'forbidden', code: 'forbidden', permission },\n { status: 403 },\n );\n\nconst organizationRequired = HttpServerResponse.json(\n {\n error: 'the crossing must name an organization',\n code: 'invalidRequest',\n detail: `${ORGANIZATION_HEADER} is required`,\n },\n { status: 400 },\n);\n\n/**\n * Guard a **service-to-service** tenant crossing: the second — and only other —\n * way a request resolves the organization it acts for.\n *\n * The first is {@link requireOrganization}, which reads the session's\n * `activeOrganizationId` and is the only *user-facing* resolution. This one\n * exists because a platform-plane caller sometimes acts for an organization the\n * principal is not a member of: checkout reserving a vendor's stock, where the\n * organization comes from the **item** and a buyer's session carries none — and\n * never will, since making a buyer a member of every vendor they buy from would\n * be a far worse breach than the problem it solved.\n *\n * There is no third path, no fallback and no operator branch. A request\n * satisfying neither guard simply never reaches a tenant handle. An operator\n * reaching into a tenant is a *different* mechanism — a person choosing an\n * organization, which needs a human's permission, a time box and a record of\n * the crossing — and does not belong in this guard.\n *\n * ⚠️ **This guard reads no cookie and no `Authorization` header, and that is\n * the design.** A route guarded here accepts the crossing token and nothing\n * else: two accepted credentials on one route means the weaker one is the\n * security level. It matters concretely — `super-admin` holds `*:*:*`, which\n * matches every crossing permission, so a route that also took a session would\n * be reachable by an operator's browser tab.\n *\n * Three checks, in this order, so nothing is revealed before fleet membership is\n * proven:\n *\n * 1. the token, compared in constant time → `401`;\n * 2. the permission, against `ServiceCrossingPolicyTag` → `403`. The token\n * proves the caller is the fleet; it does not say what the caller may do, and\n * fleet membership is not a capability;\n * 3. the organization header, non-blank → `400`.\n *\n * **The residual, stated rather than argued away**: a shared secret\n * means any process holding it can name any organization. What bounds it is the\n * permission above, the fact that only the slices needing it are configured with\n * the key, and the request log. What would remove it is an RS256 service token\n * carrying a scope claim, which is named work rather than a gap nobody noticed.\n */\nexport const requireServiceCrossing =\n (permission: Permission) =>\n <A, E, R>(use: (organizationId: string) => Effect.Effect<A, E, R>) =>\n // The return type is inferred rather than written out, for the reason\n // `requireServiceToken` records: `HttpServerResponse.json` contributes an\n // `HttpBodyError` to the failure channel, and spelling the type out while\n // omitting it is what makes the declaration emit fail invisibly.\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const expected = yield* ServiceCrossingTokenTag;\n\n if (!matches(request.headers[CROSSING_TOKEN_HEADER], expected)) {\n return yield* unauthenticated;\n }\n\n const crossing = yield* ServiceCrossingPolicyTag;\n if (!crossing.allows(permission)) {\n return yield* forbidden(permission);\n }\n\n const organizationId = request.headers[ORGANIZATION_HEADER]?.trim();\n if (organizationId === undefined || organizationId === '') {\n return yield* organizationRequired;\n }\n\n return yield* use(organizationId);\n });\n\n/**\n * The same fleet check, for a participant that has **no organization to name**.\n *\n * ⚠️ **A platform-plane store is the whole difference.** `requireServiceCrossing`\n * above ends with an organization header because it is about to resolve a tenant\n * database handle from it, and a blank one there would read some other vendor's\n * storage. order-service names one database at boot, so there is no handle to\n * choose — and demanding a header nothing consumes would be theatre that a\n * caller learns to satisfy with any value.\n *\n * What is unchanged, and is the part that matters: the token proves the caller\n * is the fleet, the host's `ServiceCrossingPolicy` says what the fleet may do,\n * and **no session is accepted**. A saga step is not a person's act — the buyer\n * behind a checkout holds no grant over the order the coordinator is writing on\n * their behalf, and accepting their session here would make the weaker\n * credential the security level.\n *\n * The recorded residual carries over verbatim: a shared secret means any process\n * holding it can act, bounded by the permission and by which slices are\n * configured with the key.\n */\nexport const requireCrossing =\n (permission: Permission) =>\n <A, E, R>(route: Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const expected = yield* ServiceCrossingTokenTag;\n\n if (!matches(request.headers[CROSSING_TOKEN_HEADER], expected)) {\n return yield* unauthenticated;\n }\n\n const crossing = yield* ServiceCrossingPolicyTag;\n if (!crossing.allows(permission)) {\n return yield* forbidden(permission);\n }\n\n return yield* route;\n });\n"],"names":["timingSafeEqual","ServiceCrossingPolicyTag","Context","Effect","HttpServerRequest","HttpServerResponse","CROSSING_TOKEN_HEADER","ORGANIZATION_HEADER","COMMAND_ID_HEADER","ServiceCrossingTokenTag","Service","matches","provided","expected","undefined","left","Buffer","from","right","length","unauthenticated","json","error","code","status","forbidden","permission","organizationRequired","detail","requireServiceCrossing","use","gen","request","headers","crossing","allows","organizationId","trim","requireCrossing","route"],"mappings":"AAAA,SAASA,eAAe,QAAQ,cAAc;AAE9C,SAA0BC,wBAAwB,QAAQ,iBAAiB;AAC3E,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AACzC,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEpE;;;;;;;;;CASC,GACD,OAAO,MAAMC,wBAAwB,mBAAmB;AAExD;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,sBAAsB,oBAAoB;AAEvD;;;CAGC,GACD,OAAO,MAAMC,oBAAoB,eAAe;AAEhD;;;;;;;;CAQC,GACD,OAAO,MAAMC,gCAAgCP,QAAQQ,OAAO,GAGxD;AAA4B;AAEhC,8EAA8E,GAC9E,MAAM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gBACzD,OAAO,OAAOT;YAChB;YAEA,OAAO,OAAOG,IAAIM;QACpB,GAAG;AAEP;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,MAAME,kBACX,CAACZ,aACD,CAAUa,QACRpC,OAAO4B,GAAG,CAAC;YACT,MAAMC,UAAU,OAAO5B,kBAAkBA,iBAAiB;YAC1D,MAAMS,WAAW,OAAOJ;YAExB,IAAI,CAACE,QAAQqB,QAAQC,OAAO,CAAC3B,sBAAsB,EAAEO,WAAW;gBAC9D,OAAO,OAAOO;YAChB;YAEA,MAAMc,WAAW,OAAOjC;YACxB,IAAI,CAACiC,SAASC,MAAM,CAACT,aAAa;gBAChC,OAAO,OAAOD,UAAUC;YAC1B;YAEA,OAAO,OAAOa;QAChB,GAAG"}
1
+ {"version":3,"sources":["../../src/auth/require-service-crossing.ts"],"sourcesContent":["import { timingSafeEqual } from 'node:crypto';\n\nimport { type Permission, ServiceCrossingPolicyTag } from '@entifix/authz';\nimport { Forbidden, Invalid, Unauthenticated } from '@entifix/core';\nimport { Context, Effect } from 'effect';\nimport { HttpServerRequest } from 'effect/http';\n\nimport { refuse } from './failures.js';\n\n/**\n * The header carrying the crossing secret.\n *\n * ⚠️ **Deliberately not `x-service-token`.** That header is config-service's\n * fleet lookup, and the two secrets are not comparable: one grants a\n * configuration *read*, this one a tenant-data *write* for any organization the\n * caller names. Sharing the header name is how a proxy configured to forward the\n * fleet token ends up presenting it to a route that writes stock, and how a\n * copy-pasted value looks right while being the wrong secret entirely.\n */\nexport const CROSSING_TOKEN_HEADER = 'x-crossing-token';\n\n/**\n * The header naming the organization the caller is acting for.\n *\n * It rides beside the token rather than inside the request body because\n * entities are organization-agnostic by rule — no `organizationId` member, no\n * tenant filter — so there is nowhere in an entity envelope for it to live. A\n * header also serves the crossings that carry no body at all (releasing a hold,\n * converting one), which a body field would have needed a second convention for.\n *\n * On its own it grants **nothing**: it is only read after the token has proved\n * the caller is the fleet, so the input the caller controls is never the input\n * that authorizes.\n */\nexport const ORGANIZATION_HEADER = 'x-organization-id';\n\n/**\n * The header a saga dispatch carries its command id in — what a participant\n * dedupes a redelivered command on, and what its unit of work claims.\n */\nexport const COMMAND_ID_HEADER = 'x-command-id';\n\n/**\n * The crossing secret this service expects, provided at the composition root\n * from its own configuration.\n *\n * A `Context.Tag` rather than an environment read, which is the difference from\n * {@link requireServiceToken}: the value is a per-service secret held in\n * config-service as an `is_secret` row, so it arrives through the same boot\n * fetch as `mongo.uri` and can be rotated without redeploying a container.\n */\nexport class ServiceCrossingTokenTag extends Context.Service<\n ServiceCrossingTokenTag,\n string\n>()('ServiceCrossingTokenTag') {}\n\n/** Constant-time comparison, so the secret cannot be recovered byte by byte. */\nconst matches = (provided: string | undefined, expected: string): boolean => {\n // An empty credential is refused outright, on either side: two empty\n // buffers compare equal, so an unset secret would admit an empty header.\n if (provided === undefined || provided === '' || expected === '')\n return false;\n const left = Buffer.from(provided);\n const right = Buffer.from(expected);\n // `timingSafeEqual` throws on a length mismatch, so lengths are compared\n // first — the length of a shared secret is not what protects it.\n return left.length === right.length && timingSafeEqual(left, right);\n};\n\nconst unauthenticated = refuse(new Unauthenticated());\n\nconst forbidden = (permission: Permission) =>\n refuse(new Forbidden({ permission }));\n\nconst organizationRequired = refuse(\n new Invalid({\n errors: [\n {\n pointer: `/headers/${ORGANIZATION_HEADER}`,\n detail: `${ORGANIZATION_HEADER} is required`,\n code: 'organizationRequired',\n },\n ],\n }),\n);\n\n/**\n * Guard a **service-to-service** tenant crossing: the second — and only other —\n * way a request resolves the organization it acts for.\n *\n * The first is {@link requireOrganization}, which reads the session's\n * `activeOrganizationId` and is the only *user-facing* resolution. This one\n * exists because a platform-plane caller sometimes acts for an organization the\n * principal is not a member of: checkout reserving a vendor's stock, where the\n * organization comes from the **item** and a buyer's session carries none — and\n * never will, since making a buyer a member of every vendor they buy from would\n * be a far worse breach than the problem it solved.\n *\n * There is no third path, no fallback and no operator branch. A request\n * satisfying neither guard simply never reaches a tenant handle. An operator\n * reaching into a tenant is a *different* mechanism — a person choosing an\n * organization, which needs a human's permission, a time box and a record of\n * the crossing — and does not belong in this guard.\n *\n * ⚠️ **This guard reads no cookie and no `Authorization` header, and that is\n * the design.** A route guarded here accepts the crossing token and nothing\n * else: two accepted credentials on one route means the weaker one is the\n * security level. It matters concretely — `super-admin` holds `*:*:*`, which\n * matches every crossing permission, so a route that also took a session would\n * be reachable by an operator's browser tab.\n *\n * Three checks, in this order, so nothing is revealed before fleet membership is\n * proven:\n *\n * 1. the token, compared in constant time → `401`;\n * 2. the permission, against `ServiceCrossingPolicyTag` → `403`. The token\n * proves the caller is the fleet; it does not say what the caller may do, and\n * fleet membership is not a capability;\n * 3. the organization header, non-blank → `400`.\n *\n * **The residual, stated rather than argued away**: a shared secret\n * means any process holding it can name any organization. What bounds it is the\n * permission above, the fact that only the slices needing it are configured with\n * the key, and the request log. What would remove it is an RS256 service token\n * carrying a scope claim, which is named work rather than a gap nobody noticed.\n */\nexport const requireServiceCrossing =\n (permission: Permission) =>\n <A, E, R>(use: (organizationId: string) => Effect.Effect<A, E, R>) =>\n // The return type is inferred rather than written out, for the reason\n // `requireServiceToken` records: `HttpServerResponse.json` contributes an\n // `HttpBodyError` to the failure channel, and spelling the type out while\n // omitting it is what makes the declaration emit fail invisibly.\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const expected = yield* ServiceCrossingTokenTag;\n\n if (!matches(request.headers[CROSSING_TOKEN_HEADER], expected)) {\n return yield* unauthenticated;\n }\n\n const crossing = yield* ServiceCrossingPolicyTag;\n if (!crossing.allows(permission)) {\n return yield* forbidden(permission);\n }\n\n const organizationId = request.headers[ORGANIZATION_HEADER]?.trim();\n if (organizationId === undefined || organizationId === '') {\n return yield* organizationRequired;\n }\n\n return yield* use(organizationId);\n });\n\n/**\n * The same fleet check, for a participant that has **no organization to name**.\n *\n * ⚠️ **A platform-plane store is the whole difference.** `requireServiceCrossing`\n * above ends with an organization header because it is about to resolve a tenant\n * database handle from it, and a blank one there would read some other vendor's\n * storage. order-service names one database at boot, so there is no handle to\n * choose — and demanding a header nothing consumes would be theatre that a\n * caller learns to satisfy with any value.\n *\n * What is unchanged, and is the part that matters: the token proves the caller\n * is the fleet, the host's `ServiceCrossingPolicy` says what the fleet may do,\n * and **no session is accepted**. A saga step is not a person's act — the buyer\n * behind a checkout holds no grant over the order the coordinator is writing on\n * their behalf, and accepting their session here would make the weaker\n * credential the security level.\n *\n * The recorded residual carries over verbatim: a shared secret means any process\n * holding it can act, bounded by the permission and by which slices are\n * configured with the key.\n */\nexport const requireCrossing =\n (permission: Permission) =>\n <A, E, R>(route: Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const expected = yield* ServiceCrossingTokenTag;\n\n if (!matches(request.headers[CROSSING_TOKEN_HEADER], expected)) {\n return yield* unauthenticated;\n }\n\n const crossing = yield* ServiceCrossingPolicyTag;\n if (!crossing.allows(permission)) {\n return yield* forbidden(permission);\n }\n\n return yield* route;\n });\n"],"names":["timingSafeEqual","ServiceCrossingPolicyTag","Forbidden","Invalid","Unauthenticated","Context","Effect","HttpServerRequest","refuse","CROSSING_TOKEN_HEADER","ORGANIZATION_HEADER","COMMAND_ID_HEADER","ServiceCrossingTokenTag","Service","matches","provided","expected","undefined","left","Buffer","from","right","length","unauthenticated","forbidden","permission","organizationRequired","errors","pointer","detail","code","requireServiceCrossing","use","gen","request","headers","crossing","allows","organizationId","trim","requireCrossing","route"],"mappings":"AAAA,SAASA,eAAe,QAAQ,cAAc;AAE9C,SAA0BC,wBAAwB,QAAQ,iBAAiB;AAC3E,SAASC,SAAS,EAAEC,OAAO,EAAEC,eAAe,QAAQ,gBAAgB;AACpE,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AACzC,SAASC,iBAAiB,QAAQ,cAAc;AAEhD,SAASC,MAAM,QAAQ,gBAAgB;AAEvC;;;;;;;;;CASC,GACD,OAAO,MAAMC,wBAAwB,mBA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M,CAACZ,aAAa;gBAChC,OAAO,OAAOD,UAAUC;YAC1B;YAEA,MAAMa,kBAAiBJ,uCAAAA,QAAQC,OAAO,CAACzB,oBAAoB,qBAApCwB,qCAAsCK,IAAI;YACjE,IAAID,mBAAmBrB,aAAaqB,mBAAmB,IAAI;gBACzD,OAAO,OAAOZ;YAChB;YAEA,OAAO,OAAOM,IAAIM;QACpB,GAAG;AAEP;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,MAAME,kBACX,CAACf,aACD,CAAUgB,QACRnC,OAAO2B,GAAG,CAAC;YACT,MAAMC,UAAU,OAAO3B,kBAAkBA,iBAAiB;YAC1D,MAAMS,WAAW,OAAOJ;YAExB,IAAI,CAACE,QAAQoB,QAAQC,OAAO,CAAC1B,sBAAsB,EAAEO,WAAW;gBAC9D,OAAO,OAAOO;YAChB;YAEA,MAAMa,WAAW,OAAOnC;YACxB,IAAI,CAACmC,SAASC,MAAM,CAACZ,aAAa;gBAChC,OAAO,OAAOD,UAAUC;YAC1B;YAEA,OAAO,OAAOgB;QAChB,GAAG"}
@@ -1,5 +1,5 @@
1
1
  import { Effect } from 'effect';
2
- import { HttpServerRequest, HttpServerResponse } from 'effect/http';
2
+ import { HttpServerRequest } from 'effect/http';
3
3
  /**
4
4
  * A secret every caller of a route presents in one header.
5
5
  *
@@ -30,5 +30,5 @@ export interface SharedToken {
30
30
  * Health endpoints should stay unguarded: a probe cannot hold a credential, and
31
31
  * a readiness check that needs one becomes an authentication problem.
32
32
  */
33
- export declare const requireSharedToken: (shared: SharedToken) => <A, E, R>(route: Effect.Effect<A, E, R>) => Effect.Effect<HttpServerResponse.HttpServerResponse | A, import("effect/http/HttpBody").HttpBodyError | E, HttpServerRequest.HttpServerRequest | R>;
33
+ export declare const requireSharedToken: (shared: SharedToken) => <A, E, R>(route: Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, HttpServerRequest.HttpServerRequest | R>;
34
34
  //# sourceMappingURL=shared-token.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-token.d.ts","sourceRoot":"","sources":["../../src/auth/shared-token.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEpE;;;;;;;GAOG;AACH,MAAM,WAAW,WAAW;IAC1B,uEAAuE;IACvE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,MAAM,CAAC;CAC9B;AAYD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,kBAAkB,GAC5B,QAAQ,WAAW,MACnB,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,wJAenC,CAAC"}
1
+ {"version":3,"file":"shared-token.d.ts","sourceRoot":"","sources":["../../src/auth/shared-token.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAIhD;;;;;;;GAOG;AACH,MAAM,WAAW,WAAW;IAC1B,uEAAuE;IACvE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,MAAM,CAAC;CAC9B;AAeD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,kBAAkB,GAC5B,QAAQ,WAAW,MACnB,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,+HAYnC,CAAC"}
@@ -1,8 +1,12 @@
1
1
  import { timingSafeEqual } from 'node:crypto';
2
+ import { Unauthenticated } from '@entifix/core';
2
3
  import { Effect } from 'effect';
3
- import { HttpServerRequest, HttpServerResponse } from 'effect/http';
4
+ import { HttpServerRequest } from 'effect/http';
5
+ import { refuse } from './failures.js';
4
6
  /** Constant-time comparison, so the token cannot be recovered byte by byte. */ const matches = (provided, expected)=>{
5
- if (provided === undefined) return false;
7
+ // An empty credential is refused outright, on either side: two empty
8
+ // buffers compare equal, so an unset secret would admit an empty header.
9
+ if (provided === undefined || provided === '' || expected === '') return false;
6
10
  const left = Buffer.from(provided);
7
11
  const right = Buffer.from(expected);
8
12
  // `timingSafeEqual` throws on a length mismatch, so the lengths are compared
@@ -26,12 +30,7 @@ import { HttpServerRequest, HttpServerResponse } from 'effect/http';
26
30
  Effect.gen(function*() {
27
31
  const request = yield* HttpServerRequest.HttpServerRequest;
28
32
  if (!matches(request.headers[shared.header], shared.token())) {
29
- return yield* HttpServerResponse.json({
30
- error: 'unauthenticated',
31
- code: 'unauthenticated'
32
- }, {
33
- status: 401
34
- });
33
+ return yield* refuse(new Unauthenticated());
35
34
  }
36
35
  return yield* route;
37
36
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/shared-token.ts"],"sourcesContent":["import { timingSafeEqual } from 'node:crypto';\n\nimport { Effect } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\n/**\n * A secret every caller of a route presents in one header.\n *\n * Both halves are the host's. Which header carries it and where the expected\n * value comes from are a deployment's conventions — a fleet-wide environment\n * variable, a mounted secret, a fixed value in a test — so the framework takes\n * them as values rather than naming either.\n */\nexport interface SharedToken {\n /** The request header the token travels in, e.g. `x-service-token`. */\n readonly header: string;\n /**\n * The expected token, asked for on each request rather than captured once —\n * so a rotated secret, or a test that sets one, takes effect without a\n * restart.\n */\n readonly token: () => string;\n}\n\n/** Constant-time comparison, so the token cannot be recovered byte by byte. */\nconst matches = (provided: string | undefined, expected: string): boolean => {\n if (provided === undefined) return false;\n const left = Buffer.from(provided);\n const right = Buffer.from(expected);\n // `timingSafeEqual` throws on a length mismatch, so the lengths are compared\n // first — the length of a shared secret is not what protects it.\n return left.length === right.length && timingSafeEqual(left, right);\n};\n\n/**\n * Serves `route` only to a caller presenting the shared token.\n *\n * ⚠️ This is **not** identity: every caller presents the same value, so it\n * proves membership of whatever group holds the secret and nothing more. It is\n * the right shape for a route whose readers are machines — a fleet fetching its\n * configuration at boot, tooling reading a service's wiring — and the wrong one\n * for anything a person or a browser reaches.\n *\n * Health endpoints should stay unguarded: a probe cannot hold a credential, and\n * a readiness check that needs one becomes an authentication problem.\n */\nexport const requireSharedToken =\n (shared: SharedToken) =>\n <A, E, R>(route: Effect.Effect<A, E, R>) =>\n // The return type is inferred rather than written out: `HttpServerResponse.json`\n // contributes an `HttpBodyError` to the failure channel, and spelling the type\n // out while omitting it is what makes `tsc` refuse the declaration emit.\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n\n if (!matches(request.headers[shared.header], shared.token())) {\n return yield* HttpServerResponse.json(\n { error: 'unauthenticated', code: 'unauthenticated' },\n { status: 401 },\n );\n }\n\n return yield* route;\n });\n"],"names":["timingSafeEqual","Effect","HttpServerRequest","HttpServerResponse","matches","provided","expected","undefined","left","Buffer","from","right","length","requireSharedToken","shared","route","gen","request","headers","header","token","json","error","code","status"],"mappings":"AAAA,SAASA,eAAe,QAAQ,cAAc;AAE9C,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAqBpE,6EAA6E,GAC7E,MAAMC,UAAU,CAACC,UAA8BC;IAC7C,IAAID,aAAaE,WAAW,OAAO;IACnC,MAAMC,OAAOC,OAAOC,IAAI,CAACL;IACzB,MAAMM,QAAQF,OAAOC,IAAI,CAACJ;IAC1B,6EAA6E;IAC7E,iEAAiE;IACjE,OAAOE,KAAKI,MAAM,KAAKD,MAAMC,MAAM,IAAIZ,gBAAgBQ,MAAMG;AAC/D;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,MAAME,qBACX,CAACC,SACD,CAAUC,QACR,iFAAiF;QACjF,+EAA+E;QAC/E,yEAAyE;QACzEd,OAAOe,GAAG,CAAC;YACT,MAAMC,UAAU,OAAOf,kBAAkBA,iBAAiB;YAE1D,IAAI,CAACE,QAAQa,QAAQC,OAAO,CAACJ,OAAOK,MAAM,CAAC,EAAEL,OAAOM,KAAK,KAAK;gBAC5D,OAAO,OAAOjB,mBAAmBkB,IAAI,CACnC;oBAAEC,OAAO;oBAAmBC,MAAM;gBAAkB,GACpD;oBAAEC,QAAQ;gBAAI;YAElB;YAEA,OAAO,OAAOT;QAChB,GAAG"}
1
+ {"version":3,"sources":["../../src/auth/shared-token.ts"],"sourcesContent":["import { timingSafeEqual } from 'node:crypto';\n\nimport { Unauthenticated } from '@entifix/core';\nimport { Effect } from 'effect';\nimport { HttpServerRequest } from 'effect/http';\n\nimport { refuse } from './failures.js';\n\n/**\n * A secret every caller of a route presents in one header.\n *\n * Both halves are the host's. Which header carries it and where the expected\n * value comes from are a deployment's conventions — a fleet-wide environment\n * variable, a mounted secret, a fixed value in a test — so the framework takes\n * them as values rather than naming either.\n */\nexport interface SharedToken {\n /** The request header the token travels in, e.g. `x-service-token`. */\n readonly header: string;\n /**\n * The expected token, asked for on each request rather than captured once —\n * so a rotated secret, or a test that sets one, takes effect without a\n * restart.\n */\n readonly token: () => string;\n}\n\n/** Constant-time comparison, so the token cannot be recovered byte by byte. */\nconst matches = (provided: string | undefined, expected: string): boolean => {\n // An empty credential is refused outright, on either side: two empty\n // buffers compare equal, so an unset secret would admit an empty header.\n if (provided === undefined || provided === '' || expected === '')\n return false;\n const left = Buffer.from(provided);\n const right = Buffer.from(expected);\n // `timingSafeEqual` throws on a length mismatch, so the lengths are compared\n // first — the length of a shared secret is not what protects it.\n return left.length === right.length && timingSafeEqual(left, right);\n};\n\n/**\n * Serves `route` only to a caller presenting the shared token.\n *\n * ⚠️ This is **not** identity: every caller presents the same value, so it\n * proves membership of whatever group holds the secret and nothing more. It is\n * the right shape for a route whose readers are machines — a fleet fetching its\n * configuration at boot, tooling reading a service's wiring — and the wrong one\n * for anything a person or a browser reaches.\n *\n * Health endpoints should stay unguarded: a probe cannot hold a credential, and\n * a readiness check that needs one becomes an authentication problem.\n */\nexport const requireSharedToken =\n (shared: SharedToken) =>\n <A, E, R>(route: Effect.Effect<A, E, R>) =>\n // The return type is inferred rather than written out: `HttpServerResponse.json`\n // contributes an `HttpBodyError` to the failure channel, and spelling the type\n // out while omitting it is what makes `tsc` refuse the declaration emit.\n Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n\n if (!matches(request.headers[shared.header], shared.token())) {\n return yield* refuse(new Unauthenticated());\n }\n\n return yield* route;\n });\n"],"names":["timingSafeEqual","Unauthenticated","Effect","HttpServerRequest","refuse","matches","provided","expected","undefined","left","Buffer","from","right","length","requireSharedToken","shared","route","gen","request","headers","header","token"],"mappings":"AAAA,SAASA,eAAe,QAAQ,cAAc;AAE9C,SAASC,eAAe,QAAQ,gBAAgB;AAChD,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,iBAAiB,QAAQ,cAAc;AAEhD,SAASC,MAAM,QAAQ,gBAAgB;AAqBvC,6EAA6E,GAC7E,MAAMC,UAAU,CAACC,UAA8BC;IAC7C,qEAAqE;IACrE,yEAAyE;IACzE,IAAID,aAAaE,aAAaF,aAAa,MAAMC,aAAa,IAC5D,OAAO;IACT,MAAME,OAAOC,OAAOC,IAAI,CAACL;IACzB,MAAMM,QAAQF,OAAOC,IAAI,CAACJ;IAC1B,6EAA6E;IAC7E,iEAAiE;IACjE,OAAOE,KAAKI,MAAM,KAAKD,MAAMC,MAAM,IAAIb,gBAAgBS,MAAMG;AAC/D;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,MAAME,qBACX,CAACC,SACD,CAAUC,QACR,iFAAiF;QACjF,+EAA+E;QAC/E,yEAAyE;QACzEd,OAAOe,GAAG,CAAC;YACT,MAAMC,UAAU,OAAOf,kBAAkBA,iBAAiB;YAE1D,IAAI,CAACE,QAAQa,QAAQC,OAAO,CAACJ,OAAOK,MAAM,CAAC,EAAEL,OAAOM,KAAK,KAAK;gBAC5D,OAAO,OAAOjB,OAAO,IAAIH;YAC3B;YAEA,OAAO,OAAOe;QAChB,GAAG"}
@@ -0,0 +1,38 @@
1
+ import { EntityFacetCounterFactoryTag } from '@entifix/business';
2
+ import { type Entity, type EntityConstructor } from '@entifix/core';
3
+ import { Effect } from 'effect';
4
+ import { HttpRouter } from 'effect/http';
5
+ import { type EntityReadScope, type EntityRouteContext, type EntityRouteGuard } from './entity-route-guard.js';
6
+ import { type FailurePolicy } from './respond.js';
7
+ export interface EntityFacetRoutesOptions<T extends Entity, R, G extends EntityRouteGuard = EntityRouteGuard> {
8
+ /** Who may count: the guard the entity's `list` has, as a rule. */
9
+ readonly guard: G;
10
+ /** Defaults to `/api/<entity key>`; the route is `<basePath>/$facets`. */
11
+ readonly basePath?: `/${string}`;
12
+ /**
13
+ * Narrows the counts to the records this caller may see — the same scope
14
+ * the entity's `list` takes, so a count never reveals a record the list
15
+ * would not.
16
+ */
17
+ readonly scope?: (context: EntityRouteContext) => Effect.Effect<EntityReadScope<T>, never, R>;
18
+ /** How the count's failures are answered and logged. */
19
+ readonly policy?: FailurePolicy;
20
+ }
21
+ /**
22
+ * `GET <base>/$facets` — how many of the entity's records hold each value of
23
+ * each `facet` member, each under its own `rsql.<member>` filtering — bound to
24
+ * storage through the host's {@link EntityFacetCounterFactoryTag}.
25
+ *
26
+ * A route of its own beside `makeEntityRoutes` rather than a sixth verb, so it
27
+ * is the one route set that requires a counter: a host that mounts it without
28
+ * binding one fails to compile, and a host that never counts binds nothing.
29
+ *
30
+ * The query is parsed against the entity's metadata, so only a `filterable`
31
+ * member is counted and every malformed request is a `400`. A scope is
32
+ * **conjoined into every facet's filtering**, never substituted, so no query
33
+ * string can count past it; `'none'` answers every member empty.
34
+ */
35
+ export declare const makeEntityFacetRoutes: <T extends Entity, R = never, const G extends EntityRouteGuard = never>(entityConstructor: EntityConstructor<T>, options: EntityFacetRoutesOptions<T, R, G>) => import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request<"Requires", EntityFacetCounterFactoryTag> | HttpRouter.Request<"Requires", import("@entifix/business").TokenServiceTag> | HttpRouter.Request<"Requires", import("@entifix/authz").PolicyDecisionTag> | HttpRouter.Request.From<"Requires", Exclude<Exclude<R, HttpRouter.Provided>, HttpRouter.Provided>> | HttpRouter.Request.From<"Requires", Exclude<Exclude<G extends {
36
+ readonly kind: "crossing";
37
+ } ? import("@entifix/authz").ServiceCrossingPolicyTag | import("./index.js").ServiceCrossingTokenTag : never, HttpRouter.Provided>, HttpRouter.Provided>>>;
38
+ //# sourceMappingURL=entity-facet-routes.d.ts.map
@@ -0,0 +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,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EAGtB,MAAM,yBAAyB,CAAC;AACjC,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,OAA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