@entifix/service-shell 0.13.0 → 0.14.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 (73) hide show
  1. package/README.md +7 -7
  2. package/dist/auth/failures.d.ts +0 -12
  3. package/dist/auth/failures.d.ts.map +1 -1
  4. package/dist/auth/failures.js +0 -10
  5. package/dist/auth/failures.js.map +1 -1
  6. package/dist/auth/index.d.ts +0 -1
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js +0 -1
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/auth/require-principal.d.ts +0 -16
  11. package/dist/auth/require-principal.d.ts.map +1 -1
  12. package/dist/auth/require-principal.js +1 -38
  13. package/dist/auth/require-principal.js.map +1 -1
  14. package/dist/auth/require-service-crossing.d.ts +2 -73
  15. package/dist/auth/require-service-crossing.d.ts.map +1 -1
  16. package/dist/auth/require-service-crossing.js +2 -117
  17. package/dist/auth/require-service-crossing.js.map +1 -1
  18. package/dist/auth/shared-token.d.ts +0 -15
  19. package/dist/auth/shared-token.d.ts.map +1 -1
  20. package/dist/auth/shared-token.js +0 -25
  21. package/dist/auth/shared-token.js.map +1 -1
  22. package/dist/index.d.ts +0 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +0 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/load-remote-configuration.d.ts +4 -4
  27. package/dist/load-remote-configuration.d.ts.map +1 -1
  28. package/dist/load-remote-configuration.js +7 -14
  29. package/dist/load-remote-configuration.js.map +1 -1
  30. package/dist/observability.d.ts +2 -2
  31. package/dist/observability.d.ts.map +1 -1
  32. package/dist/observability.js.map +1 -1
  33. package/dist/push/index.d.ts +9 -0
  34. package/dist/push/index.d.ts.map +1 -0
  35. package/dist/push/index.js +9 -0
  36. package/dist/push/index.js.map +1 -0
  37. package/dist/push/server-push.d.ts +82 -0
  38. package/dist/push/server-push.d.ts.map +1 -0
  39. package/dist/push/server-push.js +48 -0
  40. package/dist/push/server-push.js.map +1 -0
  41. package/dist/push/sse.d.ts +62 -0
  42. package/dist/push/sse.d.ts.map +1 -0
  43. package/dist/push/sse.js +120 -0
  44. package/dist/push/sse.js.map +1 -0
  45. package/dist/respond.d.ts +1 -7
  46. package/dist/respond.d.ts.map +1 -1
  47. package/dist/respond.js +1 -8
  48. package/dist/respond.js.map +1 -1
  49. package/package.json +23 -13
  50. package/dist/auth/require-organization.d.ts +0 -32
  51. package/dist/auth/require-organization.d.ts.map +0 -1
  52. package/dist/auth/require-organization.js +0 -52
  53. package/dist/auth/require-organization.js.map +0 -1
  54. package/dist/entity-facet-routes.d.ts +0 -44
  55. package/dist/entity-facet-routes.d.ts.map +0 -1
  56. package/dist/entity-facet-routes.js +0 -70
  57. package/dist/entity-facet-routes.js.map +0 -1
  58. package/dist/entity-metadata-route.d.ts +0 -25
  59. package/dist/entity-metadata-route.d.ts.map +0 -1
  60. package/dist/entity-metadata-route.js +0 -102
  61. package/dist/entity-metadata-route.js.map +0 -1
  62. package/dist/entity-route-guard.d.ts +0 -62
  63. package/dist/entity-route-guard.d.ts.map +0 -1
  64. package/dist/entity-route-guard.js +0 -35
  65. package/dist/entity-route-guard.js.map +0 -1
  66. package/dist/entity-routes.d.ts +0 -76
  67. package/dist/entity-routes.d.ts.map +0 -1
  68. package/dist/entity-routes.js +0 -267
  69. package/dist/entity-routes.js.map +0 -1
  70. package/dist/route-responses.d.ts +0 -44
  71. package/dist/route-responses.d.ts.map +0 -1
  72. package/dist/route-responses.js +0 -104
  73. package/dist/route-responses.js.map +0 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The skeleton of an Effect HTTP service. `makeService` takes a router and the Layer that satisfies it — a missing dependency is a compile error — and adds the server, logging, OpenTelemetry, `/api/health`, the served entity metadata and graceful shutdown.
4
4
 
5
- Routes are guarded with `requirePermission(...)`, which asks the `PolicyDecision` port from `@entifix/authz`. Hiding a navigation item protects nothing; the route guard does.
5
+ An endpoint is guarded by its descriptor's `guard` — the session, organization, crossing or fleet guard — which asks the `PolicyDecision` port from `@entifix/authz`. Hiding a navigation item protects nothing; the route guard does.
6
6
 
7
7
  ## Install
8
8
 
