@anvil-di/bellows 0.0.12 → 0.0.14

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.
package/dist/authz.d.ts CHANGED
@@ -12,7 +12,8 @@ export interface AuthnResult<U = unknown> {
12
12
  export interface AuthnService<U = unknown, Scheme extends string = never> {
13
13
  identify(req: Request): AuthnResult<U> | Promise<AuthnResult<U>>;
14
14
  }
15
- export type AuthzDecision = "allow" | "deny" | "next";
15
+ /** Every service on a route must return `"allow"`; the first `"deny"` responds 403. */
16
+ export type AuthzDecision = "allow" | "deny";
16
17
  export interface AuthzService {
17
18
  authorize(req: Request, user: unknown): AuthzDecision | Promise<AuthzDecision>;
18
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"authz.d.ts","sourceRoot":"","sources":["../src/authz.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAEvC,MAAM,WAAW,WAAW,CAAC,CAAC,GAAG,OAAO;IACtC,UAAU,EAAE,OAAO,CAAC;IACpB,IAAI,CAAC,EAAE,CAAC,CAAC;CACV;AAED;;;;;GAKG;AACH,MAAM,WAAW,YAAY,CAAC,CAAC,GAAG,OAAO,EAAE,MAAM,SAAS,MAAM,GAAG,KAAK;IACtE,QAAQ,CAAC,GAAG,EAAE,OAAO,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;CAClE;AAED,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;AAEtD,MAAM,WAAW,YAAY;IAC3B,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,GAAG,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;CAChF;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC"}
1
+ {"version":3,"file":"authz.d.ts","sourceRoot":"","sources":["../src/authz.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAEvC,MAAM,WAAW,WAAW,CAAC,CAAC,GAAG,OAAO;IACtC,UAAU,EAAE,OAAO,CAAC;IACpB,IAAI,CAAC,EAAE,CAAC,CAAC;CACV;AAED;;;;;GAKG;AACH,MAAM,WAAW,YAAY,CAAC,CAAC,GAAG,OAAO,EAAE,MAAM,SAAS,MAAM,GAAG,KAAK;IACtE,QAAQ,CAAC,GAAG,EAAE,OAAO,GAAG,WAAW,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC;CAClE;AAED,uFAAuF;AACvF,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,MAAM,CAAC;AAE7C,MAAM,WAAW,YAAY;IAC3B,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,GAAG,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;CAChF;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI,CAAC,CAAC"}
package/dist/routes.d.ts CHANGED
@@ -38,15 +38,14 @@ export interface RouteDefinition {
38
38
  */
39
39
  authn?: AuthnService[];
40
40
  /**
41
- * Ordered authorization cascade from `@Authz(...)` decorators (class-level
42
- * first, then method-level), run only after authn succeeds (or when no
43
- * `authn` is declared). The first non-`"next"` decision wins. When this is
44
- * non-empty and every service returns `"next"` (or one returns `"deny"`),
45
- * the route fails closed with 403 — undeclared means no authz check runs.
41
+ * Authorization checks from `@Authz(...)` decorators (class-level first,
42
+ * then method-level), run after authn and the `postAuthn` hooks. Every
43
+ * service must return `"allow"`; the first `"deny"` responds 403 and later
44
+ * services aren't consulted. Undeclared means no authz check runs.
46
45
  */
47
46
  authz?: AuthzService[];
48
47
  /**
49
- * Ordered middleware run after authn/authz and before `handler`, from
48
+ * Ordered middleware run after authz and before `handler`, from
50
49
  * `@Middleware(...)` decorators (class-level first, then method-level). A
51
50
  * middleware that doesn't call `next()` short-circuits the request —
52
51
  * standard Express semantics.
@@ -61,18 +60,18 @@ export interface BellowsHooks {
61
60
  /** Runs after the response has been sent, for every request. */
62
61
  onResponse?: (req: Request, res: Response) => void;
63
62
  /**
64
- * Global middleware injected into every route's chain after its authn/authz
65
- * cascade and before its own `middleware` and handler, so it can read the
66
- * identified `res.locals.user`. Routes declaring no `authn`/`authz` run it
67
- * too — `res.locals.user` is simply unset there. Unlike `onRequest` this
63
+ * Global middleware injected into every route's chain after authn and
64
+ * before authz, so it can read the identified `res.locals.user` and
65
+ * `authorize()` runs inside whatever it sets up. Routes declaring no
66
+ * `authn` run it too, with `res.locals.user` unset. Unlike `onRequest` this
68
67
  * can't be a `router.use`: router-level middleware runs ahead of every
69
- * route's auth handler, not after it.
68
+ * route's authn.
70
69
  */
71
- postAuth?: RequestHandler | RequestHandler[];
70
+ postAuthn?: RequestHandler | RequestHandler[];
72
71
  /**
73
72
  * Error-handling middleware registered after all routes, so an `HttpError`
74
- * thrown (or passed to `next`) by any route's auth handler, middleware, or
75
- * handler is converted to a response — Express 5 forwards rejected
73
+ * thrown (or passed to `next`) by any route's `identify()`, `authorize()`,
74
+ * middleware, or handler is converted to a response — Express 5 forwards rejected
76
75
  * promises from async handlers automatically. Defaults to `errorHandler`
77
76
  * from `./errors.js`, which only ever intercepts its own `HttpError` —
78
77
  * anything else it forwards via `next(err)` rather than responding, so it
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAgB,EACd,MAAM,EACN,KAAK,mBAAmB,EACxB,KAAK,OAAO,EACZ,KAAK,cAAc,EACnB,KAAK,QAAQ,EACd,MAAM,SAAS,CAAC;AACjB,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAG7D,OAAO,CAAC,MAAM,CAAC;IAC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G;IACH,SAAS,CAAC,EAAE,cAAc,GAAG,cAAc,EAAE,CAAC;IAC9C;;;;;;;;;;;OAWG;IACH,YAAY,CAAC,EAAE,mBAAmB,GAAG,KAAK,CAAC;CAC5C;AAED,gFAAgF;AAChF,wBAAgB,aAAa,CAAC,MAAM,EAAE,QAAQ,CAAC,eAAe,CAAC,EAAE,KAAK,GAAE,YAAiB,GAAG,MAAM,CA6CjG"}
package/dist/routes.js CHANGED
@@ -1,52 +1,41 @@
1
1
  import express, { Router, } from "express";
2
2
  import { errorHandler } from "./errors.js";
3
- /**
4
- * Build the combined authn → authz `RequestHandler` for a route, or
5
- * `undefined` when neither is declared (so undeclared routes are unaffected).
6
- */
7
- function buildAuthHandler(authn = [], authz = []) {
8
- if (authn.length === 0 && authz.length === 0) {
9
- return undefined;
10
- }
3
+ /** Runs an async handler body, passing a thrown error or rejection to `next`. */
4
+ function forwardErrors(body) {
11
5
  return (req, res, next) => {
12
- void (async () => {
13
- let user;
14
- if (authn.length > 0) {
15
- let identified = false;
16
- for (const service of authn) {
17
- const result = await service.identify(req);
18
- if (result.identified) {
19
- identified = true;
20
- user = result.user;
21
- break;
22
- }
23
- }
24
- if (!identified) {
25
- res.status(401).json({ error: "unauthorized" });
26
- return;
27
- }
6
+ body(req, res).then((proceed) => {
7
+ if (proceed)
8
+ next();
9
+ }, (err) => next(err));
10
+ };
11
+ }
12
+ function buildAuthnHandler(authn = []) {
13
+ if (authn.length === 0)
14
+ return undefined;
15
+ return forwardErrors(async (req, res) => {
16
+ for (const service of authn) {
17
+ const result = await service.identify(req);
18
+ if (result.identified) {
19
+ res.locals.user = result.user;
20
+ return true;
28
21
  }
29
- if (authz.length > 0) {
30
- let allowed = false;
31
- for (const service of authz) {
32
- const decision = await service.authorize(req, user);
33
- if (decision === "allow") {
34
- allowed = true;
35
- break;
36
- }
37
- if (decision === "deny") {
38
- break;
39
- }
40
- }
41
- if (!allowed) {
42
- res.status(403).json({ error: "forbidden" });
43
- return;
44
- }
22
+ }
23
+ res.status(401).json({ error: "unauthorized" });
24
+ return false;
25
+ });
26
+ }
27
+ function buildAuthzHandler(authz = []) {
28
+ if (authz.length === 0)
29
+ return undefined;
30
+ return forwardErrors(async (req, res) => {
31
+ for (const service of authz) {
32
+ if ((await service.authorize(req, res.locals.user)) !== "allow") {
33
+ res.status(403).json({ error: "forbidden" });
34
+ return false;
45
35
  }
46
- res.locals.user = user;
47
- next();
48
- })();
49
- };
36
+ }
37
+ return true;
38
+ });
50
39
  }
51
40
  /**
52
41
  * Build the body-parser `RequestHandler` for a route's `bodyParser` kind. All
@@ -108,17 +97,19 @@ export function bellowsRoutes(routes, hooks = {}) {
108
97
  next();
109
98
  });
110
99
  }
111
- const postAuth = hooks.postAuth
112
- ? Array.isArray(hooks.postAuth)
113
- ? hooks.postAuth
114
- : [hooks.postAuth]
100
+ const postAuthn = hooks.postAuthn
101
+ ? Array.isArray(hooks.postAuthn)
102
+ ? hooks.postAuthn
103
+ : [hooks.postAuthn]
115
104
  : [];
116
105
  for (const route of routes) {
117
- const authHandler = buildAuthHandler(route.authn, route.authz);
106
+ const authnHandler = buildAuthnHandler(route.authn);
107
+ const authzHandler = buildAuthzHandler(route.authz);
118
108
  const handlers = [
119
109
  ...(route.bodyParser ? [bodyParserMiddleware(route.bodyParser)] : []),
120
- ...(authHandler ? [authHandler] : []),
121
- ...postAuth,
110
+ ...(authnHandler ? [authnHandler] : []),
111
+ ...postAuthn,
112
+ ...(authzHandler ? [authzHandler] : []),
122
113
  ...(route.middleware ?? []),
123
114
  route.handler,
124
115
  ];
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EACd,MAAM,GAKP,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA8D3C;;;GAGG;AACH,SAAS,gBAAgB,CACvB,QAAwB,EAAE,EAC1B,QAAwB,EAAE;IA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AM;YAC7D,KAAK,KAAK;gBAAK,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,QAAQ,CAAC,CAAC;gBAAI,MAAM;YAC7D,KAAK,QAAQ;gBAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,QAAQ,CAAC,CAAC;gBAAC,MAAM;YAC7D,KAAK,OAAO;gBAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,QAAQ,CAAC,CAAC;gBAAE,MAAM;QAC/D,CAAC;IACH,CAAC;IAED,IAAI,KAAK,CAAC,YAAY,KAAK,KAAK,EAAE,CAAC;QACjC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,YAAY,CAAC,CAAC;IACjD,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anvil-di/bellows",
3
- "version": "0.0.12",
3
+ "version": "0.0.14",
4
4
  "description": "Runtime types and decorator stubs for anvil-bellows NestJS-style controller codegen.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -18,7 +18,7 @@
18
18
  "src"
19
19
  ],
20
20
  "dependencies": {
21
- "@anvil-di/bellows-cli": "0.0.12"
21
+ "@anvil-di/bellows-cli": "0.0.14"
22
22
  },
23
23
  "peerDependencies": {
24
24
  "express": ">=4"
package/src/authz.ts CHANGED
@@ -15,7 +15,8 @@ export interface AuthnService<U = unknown, Scheme extends string = never> {
15
15
  identify(req: Request): AuthnResult<U> | Promise<AuthnResult<U>>;
16
16
  }
17
17
 
18
- export type AuthzDecision = "allow" | "deny" | "next";
18
+ /** Every service on a route must return `"allow"`; the first `"deny"` responds 403. */
19
+ export type AuthzDecision = "allow" | "deny";
19
20
 
20
21
  export interface AuthzService {
21
22
  authorize(req: Request, user: unknown): AuthzDecision | Promise<AuthzDecision>;
@@ -18,7 +18,7 @@ class NoopAuthn implements AuthnService<{ id: string }, "bearerAuth"> {
18
18
 
19
19
  class NoopAuthz implements AuthzService {
20
20
  authorize(): AuthzDecision {
21
- return "next";
21
+ return "allow";
22
22
  }
23
23
  }
24
24
 
package/src/index.test.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import path from "node:path";
2
3
  import http from "node:http";
3
4
  import type { AddressInfo } from "node:net";
@@ -676,7 +677,7 @@ describe("bellowsRoutes authn/authz", () => {
676
677
  () => (identified ? { identified: true, user } : { identified: false });
677
678
 
678
679
  const authorize =
679
- (decision: "allow" | "deny" | "next"): AuthzService["authorize"] =>
680
+ (decision: "allow" | "deny"): AuthzService["authorize"] =>
680
681
  () => decision;
681
682
 
682
683
  it("no authn/authz declared: request passes through unchanged", async () => {
@@ -748,13 +749,13 @@ describe("bellowsRoutes authn/authz", () => {
748
749
  }
749
750
  });
750
751
 
751
- it("authz declared, none allow: 403, handler not called", async () => {
752
+ it("authz declared, a service denies: 403, handler not called", async () => {
752
753
  let handlerCalled = false;
753
754
  const routes: RouteDefinition[] = [
754
755
  {
755
756
  method: "GET",
756
757
  path: "/x",
757
- authz: [{ authorize: authorize("next") }],
758
+ authz: [{ authorize: authorize("deny") }],
758
759
  handler: (_req, res) => {
759
760
  handlerCalled = true;
760
761
  res.json({ ok: true });
@@ -771,12 +772,19 @@ describe("bellowsRoutes authn/authz", () => {
771
772
  }
772
773
  });
773
774
 
774
- it("authz declared, a service allows: handler runs", async () => {
775
+ it("authz declared, every service allows: each is consulted in order, handler runs", async () => {
776
+ const calls: string[] = [];
777
+ const allowing = (name: string): AuthzService => ({
778
+ authorize: () => {
779
+ calls.push(name);
780
+ return "allow";
781
+ },
782
+ });
775
783
  const routes: RouteDefinition[] = [
776
784
  {
777
785
  method: "GET",
778
786
  path: "/x",
779
- authz: [{ authorize: authorize("next") }, { authorize: authorize("allow") }],
787
+ authz: [allowing("class"), allowing("method")],
780
788
  handler: (_req, res) => res.json({ ok: true }),
781
789
  },
782
790
  ];
@@ -784,6 +792,74 @@ describe("bellowsRoutes authn/authz", () => {
784
792
  try {
785
793
  const res = await fetch(`${url}/x`);
786
794
  expect(res.status).toBe(200);
795
+ expect(calls).toEqual(["class", "method"]);
796
+ } finally {
797
+ await close();
798
+ }
799
+ });
800
+
801
+ it("authz declared, an earlier service allows and a later one denies: 403", async () => {
802
+ let handlerCalled = false;
803
+ const routes: RouteDefinition[] = [
804
+ {
805
+ method: "GET",
806
+ path: "/x",
807
+ authz: [{ authorize: authorize("allow") }, { authorize: authorize("deny") }],
808
+ handler: (_req, res) => {
809
+ handlerCalled = true;
810
+ res.json({ ok: true });
811
+ },
812
+ },
813
+ ];
814
+ const { url, close } = await serve(routes);
815
+ try {
816
+ const res = await fetch(`${url}/x`);
817
+ expect(res.status).toBe(403);
818
+ expect(handlerCalled).toBe(false);
819
+ } finally {
820
+ await close();
821
+ }
822
+ });
823
+
824
+ it("an error thrown by identify() reaches the error handler", async () => {
825
+ const routes: RouteDefinition[] = [
826
+ {
827
+ method: "GET",
828
+ path: "/x",
829
+ authn: [
830
+ {
831
+ identify: () => {
832
+ throw new ForbiddenError("not a member");
833
+ },
834
+ },
835
+ ],
836
+ handler: (_req, res) => res.json({ ok: true }),
837
+ },
838
+ ];
839
+ const { url, close } = await serve(routes);
840
+ try {
841
+ const res = await fetch(`${url}/x`);
842
+ expect(res.status).toBe(403);
843
+ expect(await res.json()).toEqual({ error: "Forbidden", message: "not a member" });
844
+ } finally {
845
+ await close();
846
+ }
847
+ });
848
+
849
+ it("a rejection from authorize() reaches the error handler", async () => {
850
+ const routes: RouteDefinition[] = [
851
+ {
852
+ method: "GET",
853
+ path: "/x",
854
+ authz: [{ authorize: () => Promise.reject(new NotFoundError("no such practice")) }],
855
+ handler: (_req, res) => res.json({ ok: true }),
856
+ },
857
+ ];
858
+ const { url, close } = await serve(routes);
859
+ try {
860
+ const res = await fetch(`${url}/x`);
861
+ expect(res.status).toBe(404);
862
+ expect(await res.json()).toEqual({ error: "Not Found", message: "no such practice" });
787
863
  } finally {
788
864
  await close();
789
865
  }
@@ -914,10 +990,10 @@ describe("bellowsRoutes authn/authz", () => {
914
990
  });
915
991
  });
916
992
 
917
- // --- bellowsRoutes: postAuth global middleware ---
993
+ // --- bellowsRoutes: postAuthn global middleware ---
918
994
 
919
- describe("bellowsRoutes postAuth", () => {
920
- it("runs after the authn cascade, in order, before route middleware", async () => {
995
+ describe("bellowsRoutes postAuthn", () => {
996
+ it("runs after the authn cascade, in order, before authz and route middleware", async () => {
921
997
  const calls: string[] = [];
922
998
  let seenUser: unknown;
923
999
  const routes: RouteDefinition[] = [
@@ -932,6 +1008,14 @@ describe("bellowsRoutes postAuth", () => {
932
1008
  },
933
1009
  },
934
1010
  ],
1011
+ authz: [
1012
+ {
1013
+ authorize: () => {
1014
+ calls.push("authz");
1015
+ return "allow";
1016
+ },
1017
+ },
1018
+ ],
935
1019
  middleware: [
936
1020
  (_req, _res, next) => {
937
1021
  calls.push("middleware");
@@ -945,29 +1029,61 @@ describe("bellowsRoutes postAuth", () => {
945
1029
  },
946
1030
  ];
947
1031
  const { url, close } = await serve(routes, {
948
- postAuth: [
1032
+ postAuthn: [
949
1033
  (_req, res, next) => {
950
- calls.push("postAuth:1");
1034
+ calls.push("postAuthn:1");
951
1035
  seenUser = res.locals.user;
952
1036
  next();
953
1037
  },
954
1038
  (_req, _res, next) => {
955
- calls.push("postAuth:2");
1039
+ calls.push("postAuthn:2");
956
1040
  next();
957
1041
  },
958
1042
  ],
959
1043
  });
960
1044
  try {
961
1045
  await fetch(`${url}/x`);
962
- expect(calls).toEqual(["authn", "postAuth:1", "postAuth:2", "middleware", "handler"]);
1046
+ expect(calls).toEqual(["authn", "postAuthn:1", "postAuthn:2", "authz", "middleware", "handler"]);
963
1047
  expect(seenUser).toEqual({ id: "u1" });
964
1048
  } finally {
965
1049
  await close();
966
1050
  }
967
1051
  });
968
1052
 
1053
+ it("authz runs inside async context the hook opens", async () => {
1054
+ const scope = new AsyncLocalStorage<string>();
1055
+ let seen: string | undefined;
1056
+ const routes: RouteDefinition[] = [
1057
+ {
1058
+ method: "GET",
1059
+ path: "/x",
1060
+ authn: [{ identify: () => ({ identified: true, user: { id: "u1" } }) }],
1061
+ authz: [
1062
+ {
1063
+ authorize: async () => {
1064
+ await Promise.resolve();
1065
+ seen = scope.getStore();
1066
+ return "allow";
1067
+ },
1068
+ },
1069
+ ],
1070
+ handler: (_req, res) => res.json({ ok: true }),
1071
+ },
1072
+ ];
1073
+ const { url, close } = await serve(routes, {
1074
+ postAuthn: (_req, _res, next) => scope.run("request-1", next),
1075
+ });
1076
+ try {
1077
+ const res = await fetch(`${url}/x`);
1078
+ expect(res.status).toBe(200);
1079
+ expect(seen).toBe("request-1");
1080
+ } finally {
1081
+ await close();
1082
+ }
1083
+ });
1084
+
969
1085
  it("never runs when authn rejects the request", async () => {
970
- let postAuthCalled = false;
1086
+ let postAuthnCalled = false;
971
1087
  const routes: RouteDefinition[] = [
972
1088
  {
973
1089
  method: "GET",
@@ -977,15 +1093,15 @@ describe("bellowsRoutes postAuth", () => {
977
1093
  },
978
1094
  ];
979
1095
  const { url, close } = await serve(routes, {
980
- postAuth: (_req, _res, next) => {
981
- postAuthCalled = true;
1096
+ postAuthn: (_req, _res, next) => {
1097
+ postAuthnCalled = true;
982
1098
  next();
983
1099
  },
984
1100
  });
985
1101
  try {
986
1102
  const res = await fetch(`${url}/x`);
987
1103
  expect(res.status).toBe(401);
988
- expect(postAuthCalled).toBe(false);
1104
+ expect(postAuthnCalled).toBe(false);
989
1105
  } finally {
990
1106
  await close();
991
1107
  }
@@ -1004,15 +1120,15 @@ describe("bellowsRoutes postAuth", () => {
1004
1120
  },
1005
1121
  ];
1006
1122
  const { url, close } = await serve(routes, {
1007
- postAuth: (_req, _res, next) => {
1008
- calls.push("postAuth");
1123
+ postAuthn: (_req, _res, next) => {
1124
+ calls.push("postAuthn");
1009
1125
  next();
1010
1126
  },
1011
1127
  });
1012
1128
  try {
1013
1129
  const res = await fetch(`${url}/x`);
1014
1130
  expect(res.status).toBe(200);
1015
- expect(calls).toEqual(["postAuth", "handler"]);
1131
+ expect(calls).toEqual(["postAuthn", "handler"]);
1016
1132
  } finally {
1017
1133
  await close();
1018
1134
  }
@@ -1031,7 +1147,7 @@ describe("bellowsRoutes postAuth", () => {
1031
1147
  },
1032
1148
  ];
1033
1149
  const { url, close } = await serve(routes, {
1034
- postAuth: (_req, res) => {
1150
+ postAuthn: (_req, res) => {
1035
1151
  res.status(429).json({ error: "too_many_requests" });
1036
1152
  },
1037
1153
  });
package/src/routes.ts CHANGED
@@ -51,15 +51,14 @@ export interface RouteDefinition {
51
51
  */
52
52
  authn?: AuthnService[];
53
53
  /**
54
- * Ordered authorization cascade from `@Authz(...)` decorators (class-level
55
- * first, then method-level), run only after authn succeeds (or when no
56
- * `authn` is declared). The first non-`"next"` decision wins. When this is
57
- * non-empty and every service returns `"next"` (or one returns `"deny"`),
58
- * the route fails closed with 403 — undeclared means no authz check runs.
54
+ * Authorization checks from `@Authz(...)` decorators (class-level first,
55
+ * then method-level), run after authn and the `postAuthn` hooks. Every
56
+ * service must return `"allow"`; the first `"deny"` responds 403 and later
57
+ * services aren't consulted. Undeclared means no authz check runs.
59
58
  */
60
59
  authz?: AuthzService[];
61
60
  /**
62
- * Ordered middleware run after authn/authz and before `handler`, from
61
+ * Ordered middleware run after authz and before `handler`, from
63
62
  * `@Middleware(...)` decorators (class-level first, then method-level). A
64
63
  * middleware that doesn't call `next()` short-circuits the request —
65
64
  * standard Express semantics.
@@ -68,56 +67,46 @@ export interface RouteDefinition {
68
67
  handler: (req: Request, res: Response) => void | Promise<void>;
69
68
  }
70
69
 
71
- /**
72
- * Build the combined authn → authz `RequestHandler` for a route, or
73
- * `undefined` when neither is declared (so undeclared routes are unaffected).
74
- */
75
- function buildAuthHandler(
76
- authn: AuthnService[] = [],
77
- authz: AuthzService[] = [],
78
- ): RequestHandler | undefined {
79
- if (authn.length === 0 && authz.length === 0) {
80
- return undefined;
81
- }
70
+ /** Runs an async handler body, passing a thrown error or rejection to `next`. */
71
+ function forwardErrors(
72
+ body: (req: Request, res: Response) => Promise<boolean>,
73
+ ): RequestHandler {
82
74
  return (req, res, next) => {
83
- void (async () => {
84
- let user: unknown;
85
- if (authn.length > 0) {
86
- let identified = false;
87
- for (const service of authn) {
88
- const result = await service.identify(req);
89
- if (result.identified) {
90
- identified = true;
91
- user = result.user;
92
- break;
93
- }
94
- }
95
- if (!identified) {
96
- res.status(401).json({ error: "unauthorized" });
97
- return;
98
- }
75
+ body(req, res).then(
76
+ (proceed) => {
77
+ if (proceed) next();
78
+ },
79
+ (err: unknown) => next(err),
80
+ );
81
+ };
82
+ }
83
+
84
+ function buildAuthnHandler(authn: AuthnService[] = []): RequestHandler | undefined {
85
+ if (authn.length === 0) return undefined;
86
+ return forwardErrors(async (req, res) => {
87
+ for (const service of authn) {
88
+ const result = await service.identify(req);
89
+ if (result.identified) {
90
+ res.locals.user = result.user;
91
+ return true;
99
92
  }
100
- if (authz.length > 0) {
101
- let allowed = false;
102
- for (const service of authz) {
103
- const decision = await service.authorize(req, user);
104
- if (decision === "allow") {
105
- allowed = true;
106
- break;
107
- }
108
- if (decision === "deny") {
109
- break;
110
- }
111
- }
112
- if (!allowed) {
113
- res.status(403).json({ error: "forbidden" });
114
- return;
115
- }
93
+ }
94
+ res.status(401).json({ error: "unauthorized" });
95
+ return false;
96
+ });
97
+ }
98
+
99
+ function buildAuthzHandler(authz: AuthzService[] = []): RequestHandler | undefined {
100
+ if (authz.length === 0) return undefined;
101
+ return forwardErrors(async (req, res) => {
102
+ for (const service of authz) {
103
+ if ((await service.authorize(req, res.locals.user)) !== "allow") {
104
+ res.status(403).json({ error: "forbidden" });
105
+ return false;
116
106
  }
117
- res.locals.user = user;
118
- next();
119
- })();
120
- };
107
+ }
108
+ return true;
109
+ });
121
110
  }
122
111
 
123
112
  /**
@@ -174,18 +163,18 @@ export interface BellowsHooks {
174
163
  /** Runs after the response has been sent, for every request. */
175
164
  onResponse?: (req: Request, res: Response) => void;
176
165
  /**
177
- * Global middleware injected into every route's chain after its authn/authz
178
- * cascade and before its own `middleware` and handler, so it can read the
179
- * identified `res.locals.user`. Routes declaring no `authn`/`authz` run it
180
- * too — `res.locals.user` is simply unset there. Unlike `onRequest` this
166
+ * Global middleware injected into every route's chain after authn and
167
+ * before authz, so it can read the identified `res.locals.user` and
168
+ * `authorize()` runs inside whatever it sets up. Routes declaring no
169
+ * `authn` run it too, with `res.locals.user` unset. Unlike `onRequest` this
181
170
  * can't be a `router.use`: router-level middleware runs ahead of every
182
- * route's auth handler, not after it.
171
+ * route's authn.
183
172
  */
184
- postAuth?: RequestHandler | RequestHandler[];
173
+ postAuthn?: RequestHandler | RequestHandler[];
185
174
  /**
186
175
  * Error-handling middleware registered after all routes, so an `HttpError`
187
- * thrown (or passed to `next`) by any route's auth handler, middleware, or
188
- * handler is converted to a response — Express 5 forwards rejected
176
+ * thrown (or passed to `next`) by any route's `identify()`, `authorize()`,
177
+ * middleware, or handler is converted to a response — Express 5 forwards rejected
189
178
  * promises from async handlers automatically. Defaults to `errorHandler`
190
179
  * from `./errors.js`, which only ever intercepts its own `HttpError` —
191
180
  * anything else it forwards via `next(err)` rather than responding, so it
@@ -212,18 +201,20 @@ export function bellowsRoutes(routes: Iterable<RouteDefinition>, hooks: BellowsH
212
201
  });
213
202
  }
214
203
 
215
- const postAuth = hooks.postAuth
216
- ? Array.isArray(hooks.postAuth)
217
- ? hooks.postAuth
218
- : [hooks.postAuth]
204
+ const postAuthn = hooks.postAuthn
205
+ ? Array.isArray(hooks.postAuthn)
206
+ ? hooks.postAuthn
207
+ : [hooks.postAuthn]
219
208
  : [];
220
209
 
221
210
  for (const route of routes) {
222
- const authHandler = buildAuthHandler(route.authn, route.authz);
211
+ const authnHandler = buildAuthnHandler(route.authn);
212
+ const authzHandler = buildAuthzHandler(route.authz);
223
213
  const handlers: RequestHandler[] = [
224
214
  ...(route.bodyParser ? [bodyParserMiddleware(route.bodyParser)] : []),
225
- ...(authHandler ? [authHandler] : []),
226
- ...postAuth,
215
+ ...(authnHandler ? [authnHandler] : []),
216
+ ...postAuthn,
217
+ ...(authzHandler ? [authzHandler] : []),
227
218
  ...(route.middleware ?? []),
228
219
  route.handler,
229
220
  ];