@@ -16,12 +16,12 @@ 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`, `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`, `makeWorker` (a process with no HTTP server — a second runner), `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 an API is written against: `entityApi` (the entity routes, `$facets` over the host's `EntityFacetCounterFactoryTag`, and `$metadata`), `buildApi`, the endpoint guards (`SessionGuard`, `OrganizationGuard`, `CrossingGuard`, `FleetGuard`, `IdempotencyGuard`), `respond` and the SSE response |
22
+ | `@entifix/service-shell/runtime` | Running a service: `makeService`, `makeServerLayer`, `makeWorker` (a process with no HTTP server — a second runner), `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
 
@@ -1,6 +1,3 @@
1
- import { Effect } from 'effect';
2
- import type { HttpServerResponse } from 'effect/http';
3
- import { problemResponse } from '../respond.js';
4
1
  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
2
  /**
6
3
  * A signed-in caller whose session names no organization, on a route that acts
@@ -10,14 +7,5 @@ declare const NoActiveOrganization_base: import("effect/Schema").Class<NoActiveO
10
7
  */
11
8
  export declare class NoActiveOrganization extends NoActiveOrganization_base {
12
9
  }
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
10
  export {};
23
11
  //# sourceMappingURL=failures.d.ts.map
@@ -1 +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"}
1
+ {"version":3,"file":"failures.d.ts","sourceRoot":"","sources":["../../src/auth/failures.ts"],"names":[],"mappings":";AAEA;;;;;GAKG;AACH,qBAAa,oBAAqB,SAAQ,yBAGzC;CAAG"}
@@ -1,6 +1,4 @@
1
1
  import { Failure } from '@entifix/core';
2
- import { Effect } from 'effect';
3
- import { problemResponse } from '../respond.js';
4
2
  /**
5
3
  * A signed-in caller whose session names no organization, on a route that acts
6
4
  * for one. A member of several organizations hits it before choosing one; the
@@ -8,13 +6,5 @@ import { problemResponse } from '../respond.js';
8
6
  * "forbidden".
9
7
  */ export class NoActiveOrganization extends Failure.conflict()('NoActiveOrganization', 'noActiveOrganization') {
10
8
  }
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
9
 
20
10
  //# sourceMappingURL=failures.js.map
@@ -1 +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
+ {"version":3,"sources":["../../src/auth/failures.ts"],"sourcesContent":["import { Failure } from '@entifix/core';\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"],"names":["Failure","NoActiveOrganization","conflict"],"mappings":"AAAA,SAASA,OAAO,QAAQ,gBAAgB;AAExC;;;;;CAKC,GACD,OAAO,MAAMC,6BAA6BD,QAAQE,QAAQ,GACxD,wBACA;AACC"}
@@ -1,5 +1,4 @@
1
1
  export * from './failures.js';
2
- export * from './require-organization.js';
3
2
  export * from './require-principal.js';
4
3
  export * from './require-service-crossing.js';
5
4
  export * from './shared-token.js';
@@ -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;AAClC,cAAc,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,cAAc,wBAAwB,CAAC;AACvC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC"}
@@ -1,5 +1,4 @@
1
1
  export * from './failures.js';
2
- export * from './require-organization.js';
3
2
  export * from './require-principal.js';
4
3
  export * from './require-service-crossing.js';
5
4
  export * from './shared-token.js';
@@ -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';\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"}
1
+ {"version":3,"sources":["../../src/auth/index.ts"],"sourcesContent":["export * from './failures.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,yBAAyB;AACvC,cAAc,gCAAgC;AAC9C,cAAc,oBAAoB;AAClC,cAAc,wBAAwB"}
@@ -11,20 +11,4 @@ import { HttpServerRequest } from 'effect/http';
11
11
  export declare const resolveRequestPrincipal: Effect.Effect<Option.Option<RequestPrincipal>, never, TokenServiceTag | HttpServerRequest.HttpServerRequest>;
12
12
  /** Whether the policy lets `principal` do what `permission` names. */
13
13
  export declare const permits: (principal: RequestPrincipal, permission: Permission) => Effect.Effect<boolean, never, PolicyDecisionTag>;
14
- /**
15
- * Guard a handler behind a valid access token — authentication only. Any
16
- * missing or invalid token is a `401`; the wrapped handler's own errors are
17
- * left intact.
18
- */
19
- 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>;
20
- /**
21
- * Guard a handler behind a permission. Authenticates as above, then asks
22
- * {@link PolicyDecisionTag} whether this subject may perform the action — so
23
- * the two failure modes stay distinguishable: `401` means "sign in", `403`
24
- * means "signed in, not allowed".
25
- *
26
- * **This is the authorization boundary.** Filtering a nav menu or hiding a page
27
- * is presentation; a route that skips this guard is open regardless.
28
- */
29
- 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>;
30
14
  //# 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,EACL,KAAK,gBAAgB,EAErB,eAAe,EAChB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AA6ChD;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,8GAWlC,CAAC;AAEH,sEAAsE;AACtE,eAAO,MAAM,OAAO,GAAI,WAAW,gBAAgB,EAAE,YAAY,UAAU,qDASvE,CAAC;AAEL;;;;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,qKAYlE,CAAC"}
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,EACL,KAAK,gBAAgB,EAErB,eAAe,EAChB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAmChD;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,8GAWlC,CAAC;AAEH,sEAAsE;AACtE,eAAO,MAAM,OAAO,GAAI,WAAW,gBAAgB,EAAE,YAAY,UAAU,qDASvE,CAAC"}
@@ -1,9 +1,8 @@
1
1
  import { parsePermission, PolicyDecisionTag } from '@entifix/authz';
2
2
  import { TokenServiceTag } from '@entifix/business';
3
- import { ACCESS_COOKIE, Forbidden, Unauthenticated } from '@entifix/core';
3
+ import { ACCESS_COOKIE } from '@entifix/core';
4
4
  import { Effect, Option } from 'effect';
5
5
  import { HttpServerRequest } from 'effect/http';
6
- import { refuse } from './failures.js';
7
6
  /** Extract a bearer token from an `Authorization` header, if present. */ const bearerToken = (authorization)=>{
8
7
  if (authorization === undefined) {
9
8
  return undefined;
@@ -36,13 +35,6 @@ import { refuse } from './failures.js';
36
35
  attributes: {}
37
36
  };
38
37
  };
39
- // `code` is a key in the shared `errors` catalog; `error` stays English for
40
- // logs. `permission` is deliberately still in the 403 — it says which grant was
41
- // missing, which is diagnostic, not a leak.
42
- const unauthenticated = refuse(new Unauthenticated());
43
- const forbidden = (permission)=>refuse(new Forbidden({
44
- permission
45
- }));
46
38
  /**
47
39
  * Resolve the caller's principal from the request, or `None`. Reads the token
48
40
  * from the `entifix_at` cookie (the Next app forwards it) or an
@@ -70,34 +62,5 @@ const forbidden = (permission)=>refuse(new Forbidden({
70
62
  action
71
63
  });
72
64
  });
73
- /**
74
- * Guard a handler behind a valid access token — authentication only. Any
75
- * missing or invalid token is a `401`; the wrapped handler's own errors are
76
- * left intact.
77
- */ export const requirePrincipal = (use)=>Effect.gen(function*() {
78
- const principal = yield* resolveRequestPrincipal;
79
- if (Option.isNone(principal)) {
80
- return yield* unauthenticated;
81
- }
82
- return yield* use(principal.value);
83
- });
84
- /**
85
- * Guard a handler behind a permission. Authenticates as above, then asks
86
- * {@link PolicyDecisionTag} whether this subject may perform the action — so
87
- * the two failure modes stay distinguishable: `401` means "sign in", `403`
88
- * means "signed in, not allowed".
89
- *
90
- * **This is the authorization boundary.** Filtering a nav menu or hiding a page
91
- * is presentation; a route that skips this guard is open regardless.
92
- */ export const requirePermission = (permission)=>(use)=>Effect.gen(function*() {
93
- const principal = yield* resolveRequestPrincipal;
94
- if (Option.isNone(principal)) {
95
- return yield* unauthenticated;
96
- }
97
- if (!(yield* permits(principal.value, permission))) {
98
- return yield* forbidden(permission);
99
- }
100
- return yield* use(principal.value);
101
- });
102
65
 
103
66
  //# sourceMappingURL=require-principal.js.map
@@ -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 {\n type RequestPrincipal,\n type TokenClaims,\n TokenServiceTag,\n} 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/** 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 */\nexport const resolveRequestPrincipal = 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/** Whether the policy lets `principal` do what `permission` names. */\nexport const permits = (principal: RequestPrincipal, permission: Permission) =>\n Effect.gen(function* () {\n const { resource, action } = parsePermission(permission);\n const policy = yield* PolicyDecisionTag;\n return policy.decide({\n subject: { roles: principal.roles },\n resource,\n action,\n });\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* resolveRequestPrincipal;\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* resolveRequestPrincipal;\n if (Option.isNone(principal)) {\n return yield* unauthenticated;\n }\n\n if (!(yield* permits(principal.value, permission))) {\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","resolveRequestPrincipal","gen","req","token","cookies","headers","none","tokens","verify","pipe","option","map","permits","principal","resource","action","policy","decide","requirePrincipal","use","isNone","requirePermission"],"mappings":"AAAA,SACEA,eAAe,EAEfC,iBAAiB,QACZ,iBAAiB;AACxB,SAGEC,eAAe,QACV,oBAAoB;AAC3B,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;AAEvC,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;QAiBXA;WAjBsD;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;QACzDiB,YAAY,GAAEX,uBAAAA,OAAOW,YAAY,YAAnBX,uBAAuB,EAAE;QACvC,2EAA2E;QAC3E,0CAA0C;QAC1CY,YAAY,CAAC;IACf;;AAEA,4EAA4E;AAC5E,gFAAgF;AAChF,4CAA4C;AAC5C,MAAMC,kBAAkBtB,OAAO,IAAIJ;AAEnC,MAAM2B,YAAY,CAACC,aACjBxB,OAAO,IAAIL,UAAU;QAAE6B;IAAW;AAEpC;;;;;CAKC,GACD,OAAO,MAAMC,0BAA0B5B,OAAO6B,GAAG,CAAC;QAG9CC;IAFF,MAAMA,MAAM,OAAO5B,kBAAkBA,iBAAiB;IACtD,MAAM6B,SACJD,6BAAAA,IAAIE,OAAO,CAACnC,cAAc,YAA1BiC,6BAA8B1B,YAAY0B,IAAIG,OAAO,CAAC,gBAAgB;IACxE,IAAIF,UAAUzB,WAAW;QACvB,OAAOL,OAAOiC,IAAI;IACpB;IAEA,MAAMC,SAAS,OAAOvC;IACtB,MAAMgB,SAAS,OAAOuB,OAAOC,MAAM,CAACL,OAAOM,IAAI,CAACrC,OAAOsC,MAAM;IAC7D,OAAOrC,OAAOsC,GAAG,CAAC3B,QAAQD;AAC5B,GAAG;AAEH,oEAAoE,GACpE,OAAO,MAAM6B,UAAU,CAACC,WAA6Bd,aACnD3B,OAAO6B,GAAG,CAAC;QACT,MAAM,EAAEa,QAAQ,EAAEC,MAAM,EAAE,GAAGjD,gBAAgBiC;QAC7C,MAAMiB,SAAS,OAAOjD;QACtB,OAAOiD,OAAOC,MAAM,CAAC;YACnB/B,SAAS;gBAAEE,OAAOyB,UAAUzB,KAAK;YAAC;YAClC0B;YACAC;QACF;IACF,GAAG;AAEL;;;;CAIC,GACD,OAAO,MAAMG,mBAAmB,CAC9BC,MAEA/C,OAAO6B,GAAG,CAAC;QACT,MAAMY,YAAY,OAAOb;QACzB,IAAI3B,OAAO+C,MAAM,CAACP,YAAY;YAC5B,OAAO,OAAOhB;QAChB;QACA,OAAO,OAAOsB,IAAIN,UAAUjC,KAAK;IACnC,GAAG;AAEL;;;;;;;;CAQC,GACD,OAAO,MAAMyC,oBACX,CAACtB,aACD,CAAUoB,MACR/C,OAAO6B,GAAG,CAAC;YACT,MAAMY,YAAY,OAAOb;YACzB,IAAI3B,OAAO+C,MAAM,CAACP,YAAY;gBAC5B,OAAO,OAAOhB;YAChB;YAEA,IAAI,CAAE,CAAA,OAAOe,QAAQC,UAAUjC,KAAK,EAAEmB,WAAU,GAAI;gBAClD,OAAO,OAAOD,UAAUC;YAC1B;YAEA,OAAO,OAAOoB,IAAIN,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 {\n type RequestPrincipal,\n type TokenClaims,\n TokenServiceTag,\n} from '@entifix/business';\nimport { ACCESS_COOKIE } from '@entifix/core';\nimport { Effect, Option } from 'effect';\nimport { HttpServerRequest } from 'effect/http';\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/**\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 */\nexport const resolveRequestPrincipal = 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/** Whether the policy lets `principal` do what `permission` names. */\nexport const permits = (principal: RequestPrincipal, permission: Permission) =>\n Effect.gen(function* () {\n const { resource, action } = parsePermission(permission);\n const policy = yield* PolicyDecisionTag;\n return policy.decide({\n subject: { roles: principal.roles },\n resource,\n action,\n });\n });\n"],"names":["parsePermission","PolicyDecisionTag","TokenServiceTag","ACCESS_COOKIE","Effect","Option","HttpServerRequest","bearerToken","authorization","undefined","scheme","value","split","toLowerCase","claimsToPrincipal","claims","userId","subject","sessionId","roles","organizationId","activeOrganizationId","partyRole","partyId","expiresAt","exp","entitlements","attributes","resolveRequestPrincipal","gen","req","token","cookies","headers","none","tokens","verify","pipe","option","map","permits","principal","permission","resource","action","policy","decide"],"mappings":"AAAA,SACEA,eAAe,EAEfC,iBAAiB,QACZ,iBAAiB;AACxB,SAGEC,eAAe,QACV,oBAAoB;AAC3B,SAASC,aAAa,QAAQ,gBAAgB;AAC9C,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AACxC,SAASC,iBAAiB,QAAQ,cAAc;AAEhD,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;QAiBXA;WAjBsD;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;QACzDiB,YAAY,GAAEX,uBAAAA,OAAOW,YAAY,YAAnBX,uBAAuB,EAAE;QACvC,2EAA2E;QAC3E,0CAA0C;QAC1CY,YAAY,CAAC;IACf;;AAEA;;;;;CAKC,GACD,OAAO,MAAMC,0BAA0BxB,OAAOyB,GAAG,CAAC;QAG9CC;IAFF,MAAMA,MAAM,OAAOxB,kBAAkBA,iBAAiB;IACtD,MAAMyB,SACJD,6BAAAA,IAAIE,OAAO,CAAC7B,cAAc,YAA1B2B,6BAA8BvB,YAAYuB,IAAIG,OAAO,CAAC,gBAAgB;IACxE,IAAIF,UAAUtB,WAAW;QACvB,OAAOJ,OAAO6B,IAAI;IACpB;IAEA,MAAMC,SAAS,OAAOjC;IACtB,MAAMa,SAAS,OAAOoB,OAAOC,MAAM,CAACL,OAAOM,IAAI,CAACjC,OAAOkC,MAAM;IAC7D,OAAOjC,OAAOkC,GAAG,CAACxB,QAAQD;AAC5B,GAAG;AAEH,oEAAoE,GACpE,OAAO,MAAM0B,UAAU,CAACC,WAA6BC,aACnDtC,OAAOyB,GAAG,CAAC;QACT,MAAM,EAAEc,QAAQ,EAAEC,MAAM,EAAE,GAAG5C,gBAAgB0C;QAC7C,MAAMG,SAAS,OAAO5C;QACtB,OAAO4C,OAAOC,MAAM,CAAC;YACnB7B,SAAS;gBAAEE,OAAOsB,UAAUtB,KAAK;YAAC;YAClCwB;YACAC;QACF;IACF,GAAG"}
@@ -1,6 +1,4 @@
1
- import { type Permission, ServiceCrossingPolicyTag } from '@entifix/authz';
2
- import { Context, Effect } from 'effect';
3
- import { HttpServerRequest } from 'effect/http';
1
+ import { Context } from 'effect';
4
2
  /**
5
3
  * The header carrying the crossing secret.
6
4
  *
@@ -26,85 +24,16 @@ export declare const CROSSING_TOKEN_HEADER = "x-crossing-token";
26
24
  * that authorizes.
27
25
  */
28
26
  export declare const ORGANIZATION_HEADER = "x-organization-id";
29
- /**
30
- * The header a saga dispatch carries its command id in — what a participant
31
- * dedupes a redelivered command on, and what its unit of work claims.
32
- */
33
- export declare const COMMAND_ID_HEADER = "x-command-id";
34
27
  declare const ServiceCrossingTokenTag_base: Context.ServiceClass<ServiceCrossingTokenTag, "ServiceCrossingTokenTag", string>;
35
28
  /**
36
29
  * The crossing secret this service expects, provided at the composition root
37
30
  * from its own configuration.
38
31
  *
39
- * A `Context.Tag` rather than an environment read, which is the difference from
40
- * {@link requireServiceToken}: the value is a per-service secret held in
32
+ * A `Context.Tag` rather than an environment read: the value is a per-service secret held in
41
33
  * config-service as an `is_secret` row, so it arrives through the same boot
42
34
  * fetch as `mongo.uri` and can be rotated without redeploying a container.
43
35
  */
44
36
  export declare class ServiceCrossingTokenTag extends ServiceCrossingTokenTag_base {
45
37
  }
46
- /**
47
- * Guard a **service-to-service** tenant crossing: the second — and only other —
48
- * way a request resolves the organization it acts for.
49
- *
50
- * The first is {@link requireOrganization}, which reads the session's
51
- * `activeOrganizationId` and is the only *user-facing* resolution. This one
52
- * exists because a platform-plane caller sometimes acts for an organization the
53
- * principal is not a member of: checkout reserving a vendor's stock, where the
54
- * organization comes from the **item** and a buyer's session carries none — and
55
- * never will, since making a buyer a member of every vendor they buy from would
56
- * be a far worse breach than the problem it solved.
57
- *
58
- * There is no third path, no fallback and no operator branch. A request
59
- * satisfying neither guard simply never reaches a tenant handle. An operator
60
- * reaching into a tenant is a *different* mechanism — a person choosing an
61
- * organization, which needs a human's permission, a time box and a record of
62
- * the crossing — and does not belong in this guard.
63
- *
64
- * ⚠️ **This guard reads no cookie and no `Authorization` header, and that is
65
- * the design.** A route guarded here accepts the crossing token and nothing
66
- * else: two accepted credentials on one route means the weaker one is the
67
- * security level. It matters concretely — `super-admin` holds `*:*:*`, which
68
- * matches every crossing permission, so a route that also took a session would
69
- * be reachable by an operator's browser tab.
70
- *
71
- * Three checks, in this order, so nothing is revealed before fleet membership is
72
- * proven:
73
- *
74
- * 1. the token, compared in constant time → `401`;
75
- * 2. the permission, against `ServiceCrossingPolicyTag` → `403`. The token
76
- * proves the caller is the fleet; it does not say what the caller may do, and
77
- * fleet membership is not a capability;
78
- * 3. the organization header, non-blank → `400`.
79
- *
80
- * **The residual, stated rather than argued away**: a shared secret
81
- * means any process holding it can name any organization. What bounds it is the
82
- * permission above, the fact that only the slices needing it are configured with
83
- * the key, and the request log. What would remove it is an RS256 service token
84
- * carrying a scope claim, which is named work rather than a gap nobody noticed.
85
- */
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
- /**
88
- * The same fleet check, for a participant that has **no organization to name**.
89
- *
90
- * ⚠️ **A platform-plane store is the whole difference.** `requireServiceCrossing`
91
- * above ends with an organization header because it is about to resolve a tenant
92
- * database handle from it, and a blank one there would read some other vendor's
93
- * storage. order-service names one database at boot, so there is no handle to
94
- * choose — and demanding a header nothing consumes would be theatre that a
95
- * caller learns to satisfy with any value.
96
- *
97
- * What is unchanged, and is the part that matters: the token proves the caller
98
- * is the fleet, the host's `ServiceCrossingPolicy` says what the fleet may do,
99
- * and **no session is accepted**. A saga step is not a person's act — the buyer
100
- * behind a checkout holds no grant over the order the coordinator is writing on
101
- * their behalf, and accepting their session here would make the weaker
102
- * credential the security level.
103
- *
104
- * The recorded residual carries over verbatim: a shared secret means any process
105
- * holding it can act, bounded by the permission and by which slices are
106
- * configured with the key.
107
- */
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
38
  export {};
110
39
  //# 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":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAE3E,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAKhD;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,qBAAqB,CAAC;AAExD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,mBAAmB,sBAAsB,CAAC;AAEvD;;;GAGG;AACH,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;;AAEhD;;;;;;;;GAQG;AACH,qBAAa,uBAAwB,SAAQ,4BAGf;CAAG;AAmBjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,eAAO,MAAM,sBAAsB,GAChC,YAAY,UAAU,MACtB,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,cAAc,EAAE,MAAM,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
+ {"version":3,"file":"require-service-crossing.d.ts","sourceRoot":"","sources":["../../src/auth/require-service-crossing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,qBAAqB,CAAC;AAExD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,mBAAmB,sBAAsB,CAAC;;AAEvD;;;;;;;GAOG;AACH,qBAAa,uBAAwB,SAAQ,4BAGf;CAAG"}
@@ -1,9 +1,4 @@
1
- import { ServiceCrossingPolicyTag } from '@entifix/authz';
2
- import { Forbidden, Invalid, Unauthenticated } from '@entifix/core';
3
- import { Context, Effect } from 'effect';
4
- import { HttpServerRequest } from 'effect/http';
5
- import { refuse } from './failures.js';
6
- import { tokenMatches } from './shared-token.js';
1
+ import { Context } from 'effect';
7
2
  /**
8
3
  * The header carrying the crossing secret.
9
4
  *
@@ -27,124 +22,14 @@ import { tokenMatches } from './shared-token.js';
27
22
  * the caller is the fleet, so the input the caller controls is never the input
28
23
  * that authorizes.
29
24
  */ export const ORGANIZATION_HEADER = 'x-organization-id';
30
- /**
31
- * The header a saga dispatch carries its command id in — what a participant
32
- * dedupes a redelivered command on, and what its unit of work claims.
33
- */ export const COMMAND_ID_HEADER = 'x-command-id';
34
25
  /**
35
26
  * The crossing secret this service expects, provided at the composition root
36
27
  * from its own configuration.
37
28
  *
38
- * A `Context.Tag` rather than an environment read, which is the difference from
39
- * {@link requireServiceToken}: the value is a per-service secret held in
29
+ * A `Context.Tag` rather than an environment read: the value is a per-service secret held in
40
30
  * config-service as an `is_secret` row, so it arrives through the same boot
41
31
  * fetch as `mongo.uri` and can be rotated without redeploying a container.
42
32
  */ export class ServiceCrossingTokenTag extends Context.Service()('ServiceCrossingTokenTag') {
43
33
  }
44
- const unauthenticated = refuse(new Unauthenticated());
45
- const forbidden = (permission)=>refuse(new Forbidden({
46
- permission
47
- }));
48
- const organizationRequired = refuse(new Invalid({
49
- errors: [
50
- {
51
- pointer: `/headers/${ORGANIZATION_HEADER}`,
52
- detail: `${ORGANIZATION_HEADER} is required`,
53
- code: 'organizationRequired'
54
- }
55
- ]
56
- }));
57
- /**
58
- * Guard a **service-to-service** tenant crossing: the second — and only other —
59
- * way a request resolves the organization it acts for.
60
- *
61
- * The first is {@link requireOrganization}, which reads the session's
62
- * `activeOrganizationId` and is the only *user-facing* resolution. This one
63
- * exists because a platform-plane caller sometimes acts for an organization the
64
- * principal is not a member of: checkout reserving a vendor's stock, where the
65
- * organization comes from the **item** and a buyer's session carries none — and
66
- * never will, since making a buyer a member of every vendor they buy from would
67
- * be a far worse breach than the problem it solved.
68
- *
69
- * There is no third path, no fallback and no operator branch. A request
70
- * satisfying neither guard simply never reaches a tenant handle. An operator
71
- * reaching into a tenant is a *different* mechanism — a person choosing an
72
- * organization, which needs a human's permission, a time box and a record of
73
- * the crossing — and does not belong in this guard.
74
- *
75
- * ⚠️ **This guard reads no cookie and no `Authorization` header, and that is
76
- * the design.** A route guarded here accepts the crossing token and nothing
77
- * else: two accepted credentials on one route means the weaker one is the
78
- * security level. It matters concretely — `super-admin` holds `*:*:*`, which
79
- * matches every crossing permission, so a route that also took a session would
80
- * be reachable by an operator's browser tab.
81
- *
82
- * Three checks, in this order, so nothing is revealed before fleet membership is
83
- * proven:
84
- *
85
- * 1. the token, compared in constant time → `401`;
86
- * 2. the permission, against `ServiceCrossingPolicyTag` → `403`. The token
87
- * proves the caller is the fleet; it does not say what the caller may do, and
88
- * fleet membership is not a capability;
89
- * 3. the organization header, non-blank → `400`.
90
- *
91
- * **The residual, stated rather than argued away**: a shared secret
92
- * means any process holding it can name any organization. What bounds it is the
93
- * permission above, the fact that only the slices needing it are configured with
94
- * the key, and the request log. What would remove it is an RS256 service token
95
- * carrying a scope claim, which is named work rather than a gap nobody noticed.
96
- */ export const requireServiceCrossing = (permission)=>(use)=>// The return type is inferred rather than written out, for the reason
97
- // `requireServiceToken` records: `HttpServerResponse.json` contributes an
98
- // `HttpBodyError` to the failure channel, and spelling the type out while
99
- // omitting it is what makes the declaration emit fail invisibly.
100
- Effect.gen(function*() {
101
- var _request_headers_ORGANIZATION_HEADER;
102
- const request = yield* HttpServerRequest.HttpServerRequest;
103
- const expected = yield* ServiceCrossingTokenTag;
104
- if (!tokenMatches(request.headers[CROSSING_TOKEN_HEADER], expected)) {
105
- return yield* unauthenticated;
106
- }
107
- const crossing = yield* ServiceCrossingPolicyTag;
108
- if (!crossing.allows(permission)) {
109
- return yield* forbidden(permission);
110
- }
111
- const organizationId = (_request_headers_ORGANIZATION_HEADER = request.headers[ORGANIZATION_HEADER]) == null ? void 0 : _request_headers_ORGANIZATION_HEADER.trim();
112
- if (organizationId === undefined || organizationId === '') {
113
- return yield* organizationRequired;
114
- }
115
- return yield* use(organizationId);
116
- });
117
- /**
118
- * The same fleet check, for a participant that has **no organization to name**.
119
- *
120
- * ⚠️ **A platform-plane store is the whole difference.** `requireServiceCrossing`
121
- * above ends with an organization header because it is about to resolve a tenant
122
- * database handle from it, and a blank one there would read some other vendor's
123
- * storage. order-service names one database at boot, so there is no handle to
124
- * choose — and demanding a header nothing consumes would be theatre that a
125
- * caller learns to satisfy with any value.
126
- *
127
- * What is unchanged, and is the part that matters: the token proves the caller
128
- * is the fleet, the host's `ServiceCrossingPolicy` says what the fleet may do,
129
- * and **no session is accepted**. A saga step is not a person's act — the buyer
130
- * behind a checkout holds no grant over the order the coordinator is writing on
131
- * their behalf, and accepting their session here would make the weaker
132
- * credential the security level.
133
- *
134
- * The recorded residual carries over verbatim: a shared secret means any process
135
- * holding it can act, bounded by the permission and by which slices are
136
- * configured with the key.
137
- */ export const requireCrossing = (permission)=>(route)=>Effect.gen(function*() {
138
- const request = yield* HttpServerRequest.HttpServerRequest;
139
- const expected = yield* ServiceCrossingTokenTag;
140
- if (!tokenMatches(request.headers[CROSSING_TOKEN_HEADER], expected)) {
141
- return yield* unauthenticated;
142
- }
143
- const crossing = yield* ServiceCrossingPolicyTag;
144
- if (!crossing.allows(permission)) {
145
- return yield* forbidden(permission);
146
- }
147
- return yield* route;
148
- });
149
34
 
150
35
  //# sourceMappingURL=require-service-crossing.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/require-service-crossing.ts"],"sourcesContent":["import { 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';\nimport { tokenMatches } from './shared-token.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\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 (!tokenMatches(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 (!tokenMatches(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":["ServiceCrossingPolicyTag","Forbidden","Invalid","Unauthenticated","Context","Effect","HttpServerRequest","refuse","tokenMatches","CROSSING_TOKEN_HEADER","ORGANIZATION_HEADER","COMMAND_ID_HEADER","ServiceCrossingTokenTag","Service","unauthenticated","forbidden","permission","organizationRequired","errors","pointer","detail","code","requireServiceCrossing","use","gen","request","expected","headers","crossing","allows","organizationId","trim","undefined","requireCrossing","route"],"mappings":"AAAA,SAA0BA,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;AACvC,SAASC,YAAY,QAAQ,oBAAoB;AAEjD;;;;;;;;;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,gCAAgCR,QAAQS,OAAO,GAGxD;AAA4B;AAEhC,MAAMC,kBAAkBP,OAAO,IAAIJ;AAEnC,MAAMY,YAAY,CAACC,aACjBT,OAAO,IAAIN,UAAU;QAAEe;IAAW;AAEpC,MAAMC,uBAAuBV,OAC3B,IAAIL,QAAQ;IACVgB,QAAQ;QACN;YACEC,SAAS,CAAC,SAAS,EAAET,qBAAqB;YAC1CU,QAAQ,GAAGV,oBAAoB,YAAY,CAAC;YAC5CW,MAAM;QACR;KACD;AACH;AAGF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuCC,GACD,OAAO,MAAMC,yBACX,CAACN,aACD,CAAUO,MACR,sEAAsE;QACtE,0EAA0E;QAC1E,0EAA0E;QAC1E,iEAAiE;QACjElB,OAAOmB,GAAG,CAAC;gBAacC;YAZvB,MAAMA,UAAU,OAAOnB,kBAAkBA,iBAAiB;YAC1D,MAAMoB,WAAW,OAAOd;YAExB,IAAI,CAACJ,aAAaiB,QAAQE,OAAO,CAAClB,sBAAsB,EAAEiB,WAAW;gBACnE,OAAO,OAAOZ;YAChB;YAEA,MAAMc,WAAW,OAAO5B;YACxB,IAAI,CAAC4B,SAASC,MAAM,CAACb,aAAa;gBAChC,OAAO,OAAOD,UAAUC;YAC1B;YAEA,MAAMc,kBAAiBL,uCAAAA,QAAQE,OAAO,CAACjB,oBAAoB,qBAApCe,qCAAsCM,IAAI;YACjE,IAAID,mBAAmBE,aAAaF,mBAAmB,IAAI;gBACzD,OAAO,OAAOb;YAChB;YAEA,OAAO,OAAOM,IAAIO;QACpB,GAAG;AAEP;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,MAAMG,kBACX,CAACjB,aACD,CAAUkB,QACR7B,OAAOmB,GAAG,CAAC;YACT,MAAMC,UAAU,OAAOnB,kBAAkBA,iBAAiB;YAC1D,MAAMoB,WAAW,OAAOd;YAExB,IAAI,CAACJ,aAAaiB,QAAQE,OAAO,CAAClB,sBAAsB,EAAEiB,WAAW;gBACnE,OAAO,OAAOZ;YAChB;YAEA,MAAMc,WAAW,OAAO5B;YACxB,IAAI,CAAC4B,SAASC,MAAM,CAACb,aAAa;gBAChC,OAAO,OAAOD,UAAUC;YAC1B;YAEA,OAAO,OAAOkB;QAChB,GAAG"}
1
+ {"version":3,"sources":["../../src/auth/require-service-crossing.ts"],"sourcesContent":["import { Context } from 'effect';\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 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: 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"],"names":["Context","CROSSING_TOKEN_HEADER","ORGANIZATION_HEADER","ServiceCrossingTokenTag","Service"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AAEjC;;;;;;;;;CASC,GACD,OAAO,MAAMC,wBAAwB,mBAAmB;AAExD;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,sBAAsB,oBAAoB;AAEvD;;;;;;;CAOC,GACD,OAAO,MAAMC,gCAAgCH,QAAQI,OAAO,GAGxD;AAA4B"}
@@ -1,5 +1,3 @@
1
- import { Effect } from 'effect';
2
- import { HttpServerRequest } from 'effect/http';
3
1
  /**
4
2
  * A secret every caller of a route presents in one header.
5
3
  *
@@ -20,17 +18,4 @@ export interface SharedToken {
20
18
  }
21
19
  /** Constant-time comparison, so the token cannot be recovered byte by byte. */
22
20
  export declare const tokenMatches: (provided: string | undefined, expected: string) => boolean;
23
- /**
24
- * Serves `route` only to a caller presenting the shared token.
25
- *
26
- * ⚠️ This is **not** identity: every caller presents the same value, so it
27
- * proves membership of whatever group holds the secret and nothing more. It is
28
- * the right shape for a route whose readers are machines — a fleet fetching its
29
- * configuration at boot, tooling reading a service's wiring — and the wrong one
30
- * for anything a person or a browser reaches.
31
- *
32
- * Health endpoints should stay unguarded: a probe cannot hold a credential, and
33
- * a readiness check that needs one becomes an authentication problem.
34
- */
35
- 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>;
36
21
  //# 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":"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,+EAA+E;AAC/E,eAAO,MAAM,YAAY,GACvB,UAAU,MAAM,GAAG,SAAS,EAC5B,UAAU,MAAM,KACf,OAUF,CAAC;AAEF;;;;;;;;;;;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
+ {"version":3,"file":"shared-token.d.ts","sourceRoot":"","sources":["../../src/auth/shared-token.ts"],"names":[],"mappings":"AAEA;;;;;;;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,+EAA+E;AAC/E,eAAO,MAAM,YAAY,GACvB,UAAU,MAAM,GAAG,SAAS,EAC5B,UAAU,MAAM,KACf,OAUF,CAAC"}
@@ -1,8 +1,4 @@
1
1
  import { timingSafeEqual } from 'node:crypto';
2
- import { Unauthenticated } from '@entifix/core';
3
- import { Effect } from 'effect';
4
- import { HttpServerRequest } from 'effect/http';
5
- import { refuse } from './failures.js';
6
2
  /** Constant-time comparison, so the token cannot be recovered byte by byte. */ export const tokenMatches = (provided, expected)=>{
7
3
  // An empty credential is refused outright, on either side: two empty
8
4
  // buffers compare equal, so an unset secret would admit an empty header.
@@ -13,26 +9,5 @@ import { refuse } from './failures.js';
13
9
  // first — the length of a shared secret is not what protects it.
14
10
  return left.length === right.length && timingSafeEqual(left, right);
15
11
  };
16
- /**
17
- * Serves `route` only to a caller presenting the shared token.
18
- *
19
- * ⚠️ This is **not** identity: every caller presents the same value, so it
20
- * proves membership of whatever group holds the secret and nothing more. It is
21
- * the right shape for a route whose readers are machines — a fleet fetching its
22
- * configuration at boot, tooling reading a service's wiring — and the wrong one
23
- * for anything a person or a browser reaches.
24
- *
25
- * Health endpoints should stay unguarded: a probe cannot hold a credential, and
26
- * a readiness check that needs one becomes an authentication problem.
27
- */ export const requireSharedToken = (shared)=>(route)=>// The return type is inferred rather than written out: `HttpServerResponse.json`
28
- // contributes an `HttpBodyError` to the failure channel, and spelling the type
29
- // out while omitting it is what makes `tsc` refuse the declaration emit.
30
- Effect.gen(function*() {
31
- const request = yield* HttpServerRequest.HttpServerRequest;
32
- if (!tokenMatches(request.headers[shared.header], shared.token())) {
33
- return yield* refuse(new Unauthenticated());
34
- }
35
- return yield* route;
36
- });
37
12
 
38
13
  //# sourceMappingURL=shared-token.js.map
@@ -1 +1 @@
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. */\nexport const tokenMatches = (\n provided: string | undefined,\n expected: string,\n): 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 (!tokenMatches(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","tokenMatches","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,OAAO,MAAMC,eAAe,CAC1BC,UACAC;IAEA,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,EAAE;AAEF;;;;;;;;;;;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,aAAaa,QAAQC,OAAO,CAACJ,OAAOK,MAAM,CAAC,EAAEL,OAAOM,KAAK,KAAK;gBACjE,OAAO,OAAOjB,OAAO,IAAIH;YAC3B;YAEA,OAAO,OAAOe;QAChB,GAAG"}
1
+ {"version":3,"sources":["../../src/auth/shared-token.ts"],"sourcesContent":["import { timingSafeEqual } from 'node:crypto';\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. */\nexport const tokenMatches = (\n provided: string | undefined,\n expected: string,\n): 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"],"names":["timingSafeEqual","tokenMatches","provided","expected","undefined","left","Buffer","from","right","length"],"mappings":"AAAA,SAASA,eAAe,QAAQ,cAAc;AAqB9C,6EAA6E,GAC7E,OAAO,MAAMC,eAAe,CAC1BC,UACAC;IAEA,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,IAAIT,gBAAgBK,MAAMG;AAC/D,EAAE"}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,4 @@
1
1
  export * from './auth/index.js';
2
- export * from './entity-facet-routes.js';
3
- export * from './entity-metadata-route.js';
4
- export * from './entity-routes.js';
5
2
  export * from './http-api/index.js';
6
3
  export * from './idempotency.js';
7
4
  export * from './metadata-composition.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC"}